Unittest tests order

后端 未结 19 1315
刺人心
刺人心 2020-12-01 03:17

How do I be sure of the unittest methods order? Is the alphabetical or numeric prefixes the proper way?

class TestFoo(TestCase):
    def test_1(self):
               


        
19条回答
  •  误落风尘
    2020-12-01 03:57

    I half agree with the idea that tests souldn't be ordered. In some cases it helps (it's easier damn it!) to have them in order... after all that's the reason for the 'unit' in UnitTest.

    That said one alternative is to use mock objects to mockout and patch the items that should run before that specific code under test. You can also put a dummy function in there to monkey patch your code. For more info check out Mock, which is part of the standard library now. Mock

    Here are some YouTube videos if you haven't used Mock before.

    Video 1

    Video 2

    Video 3

    More to the point, try using class methods to structure your code, then place all the class methods in one main test method.

    import unittest
    import sqlite3
    
    class MyOrderedTest(unittest.TestCase):
    
        @classmethod
        def setUpClass(cls):
            cls.create_db()
            cls.setup_draft()
            cls.draft_one()
            cls.draft_two()
            cls.draft_three()
    
        @classmethod
        def create_db(cls):
            cls.conn = sqlite3.connect(":memory:")
    
        @classmethod
        def setup_draft(cls):
            cls.conn.execute("CREATE TABLE players ('draftid' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'first', 'last')")
    
        @classmethod
        def draft_one(cls):
            player = ("Hakeem", "Olajuwon")
            cls.conn.execute("INSERT INTO players (first, last) VALUES (?, ?)", player)
    
        @classmethod
        def draft_two(cls):
            player = ("Sam", "Bowie")
            cls.conn.execute("INSERT INTO players (first, last) VALUES (?, ?)", player)
    
        @classmethod
        def draft_three(cls):
            player = ("Michael", "Jordan")
            cls.conn.execute("INSERT INTO players (first, last) VALUES (?, ?)", player)
    
        def test_unordered_one(self):
            cur = self.conn.execute("SELECT * from players")
            draft = [(1, u'Hakeem', u'Olajuwon'), (2, u'Sam', u'Bowie'), (3, u'Michael', u'Jordan')]
            query = cur.fetchall()
            print query
            self.assertListEqual(query, draft)
    
        def test_unordered_two(self):
            cur = self.conn.execute("SELECT first, last FROM players WHERE draftid=3")
            result = cur.fetchone()
            third = " ".join(result)
            print third
            self.assertEqual(third, "Michael Jordan")
    

提交回复
热议问题