mardi 2 février 2016

Nosetests: testcases influence each other [duplicate]

This question already has an answer here:

My nosetests version is 1.3.7 and my python version is 3.5.1

Minimal working example: let's develop a class that implements directed graphs. Start with just enough code to be able to add an edge:

class DiGraph:
    def __init__(self, edges={}):
        self.edges = edges

    def add_edge(self, n1, n2):
        if n1 not in self.edges: self.edges[n1] = []
        if n2 not in self.edges: self.edges[n2] = []

        self.edges[n1].append(n2)

Let's test this simple skeleton with nosetests:

class TestDiGraph:
    def test_add_edge_0(self):
        g = DiGraph()
        g.add_edge(0, 1)

        assert g.edges[0] == [1]
        assert g.edges[1] == []

    def test_add_edge_1(self):
        g = DiGraph()
        g.add_edge(0, 2)
        g.add_edge(0, 2)

        assert g.edges[0] == [2, 2], g.edges
        assert g.edges[2] == []

For me the console output of nosetests test_graph.py:TestDiGraph looks like this:

.F
======================================================================
FAIL: algos.tests.test_graph.TestDiGraph.test_add_edge_1
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python3.5/site-packages/nose/case.py", line 198, in runTest
    self.test(*self.arg)
  File "/home/alex/Code/algos/tests/test_graph.py", line 53, in test_add_edge_1
    assert g.edges[0] == [2, 2], g.edges
AssertionError: {0: [1, 2, 2], 1: [], 2: []}

You can clearly see that node 1 from test_add_edge_0 got leaked into test_add_edge_1, causing it to fail.

Here are my other observations:

  • Each test method succeeds on its own, i.e. if I delete the other test method and run nosetests.
  • If I delete the edges={} argument from __init__ and set it manually with self.edges = {}, both tests pass together.

What am I missing? Why does the test data leak?

Aucun commentaire:

Enregistrer un commentaire