defprint_path(): print(f'os.getcwd() is {os.getcwd()}') print(f'sys.path[0] is {sys.path[0]}') print(f'sys.argv[0] is {sys.argv[0]}') print(f'__file__ is {__file__}') print(f'os.path.dirname(__file__) is {os.path.dirname(__file__)}') print(f'os.path.abspath(__file__) is {os.path.abspath(__file__)}') print(f'os.path.realpath(__file__) is {os.path.realpath(__file__)}') print(f'os.path.split(os.path.realpath(__file__))[0] is {os.path.split(os.path.realpath(__file__))[0]}')
------ module_a/getpath.py ------ os.getcwd() is /Users/vk/tmp/path sys.path[0] is /Users/vk/tmp/path/module_a sys.argv[0] is module_a/getpath.py __file__ is module_a/getpath.py os.path.dirname(__file__) is module_a os.path.abspath(__file__) is /Users/vk/tmp/path/module_a/getpath.py os.path.realpath(__file__) is /Users/vk/tmp/path/module_a/getpath.py os.path.split(os.path.realpath(__file__))[0] is /Users/vk/tmp/path/module_a --------------------------------- ------ module_a/module_b/getpath.py ------ os.getcwd() is /Users/vk/tmp/path sys.path[0] is /Users/vk/tmp/path/module_a sys.argv[0] is module_a/getpath.py __file__ is /Users/vk/tmp/path/module_a/module_b/getpath.py os.path.dirname(__file__) is /Users/vk/tmp/path/module_a/module_b os.path.abspath(__file__) is /Users/vk/tmp/path/module_a/module_b/getpath.py os.path.realpath(__file__) is /Users/vk/tmp/path/module_a/module_b/getpath.py os.path.split(os.path.realpath(__file__))[0] is /Users/vk/tmp/path/module_a/module_b ------------------------------------------
deftest_split(self): s = 'hello world' self.assertEqual(s.split(), ['hello', 'world']) # check that s.split fails when the separator is not a string with self.assertRaises(TypeError): s.split(2)
if __name__ == '__main__': unittest.main()
继承 unittest.TestCase 就创建了一个测试样例。上述三个独立的测试是三个类的方法,这些方法的命名都以 test 开头。 这个命名约定告诉测试运行者类的哪些方法表示测试。
@retry(retry_on_exception=if_value_error, stop_max_attempt_number=3, wait_random_min=1000, wait_random_max=3000) defrun(): value = random.randint(0, 10) msg = f'value is {value}' print(msg) if value <= 5: raise ValueError('value is too small!') else: raise Exception('value is too large!')
if __name__ == '__main__': run()
当函数run抛出ValueError异常时,则进行重试;抛出Exception异常时,不会重试。
指定返回值重试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
from retrying import retry import random
defif_return_small(value): return value <= 5
@retry(retry_on_result=if_return_small, stop_max_attempt_number=3, wait_random_min=1000, wait_random_max=3000) defrun(): value = random.randint(0, 10) msg = f'value is {value}' print(msg) return value