首页
登录 | 注册

看了几天unittest,看的头晕,却感觉没啥心得

发现了1点,继承自unittest.TestCase 的subclass 不能重写__init__()方法。
setUp()和tearDown():会被每个test函数调用。每个test函数是按照字母排序,所以我在test_run_process后用了test_s2.
被测试的函数定义在此:



  1. class Calculate:
  2.     def add(self,x,y):
  3.         if type(x)==int and type(y)==int:
  4.             return x+y
  5.         else:
  6.             raise TypeError("Invalid type: {} and {}".format(type(x),type(y)))
test文件在这里:

  1. import numbers
  2. import unittest
  3. from calculate import Calculate
  4. import sys
  5. import subprocess
  6. import shutil
  7. import os
  8. import os.path
  9. import time
  10. import filecmp

  11. class TestCalculate(unittest.TestCase):
  12.     def setUp(self):
  13.         self.calc=Calculate()

  14.     @unittest.skip("demonstrating skipping")
  15.     def test_nothing(self):
  16.         self.fail("should not happen")

  17.     @unittest.skipIf(sys.version_info<(3,6),"not supported in this library version")
  18.     def test_format(self):
  19.         # Tests that work for only a certain version of the library
  20.         pass
  21.     
  22.     @unittest.skipUnless(sys.platform.startswith('win'),"requires windows")
  23.     def test_windows_support(self):
  24.         #windows specific testing code
  25.         pass


  26.     def test_add_method_returns_correct_result(self):
  27.         self.assertEqual(4,self.calc.add(2,2))
  28.     
  29.     def test_add_method_raises_typerror_if_not_int(self):
  30.         self.assertRaises(TypeError,self.calc.add,"Hello","world")
  31.     
  32.     def test_assert_raises(self):
  33.         with self.assertRaises(AttributeError):
  34.             [].get
  35.     
  36.     #assertEqaul(x,y,msg=None)
  37.     def test_assert_equal(self):
  38.         self.assertEqual(1,2,msg="we not are equal")
  39.     
  40.     #assertAlsmotEqual(x,y,places=None,msg=None,delta=None)
  41.     def test_assert_almost_equal_delta_0_5(self):
  42.         self.assertAlmostEqual(1,1.2,delta=0.5,msg="we are not almost equal")

  43.     def test_assert_almost_equal_places(self):
  44.         self.assertAlmostEqual(1,1.00001, places=4)
  45.     
  46.     #assertRaises(exception,method,arguments,msg=None)
  47.     def test_assert_raises_2(self):
  48.         self.assertRaises(ValueError,int, 'a')
  49.     
  50.     #assertDictContainsSubset is deprecated in python 3.2
  51.     #assertDictContainsSubset(expected, actual, msg=None)
  52.     @unittest.skipIf(sys.version_info>(3,2),"not supported in this library version")
  53.     def test_assert_dict_contains_subset(self):
  54.         expected={'a':'b',"k":"g"}
  55.         actual={'a':'b','c':'d','e':'f'}
  56.         self.assertDictContainsSubset(expected,actual,msg="not contain")
  57.     
  58.     #assertDictEqual(d1,d2,msg=None)
  59.     def test_assert_dict_equal(self):
  60.         expected={'a':'b',"k":"g"}
  61.         actual={'a':'b',"k":'g'}
  62.         self.assertDictEqual(expected,actual)
  63.     
  64.     #assertTrue(exper,msg=None)
  65.     def test_assert_true(self):
  66.         self.assertTrue(1)
  67.         self.assertTrue("hello world")
  68.     
  69.     def test_assert_true_2(self):
  70.         d1=dict(a=1,b=2,c=3,d=4)
  71.         d2=dict(a=1,b=2)
  72.         self.assertTrue(set(d2.items()).issubset(set(d1.items())))

  73.     #assertGreater(a,b,msg=None):
  74.     def test_assert_greater(self):
  75.         self.assertGreater(2,1,msg="smaller")

  76.     
  77.     #assertGreaterEqual(a,b,msg=None)
  78.     def test_assert_greater_equal(self):
  79.         self.assertGreaterEqual(2,2)

  80.     
  81.     #assertIn(member,container,msg=None)
  82.     def test_assert_in(self):
  83.         self.assertIn(1,[1,2,3,4,5])
  84.     
  85.     #assertIs(expr1,expr2)
  86.     def test_assert_is(self):
  87.         self.assertIs("a","a")

  88.     #assertIsInstance(obj, class, msg=None):
  89.     def test_assert_is_instance(self):
  90.         self.assertIsInstance(1,numbers.Integral)

  91.     #assertNotIsInstance(obj,class, msg=None)
  92.     def test_assert_is_not_instance(self):
  93.         self.assertNotIsInstance(1,str)

  94.     #assertIsNone(obj, msg=None)
  95.     def test_assert_is_none(self):
  96.         self.assertIsNone(None)

  97.     #assertIsNot(expr1,expr2,msg=None)
  98.     def test_assert_is_not(self):
  99.         self.assertIsNot([],[])

  100.     #assertIsNotNone(obj,msg=None)
  101.     def test_assert_is_not_none(self):
  102.         self.assertIsNotNone(1)

  103.     #assertLess(a,b,msg=None)
  104.     def test_assert_less(self):
  105.         self.assertLess(1,2)

  106.     #assertLessEqual(a,b,msg=None)
  107.     def test_assert_less_equal(self):
  108.         self.assertLessEqual(1,2)
  109.     
  110.     #This function not exits in python3
  111.     #assertItemsEqual(a,b,msg=None):
  112.     @unittest.skipIf(sys.version_info>(3,0),"not supported in this library version")
  113.     def test_assert_items_equal(self):
  114.         try:
  115.             self.assertItemsEqual([1,2,3],[3,2,1])
  116.         except AttributeError as e:
  117.             print(e)

  118.     #assertRaises(exeClass,callableObj, *args, **kwargs, msg=None)
  119.     def test_assert_raises(self):
  120.         self.assertRaises(IndexError,[].pop,0)
  121.     

  122. @unittest.skip("showing class skipping")
  123. class MySkippingTestCase(unittest.TestCase):
  124.     """
  125.     def __init__(self):
  126.         unittest.TestCase.__init__(*args,**kwargs)
  127.     """
  128.     
  129.     def setUp(self):
  130.         self.a="5 is a good number"
  131.         self.b=self.test_run_3_post_condition()
  132.         #self.c=self.test_run_process_file()
  133.         #self.d=self.test_run_process2()
  134.         pass


  135.     def test_not_run(self):
  136.         pass
  137.     """
  138.     def skipUnlessHasattr(obj,attr):
  139.         if hasattr(obj,attr):
  140.             return labda func: func
  141.         return unittest.skip("{!r} does not have {!r}".format(obj, attr))
  142.     """

  143.     def test_run_3_post_condition(self):
  144.         for i in range(1,100):
  145.             if i==5:
  146.                 return "{} is a good number".format(i)
  147.         return "{} is a good number".format(5)
  148.     
  149.     def test_run_1(self):
  150.         self.assertEqual(self.a,self.b)

  151.     def test_run_2(self):
  152.         self.assertTrue(self.a!=self.b,"thould be equal")

  153.     
  154.     def test_rename_file(self):
  155.         #ret=os.rename("echo.sh","echo")
  156.         self.assertTrue(os.path.exists("echo.sh"))

  157.     def test_final(self):
  158.         self.assertEqual(self.test_run_process_1(),self.test_run_process_2())
  159.     
  160. import difflib
  161. class MyTest(unittest.TestCase):
  162.     """
  163.     def __init__(self):
  164.         super().__init__()
  165.     """

  166.     def setUp(self):
  167.         pass

  168.     def test_run_process_1(self):
  169.         proc=subprocess.Popen("./echo.sh",stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  170.         sout,serr=proc.communicate()
  171.         stdout=sout.decode().strip()
  172.         with open("time_begin.txt","wt") as tb:
  173.             tb.write(stdout)
  174.         return True
  175.     
  176.     def test_run_process_2(self):
  177.         time.sleep(5)
  178.         proc=subprocess.Popen("./echo.sh",stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  179.         sout,serr=proc.communicate()
  180.         stdout=sout.decode().strip()
  181.         with open("time_finish.txt","wt") as tb:
  182.             tb.write(stdout)
  183.         return True
  184.     
  185.     #def test_s1(self):
  186.     # self.assertEqual(self.test_run_process_1(),self.test_run_process_2())
  187.     
  188.     def test_s2(self):
  189.         with open("time_begin.txt") as f1:
  190.             fromlines=f1.readlines()
  191.         with open("time_finish.txt") as f2:
  192.             tolines=f2.readlines()
  193.         diff=difflib.unified_diff(fromlines,tolines)
  194.         sys.stdout.writelines(diff)

  195.     def test_s3(self):
  196.         self.assertFalse(filecmp.cmp("time_begin.txt","time_finish.txt"))

  197. if __name__=="__main__":
  198.     #unittest.main() -verbosity 2
  199.     suite=unittest.TestLoader().loadTestsFromTestCase(MyTest)
  200.     unittest.TextTestRunner(verbosity=2).run(suite)
以前C语言还要先test 传进去的参数呢,python 这些测试框架整的够复杂的,方法真多。真的是有用还是语法糖太多啊,哎。搞不清楚。


相关文章

  • 原文已删除
  • Python热潮一直蒸蒸日上,在各大领域里程序语言均占首位,所以学习python的人数也越来越多,却迟迟没有很大的成就,由于python本身应用的领域太多,涉及方方面面的书籍也很多,因此小编推荐一些比较好的python书给大家,希望对你们有 ...
  • 学习Java和其他技术的资源其实非常多,但是我们需要取其精华去其糟粕,选择那些最好的,最适合我们的,同时也要由浅入深,先易后难.基于这样的一个标准,我在这里为大家提供一份Java的学习资源清单. 一:Java入门学习资源 这里主要推荐的是几 ...
  • 之前写了些比较底层的东西,马上就要写redis当中是如何使用这些底层来实现数据结构的,突然之间想到,应该先简单介绍下各个数据结构的命令,之后再进行实现的分析,如果读者已经对redis命令很熟悉了,就不需要再继续往下看了,等下一篇出来直接看就 ...
  • 内核中的UDP socket流程(3)--sock_create作者:gfree.wind@gmail.com原文:http://blog.chinaunix.net/space.php?uid=23629988&do=blog&a ...
  • 本文的copyleft归gfree.wind@gmail.com所有,使用GPL发布,可以自由拷贝,转载.但转载请保持文档的完整性,注明原作者及原链接,严禁用于任何商业用途. 作者:gfree.wind@gmail.com 博客:linux ...

2020 unjeep.com webmaster#unjeep.com
12 q. 0.012 s.
京ICP备10005923号