unit test_sandbox提供了一个@sandbox decorator,确保单元测试方法在测试执行期间不会发出任何socket/web请求。
unittest_sandbox的Python项目详细描述
unit test沙盒提供了一个@sandbox decorator来确保单元测试 方法在测试执行期间不发出任何socket/web请求。注: 这目前只适用于python 3。
安装
安装运行:pip install unittest_sandbox
示例用法
fromunittestimportTestCaseimportrequestsfromunittest_sandboximportInternetAccessBlockedException,sandbox# The @sandbox() decorator can be applied to methods individually like belowclassRequestTests(TestCase):deftest_non_request_works(self):self.assertEqual(1+1,2)@sandbox()deftest_web_request_raises_exception_when_sandbox_decorator_is_applied(self):# If a web request is sent in a test method wrapped with the @sandbox decorator,# an InternetAccessBlockedException will be raised.withself.assertRaises(InternetAccessBlockedException):requests.get('https://www.google.com')# The @sandbox() decorator can also be applied to the class as a whole. This is the same as decorating# all 'test_' methods with @sandbox()@sandbox()classRequestTests(TestCase):deftest_non_request_works(self):self.assertEqual(1+1,2)deftest_web_request_raises_exception_when_sandbox_decorator_is_applied(self):# If a web request is sent in a test method wrapped with the @sandbox decorator,# an InternetAccessBlockedException will be raised.withself.assertRaises(InternetAccessBlockedException):requests.get('https://www.google.com')# A function can also be imported and called to prevent any web requests from occurring.# For example, this could be called at the start of a Django settings file used by the test runner to# ensure that no web requests are made by the tests.fromunittest_sandboximportblock_socket_accessblock_socket_access()