测试API创建方法时遇到错误请求400

时间:2019-07-29 11:30:09

标签: python django django-models django-rest-framework pytest

我正在尝试使用pytest测试API。我收到一个错误的请求400,我希望状态码为201。

设置测试数据的方式一定存在错误,但我不知道该在哪里。

这是我要发送的数据

graph_data =   {
        "project": "project1",
        "name": "Graph1",
        "nodes": [
            {
                "name": "Node1 of Graph 1",
                "graph": 1
            }
        ],
        "edges": [
            {
                "name": "EdgeForGraph1",
                "graph": 1,
                "source": 1,
                "target": 1
            }
        ]
    }

这是我的测试:

@pytest.mark.django_db
class TestCreate:

    def setup(self):
        """Setup for tests to create user, graph, project and node

        """

        password = 'mypassword'
        username = 'testuser'
        project  = Project.objects.create(project_name='project1')
        graph    = Graph.objects.create(project=project, name='Graph1')
        node = Node.objects.create(graph=graph, name='node of Graph')
        source = Node.objects.create(graph=graph)
        target = Node.objects.create(graph=graph)
        user = User.objects.create_superuser(username=username, email='test@test.com',
                                             password=password)
        edge = Edge.objects.create(graph=graph, source=source, target=target)


    def test_aut_user_can_create_graph(self, client):
        headers = get_token(client)
        print(headers)
        create_data = graph_data
        print(create_data)
        url = api_reverse('create-graph')
        response = client.post(url, create_data, headers=headers)

        assert response.status_code == 201


get_token方法返回用于身份验证的令牌。

这是我的模特:

class Graph(models.Model):
    project         = models.ForeignKey(Project, on_delete=models.CASCADE)
    name            = models.CharField(max_length=120, blank=True)
    description     = models.CharField(max_length=400, blank=True)

    def __str__(self):
        return self.name

    @property
    def nodes(self):
        return self.node_set.all()


    @property
    def edges(self):
        return self.edge_set.all()

class Node(models.Model):
    name            = models.CharField(max_length=120, blank=True)
    graph           = models.ForeignKey(Graph, on_delete=models.CASCADE)

    def __str__(self):
        return self.name


class Edge(models.Model):
    name            = models.CharField(max_length=120, blank=True)
    graph           = models.ForeignKey(Graph, on_delete=models.CASCADE)
    source          = models.ForeignKey(Node, on_delete=models.CASCADE, related_name='source_set')
    target          = models.ForeignKey(Node, on_delete=models.CASCADE, related_name='target_set')

也许它与edge和node的属性有关?

它总是给我400 Bad Request,而我只是不知道如何更改它。任何帮助将不胜感激。

非常感谢

0 个答案:

没有答案