代码之家  ›  专栏  ›  技术社区  ›  dark horse

Python—比较两个函数的输出的单元测试

  •  -1
  • dark horse  · 技术社区  · 6 年前

    我试图执行一个单元测试来检查两个查询的计数是否相同。

    基本.py

    import psycopg2
    
    def q1():
      dwh_connection = psycopg2.connect(connection_details)
      cur = dwh_connection.cursor()
      cur.execute("select count(*) from table_1 limit 4")
      dwh_connection.close()
    
    def q2():
      dwh_connection = psycopg2.connect(connection_details)
      cur = dwh_connection.cursor()
      cur.execute("select count(*) from table_2 limit 4")
      dwh_connection.close()
    

    编辑:

    File "/Users/PycharmProjects/unit/test_calc.py", line 10, in test_queries self.assertEqual(q1(),q2()) 
    
    NameError: name 'q1' is not defined
    

    下面是我的unittest代码

    import unittest
    import base import q1, q2
    
    
    class TestStringMethods(unittest.TestCase):
    
        def test_queries(self):
            self.assertEqual(q1(),q2())
    
    if __name__ == '__main__':
        unittest.main()
    

    代码基本.py

    import psycopg2
    
    def q1():
       dwh_connection = psycopg2.connect(conn_details)
       cur = dwh_connection.cursor()
       query = "select count(*) from tble_1;"
       cur.execute(query)
       var = cur.fetchone()
       print (var[0])
       dwh_connection.close()
    
    def q2():
       dwh_connection = psycopg2.connect(conn_details)
       cur = dwh_connection.cursor()
       query = "select count(*) from tble_2;"
       cur.execute(query)
       var = cur.fetchone()
       print (var[0])
       dwh_connection.close()
    
    q1()
    q2()
    
    The above code works just fine, if executed separately.
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   blue_note    6 年前

    import unittest
    
    class TestExample(unittest.TestCase):
    
        def test_queries(self):
            self.assertEqual(q1(), q2())
    
    if __name__ == '__main__':
        unittest.main()
    

    但是,您的函数现在不返回任何内容。把它们改成

    def q1():
       dwh_connection = psycopg2.connect(connection_details)
       cur = dwh_connection.cursor()
       result = cur.execute("""select count(*) from table_1 limit 4""").fetchone()
       dwh_connection.close()
       return result