class TestCommandTaskWithMockPopen(MockLoggerMixin, unittest.TestCase): """ Run command tasks with a mocked popen """ def setUp(self): self.global_config = BaseGlobalConfig() self.project_config = BaseProjectConfig( self.global_config, config={"noyaml": True} ) self.task_config = TaskConfig() self._task_log_handler.reset() self.task_log = self._task_log_handler.messages self.Popen = MockPopen() self.r = Replacer() self.r.replace("cumulusci.tasks.command.subprocess.Popen", self.Popen) self.addCleanup(self.r.restore) def test_functional_mock_command(self): """ Functional test that runs a command with mocked popen results and checks the log. """ self.task_config.config["options"] = {"command": "ls -la"} self.Popen.set_command("ls -la", stdout=b"testing testing 123", stderr=b"e") task = Command(self.project_config, self.task_config) task() self.assertTrue(any("testing testing" in s for s in self.task_log["info"]))
def setUp(self): self.dir = TempDirectory() self.addCleanup(self.dir.cleanup) self.Popen = MockPopen() r = Replacer() r.replace('archivist.helpers.Popen', self.Popen) self.addCleanup(r.restore)
def test_cleanup_properly(self): r = Replacer() try: m = Mock() d = mkdtemp() m.return_value = d r.replace('testfixtures.tempdirectory.mkdtemp',m) self.failUnless(os.path.exists(d)) self.assertFalse(m.called) @tempdir() def test_method(d): d.write('something', b'stuff') d.check('something', ) self.assertFalse(m.called) compare(os.listdir(d),[]) test_method() self.assertTrue(m.called) self.failIf(os.path.exists(d)) finally: r.restore() if os.path.exists(d): # only runs if the test fails! rmtree(d) # pragma: no cover
def test_replacer_del(self): r = Replacer() r.replace('testfixtures.tests.sample1.left_behind', object(), strict=False) with catch_warnings(record=True) as w: del r self.assertTrue(len(w), 1) compare(str(w[0].message), "Replacer deleted without being restored, ""originals left:" " {'testfixtures.tests.sample1.left_behind': <not_there>}")
class SavedSearchFormTests(TestCase): def setUp(self): super(SavedSearchFormTests, self).setUp() self.user = UserFactory() self.data = {'url': 'http://www.my.jobs/jobs', 'feed': 'http://www.my.jobs/jobs/feed/rss?', 'email': '*****@*****.**', 'frequency': 'D', 'label': 'All jobs from www.my.jobs', 'sort_by': 'Relevance'} self.r = Replacer() self.r.replace('urllib2.urlopen', return_file) def tearDown(self): self.r.restore() def test_successful_form(self): form = SavedSearchForm(user=self.user,data=self.data) self.assertTrue(form.is_valid()) def test_invalid_url(self): self.data['url'] = 'http://google.com' form = SavedSearchForm(user=self.user,data=self.data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'][0], 'This URL is not valid.') def test_day_of_week(self): self.data['frequency'] = 'W' form = SavedSearchForm(user=self.user,data=self.data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['day_of_week'][0], 'This field is required.') self.data['day_of_week'] = '1' form = SavedSearchForm(user=self.user,data=self.data) self.assertTrue(form.is_valid()) def test_day_of_month(self): self.data['frequency'] = 'M' form = SavedSearchForm(user=self.user,data=self.data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['day_of_month'][0], 'This field is required.') self.data['day_of_month'] = '1' form = SavedSearchForm(user=self.user,data=self.data) self.assertTrue(form.is_valid()) def test_duplicate_url(self): original = SavedSearchFactory(user=self.user) form = SavedSearchForm(user=self.user,data=self.data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'][0], 'URL must be unique.')
def test_import_and_obtain_with_lists(self): t = test_datetime(None) t.add(2002, 1, 1, 1, 0, 0) t.add(2002, 1, 1, 2, 0, 0) from testfixtures import Replacer r = Replacer() r.replace('testfixtures.tests.sample1.now', t.now) try: compare(sample1.str_now_2(), '2002-01-01 01:00:00') compare(sample1.str_now_2(), '2002-01-01 02:00:00') finally: r.restore()
def test_import_and_obtain_with_lists(self): t = test_date(None) t.add(2002, 1, 1) t.add(2002, 1, 2) from testfixtures import Replacer r = Replacer() r.replace('testfixtures.tests.sample1.today', t.today) try: compare(sample1.str_today_2(), '2002-01-01') compare(sample1.str_today_2(), '2002-01-02') finally: r.restore()
class PopenCommandsTest(unittest.TestCase): def setUp(self): self.Popen = MockPopen() self.r = Replacer() self.r.replace('swabbie.utils.command.subprocess.Popen', self.Popen) self.addCleanup(self.r.restore) def test_call_cmd(self): self.Popen.set_command('cmd1', stdout='foo') command_result = Command._call_cmd('cmd1') expected_command_result = CommandResult(output='foo', return_code=0) self.assertEqual(command_result.output, expected_command_result.output) self.assertEqual(command_result.return_code, expected_command_result.return_code) self.assertFalse(command_result.err)
class TestCheck(TestCase): def setUp(self): self.r = Replacer() self.l = LogCapture() def tearDown(self): self.l.uninstall() self.r.restore() def checker_returns(self,output): resolve = Mock() self.r.replace('checker.resolve',resolve) def the_checker(config_folder,param): return output resolve.return_value = the_checker return resolve def test_bad_checker(self): from checker import check check = should_raise(check,ImportError('No module named unknown')) check('/config','unknown',None) def test_normal(self): m = self.checker_returns('some output') check('/config','achecker',None) compare(m.call_args_list,[ (('checker.checkers.achecker.check',), {}) ]) def test_log_newline(self): self.checker_returns('some output\n') check('/config','achecker','aparam') self.l.check( ('root', 'INFO', 'some output'), ) def test_log_no_newline(self): self.checker_returns('some output') check('/config','achecker','aparam') self.l.check( ('root', 'INFO', 'some output'), ) def test_no_log_empty(self): self.checker_returns('') check('/config','achecker','aparam') self.l.check()
def setUp(self): super(SavedSearchHelperTests, self).setUp() self.user = UserFactory() self.valid_url = 'http://www.my.jobs/search?location=chicago&q=nurse' self.r = Replacer() self.r.replace('urllib2.urlopen', return_file)
def setUp(self): self.redirect_guid = JOB['guid'] self.redirect = RedirectFactory(buid=JOB['buid'], guid='{%s}' % uuid.UUID(self.redirect_guid)) self.password = '******' self.user = User.objects.create(email='*****@*****.**') self.user.set_password(self.password) self.user.save() self.contact = CompanyEmail.objects.create( buid=self.redirect.buid, email=self.user.email) self.email = self.user.email.replace('@', '%40') self.auth = { 'bad': [ '', 'Basic %s' % base64.b64encode('bad%40email:wrong_pass')], 'good': 'Basic %s' % base64.b64encode('%s:%s' % (self.user.email.\ replace('@', '%40'), self.password))} self.post_dict = {'to': '*****@*****.**', 'from': '*****@*****.**', 'text': 'This address does not contain a valid guid', 'html': '', 'subject': 'Bad Email', 'attachments': 0} self.r = Replacer() self.r.replace('pysolr.Solr.search', mock_search)
def setUp(self): self.r = Replacer() # test values for author info, requiring less setup self.r.replace('opencore.views.people.get_author_info', lambda id,request: { 'title' : 'Author title', 'country' : 'Author country', 'organization' : 'author org', 'url' : 'author-url', 'photo_url' : 'author-photo-url', }) self.r.replace('opencore.views.forms.get_current_request', lambda :self.request) self.r.replace('opencore.views.forms.authenticated_userid', lambda request:'auth_user_id') testing.cleanUp() sessions = DummySessions() context = DummyProfile(sessions=sessions, **profile_data) context.title = 'title' context.__name__='admin' context.users = DummyUsers() context.users.add('admin','admin','password',()) self.context = context request = testing.DummyRequest() request.api = get_template_api(context, request) request.context = context self.request = request
def setUp(self): super(MySearchViewTests, self).setUp() self.client = TestClient() self.user = UserFactory() self.client.login_user(self.user) self.new_form_data = { 'url': 'www.my.jobs/jobs', 'feed': 'http://www.my.jobs/jobsfeed/rss?', 'label': 'Jobs Label', 'email': self.user.email, 'frequency': 'D', 'is_active': 'True', 'sort_by': 'Relevance', } self.new_digest_data = { 'is_active': 'True', 'user': self.user, 'email': self.user.email, 'frequency': 'M', 'day_of_month': 1, } self.new_form = forms.SavedSearchForm(user=self.user, data=self.new_form_data) self.r = Replacer() self.r.replace('urllib2.urlopen', return_file)
def setUp(self): self.replacer = Replacer() self.mock_a = MagicMock() self.mock_b = MagicMock() self.replacer.replace('test_hello.RealClassA', self.mock_a) self.replacer.replace('test_hello.RealClassB', self.mock_b)
def setUp(self): self.config = { "authorize_url": "localhost:8080/goauth/authorize", "cache": {"class": "nexus.token_utils.InMemoryCache", "args": []}, "server": "graph.api.globusonline.org", "api_key": "I am not a key", "api_secret": "I am not a secret", } self.replacer = Replacer()
class TestCheck(TestCase): def setUp(self): self.r = Replacer() self.l = LogCapture() def tearDown(self): self.l.uninstall() self.r.restore() def checker_returns(self, output): resolve = Mock() self.r.replace("checker.check.resolve", resolve) def the_checker(config_folder, param): return output resolve.return_value = the_checker return resolve def test_bad_checker(self): with ShouldRaise(ImportError("No module named unknown")): check("/config", "unknown", None) def test_normal(self): m = self.checker_returns("some output") check("/config", "achecker", None) compare(m.call_args_list, [(("checker.checkers.achecker.check",), {})]) def test_log_newline(self): self.checker_returns("some output\n") check("/config", "achecker", "aparam") self.l.check(("root", "INFO", "some output")) def test_log_no_newline(self): self.checker_returns("some output") check("/config", "achecker", "aparam") self.l.check(("root", "INFO", "some output")) def test_no_log_empty(self): self.checker_returns("") check("/config", "achecker", "aparam") self.l.check()
def setUp(self): super(SavedSearchResourceTests, self).setUp() self.user = UserFactory() self.client = TestClient() self.data = {'email':'*****@*****.**', 'url':'www.my.jobs/jobs'} create_api_key(User, instance=self.user, created=True) self.credentials = (self.user.email, self.user.api_key.key) self.r = Replacer() self.r.replace('urllib2.urlopen', return_file)
class Test_handle_photo_upload(TestCase): def setUp(self): testing.cleanUp() registerContentFactory(DummyImageFile,ICommunityFile) self.cstruct = { 'fp': StringIO('some image data'), 'mimetype': 'image/jpeg', 'filename': u'test.jpg', } self.context = DummyProfile() self.authenticated_userid = Mock() self.authenticated_userid.return_value = 'auser' self.r = Replacer() self.r.replace('opencore.views.utils.authenticated_userid', self.authenticated_userid) def tearDown(self): self.r.restore() testing.cleanUp() def test_no_cstruct(self): handle_photo_upload(self.context,None,None) self.assertFalse(self.context.get('photo')) def test_no_existing_photo(self): handle_photo_upload(self.context,None,self.cstruct) content = self.context['photo'] compare(content.title,'Photo of firstname lastname') compare(content.mimetype,'image/jpeg') compare(content.filename,'test.jpg') compare(content.creator,'auser') def test_existing_photo(self): self.context['photo']=testing.DummyModel() handle_photo_upload(self.context,None,self.cstruct) content = self.context['photo'] compare(content.title,'Photo of firstname lastname') compare(content.mimetype,'image/jpeg') compare(content.filename,'test.jpg') compare(content.creator,'auser')
def setUp(self): super(SavedSearchFormTests, self).setUp() self.user = UserFactory() self.data = {'url': 'http://www.my.jobs/jobs', 'feed': 'http://www.my.jobs/jobs/feed/rss?', 'email': '*****@*****.**', 'frequency': 'D', 'label': 'All jobs from www.my.jobs', 'sort_by': 'Relevance'} self.r = Replacer() self.r.replace('urllib2.urlopen', return_file)
def setUp(self): self.r = Replacer() self.m = Mock() self.r.replace('mortar_rdb.create_engine',self.m.create_engine) self.engine = self.m.create_engine.return_value self.engine.url.password = None self.r.replace('mortar_rdb.scoped_session',self.m.scoped_session) self.ScopedSession = self.m.scoped_session.return_value self.r.replace('mortar_rdb.sessionmaker',self.m.sessionmaker) self.Session = self.m.sessionmaker.return_value self.r.replace('mortar_rdb.getSiteManager',self.m.getSiteManager) self.m.getSiteManager.return_value = self.m.registry
class TestReplacerXUnit(unittest.TestCase): def setUp(self): self.replacer = Replacer() self.mock_a = MagicMock() self.mock_b = MagicMock() self.replacer.replace('test_hello.RealClassA', self.mock_a) self.replacer.replace('test_hello.RealClassB', self.mock_b) def tearDown(self): self.replacer.restore() def test_mock(self): instance_a = RealClassA() instance_b = RealClassB() instance_a.say.return_value = 'FakeClassA' instance_b.say.return_value = 'FakeClassB' self.assertEqual(instance_a.say(), 'FakeClassA') self.assertEqual(instance_b.say(), 'FakeClassB')
def setUp(self): testing.cleanUp() registerContentFactory(DummyImageFile,ICommunityFile) self.cstruct = { 'fp': StringIO('some image data'), 'mimetype': 'image/jpeg', 'filename': u'test.jpg', } self.context = DummyProfile() self.authenticated_userid = Mock() self.authenticated_userid.return_value = 'auser' self.r = Replacer() self.r.replace('opencore.views.utils.authenticated_userid', self.authenticated_userid)
def setUp(self): self.global_config = BaseGlobalConfig() self.project_config = BaseProjectConfig( self.global_config, config={"noyaml": True} ) self.task_config = TaskConfig() self._task_log_handler.reset() self.task_log = self._task_log_handler.messages self.Popen = MockPopen() self.r = Replacer() self.r.replace("cumulusci.tasks.command.subprocess.Popen", self.Popen) self.addCleanup(self.r.restore)
def test_remove_called_twice(self): from testfixtures.tests import sample1 def test_z(): pass r = Replacer() r.replace('testfixtures.tests.sample1.z',test_z) r.restore() assert sample1.z() == 'original z' r.restore() assert sample1.z() == 'original z'
def setUp(self): self.components = TestComponents() self.r = Replacer() self.m = Mock() self.r.replace('mortar_rdb.testing.real_register_session', self.m.realRegisterSession) self.r.replace('mortar_rdb.testing.create_engine', self.m.create_engine) # mock out for certainty # self.r.replace('mortar_rdb.testing.???',Mock()) # mock out for table destruction get_session = Mock() bind = get_session.return_value.bind bind.dialect.inspector.return_value = inspector = Mock() inspector.get_table_names.return_value = () self.r.replace('mortar_rdb.testing.get_session', get_session)
def setUp(self): aws_data = { 'ServiceNamespace': 'ecs', 'ResourceId': 'service/my_cluster/my_service', 'ScalableDimension': 'ecs:service:DesiredCount', 'MinCapacity': 1, 'MaxCapacity': 3, 'RoleARN': 'my_role_arn', 'CreationTime': datetime(2017, 4, 14) } init = Mock(return_value=None) init.return_value = None appscaling_client = Mock() self.describe_scaling_targets = Mock(return_value=aws_data) appscaling_client.describe_scalable_targets = self.describe_scaling_targets client = Mock(return_value=appscaling_client) with Replacer() as r: r.replace('boto3.client', client) r.replace('deployfish.aws.appscaling.ScalingPolicy.__init__', init) self.appscaling = ApplicationAutoscaling('my_service', 'my_cluster', aws=aws_data)
def test_wagtail_admins_see_only_wagtail_images_page_2(self): request = self.wagtail_factory.get('/') request.user = get_user_model().objects.get(username='******') request.site = Site.objects.get(hostname='wagtail.flint.oursites.com') get_current_request_dummy = Dummy( default_return=Dummy(site=request.site, user=request.user)) with Replacer() as r: r.replace('wagtail_patches.monkey_patches.get_current_request', get_current_request_dummy) # Request page 2 of the listing. This code path *does* return a response that can be tested against, # so we don't use the modal workflow dummy. request.GET = QueryDict('p=2') response = patched_image_chooser(request) images = response.context_data['images'] # This time, there should be just the one remaining Wagtail Image, and nothing else. It's Image 1 because # the list is in reverse order. self.assertEqual(len(images), 1) for doc in images: self.assertEqual(doc.title, 'Wagtail Image 1')
def test_test_admins_see_only_test_images_page_1(self): request = self.wagtail_factory.get('/') request.user = get_user_model().objects.get(username='******') request.site = Site.objects.get(hostname='test.flint.oursites.com') get_current_request_dummy = Dummy( default_return=Dummy(site=request.site, user=request.user)) with Replacer() as r: r.replace('wagtail_patches.monkey_patches.render_modal_workflow', self.render_modal_workflow_dummy) r.replace('wagtail_patches.monkey_patches.get_current_request', get_current_request_dummy) patched_image_chooser(request) images = self.get_context_variable_from_render_modal_dummy( 'images') # Confirm that there are exactly 2 "Test Images" in the listing, and that they are in reverse # creation order. self.assertEqual(len(images), 2) for ndx, doc in enumerate(images): self.assertEqual(doc.title, 'Test Image {}'.format(2 - ndx))
def test_method(self): from testfixtures.tests import sample1 assert sample1.X().y() == 'original y' def test_y(self): return 'replacement y' r = Replacer() r.replace('testfixtures.tests.sample1.X.y',test_y) assert sample1.X().y()[:38] == 'replacement y' r.restore() assert sample1.X().y() == 'original y'
def test_function(self): from testfixtures.tests import sample1 assert sample1.z() == 'original z' def test_z(): return 'replacement z' r = Replacer() r.replace('testfixtures.tests.sample1.z',test_z) assert sample1.z() == 'replacement z' r.restore() assert sample1.z() == 'original z'
def test_main_verbose(self): with TempDirectory() as d: # setup db db_path = d.getpath('sqlite.db') conn = sqlite3.connect(db_path) conn.execute('create table notes (filename varchar, text varchar)') conn.commit() # setup config config = d.write( 'config.ini', ''' [main] db = %s log = %s ''' % (db_path, d.getpath('script.log')), 'ascii') # setup file to read source = d.write('test.txt', 'some text', 'ascii') with Replacer() as r: r.replace('sys.argv', ['script.py', config, source]) with OutputCapture() as output: main() output.compare("Successfully added 'test.txt'")
def test_logging(self): """ Depending on what the configuration says, logging should be using either syslog or a custom configuration file into which anything may go. """ with Replacer() as r: def _file_config(*args, **kwargs): eq_(args[0], self.log_file_config) r.replace('logging.config.fileConfig', _file_config) fork = cli.Fork(self.test_dir, self.app_ctx, False) fork.config_mod.log_file_config = self.log_file_config with patch.object(server.HTTPProxy, 'serve_forever') as mock_method: fork.run() # Clean up after the test, otherwise unrelated tests will see the # changes made to the config module. fork.config_mod.log_file_config = None
def test_create_local_user_view_GET(self): self.login('superuser') with Replacer() as r: r.replace('wagtail_patches.views.users.LocalUserCreateForm', self.form_dummy_valid) # Unlike most replacements, we can replace the module's origin here because it gets imported at runtime, # rather than being imported at load time. r.replace('wagtail.wagtailadmin.messages', self.messages_dummy) # First, test to make sure the routing works. response = self.client.get(reverse('wagtailusers_users:add_local'), HTTP_HOST=self.wagtail_site.hostname) self.assertEqual(response.status_code, 200) self.assertEqual(response.template_name, 'wagtail_patches/users/create_local.html') self.form_dummy_valid.reset_dummy() # Confirm that unpriviledged users can't access the view. self.login('wagtail_editor') response = self.client.get(reverse('wagtailusers_users:add_local'), HTTP_HOST=self.wagtail_site.hostname) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, reverse('wagtailadmin_home')) self.assertEqual(len(self.messages_dummy.error.calls), 1) # Now, the real unit test requires us to call the view function directly, since it's not # consistently possible to retrieve the request object from the output of the http testing client. request = self.wagtail_factory.get('/') request.user = self.wagtail_admin request.site = self.wagtail_site response = create_local(request) self.assertEqual(response.template_name, 'wagtail_patches/users/create_local.html') self.assertEqual(response.context_data['form'], self.form_dummy_valid.default_return) self.assertEqual(len(self.form_dummy_valid.calls), 1) self.assertEqual(self.form_dummy_valid.calls[0]['args'][0], request)
def test_image_tags_restricted_to_site_of_creation(self): request = self.wagtail_factory.get('/') request.user = get_user_model().objects.get(username='******') request.site = Site.objects.get(hostname='test.flint.oursites.com') get_current_request_dummy = Dummy( default_return=Dummy(site=request.site, user=request.user)) with Replacer() as r: r.replace('wagtail_patches.monkey_patches.render_modal_workflow', self.render_modal_workflow_dummy) r.replace('wagtail_patches.monkey_patches.get_current_request', get_current_request_dummy) patched_image_chooser(request) popular_tags = self.get_context_variable_from_render_modal_dummy( 'popular_tags') # popular_tags shoudl not contain the tag 'wagtail' because it doesn't exist # on this site self.assertTrue('wagtail' not in popular_tags.get().name) # Make sure that we did receive some tags, and not just an empty list self.assertTrue('test' in popular_tags.get().name)
def test_multiple_context_managers(self): def test_y(self): return 'test y' def test_z(): return 'test z' compare(sample1.z(), 'original z') compare(sample1.X().y(), 'original y') with Replacer() as replace: z = replace('testfixtures.tests.sample1.z', test_z) y = replace('testfixtures.tests.sample1.X.y', test_y) compare(z(), 'test z') if PY3: compare(y, sample1.X.y) compare(sample1.X().y(), 'test y') compare(sample1.z(), 'test z') compare(sample1.X().y(), 'test y') compare(sample1.z(), 'original z') compare(sample1.X().y(), 'original y')
def test__CoCoLite(): db = cq._CoCoLite(mock_func) # Test that mock_func works as expected. nt.assert_equal(db.func(None, None), None) nt.assert_equal(db.func('Mapping', 'A'), 'xml Mapping A xml') # Test selection when cache has no matching entries (select_xml). nt.assert_raises(IndexError, db.select_xml, 'Mapping', 'A') # Test insertion (__call__, select_xml, and func). nt.assert_equal(db('Mapping', 'A'), 'xml Mapping A xml') # Test selection when cache has one matching entry (select_xml). nt.assert_equal(db.select_xml('Mapping', 'A'), 'xml Mapping A xml') # Test selection with __call__, mocking select_xml. with Replacer() as r: mock_select_xml = lambda self, s, b: 'stuff' r.replace('cocotools.query._CoCoLite.select_xml', mock_select_xml) nt.assert_equal(db('Mapping', 'A'), 'stuff') # Test selection when cache has multiple matching entries # (select_xml). db.con.execute(""" INSERT INTO cache VALUES ('A', 'Mapping', 'entry #2') """) nt.assert_raises(sqlite3.IntegrityError, db.select_xml, 'Mapping', 'A')
def test_main_exception(self): with TempDirectory() as d: from testfixtures import OutputCapture # setup db db_path = d.getpath('sqlite.db') conn = sqlite3.connect(db_path) # don't create the table so we get at exception conn.commit() # setup config config = d.write( 'config.ini', ''' [main] db = %s log = %s ''' % (db_path, d.getpath('script.log')), 'ascii') # setup file to read source = d.write('bad.txt', 'some text', 'ascii') with Replacer() as r: r.replace('sys.argv', ['script.py', config, source]) with OutputCapture() as output: main() self.assertTrue('OperationalError' in output.captured, output.captured)
def test_class(self): from testfixtures.tests import sample1 x = sample1.X() assert x.__class__.__name__ == 'X' class XReplacement(sample1.X): pass r = Replacer() r.replace('testfixtures.tests.sample1.X', XReplacement) x = sample1.X() assert x.__class__.__name__ == 'XReplacement' assert sample1.X().y() == 'original y' r.restore() x = sample1.X() assert x.__class__.__name__ == 'X'
def test_class_method(self): from testfixtures.tests import sample1 c = sample1.X assert sample1.X.aMethod() is c def rMethod(cls): return cls, 1 r = Replacer() r.replace('testfixtures.tests.sample1.X.aMethod',rMethod) sample1.X.aMethod() assert sample1.X.aMethod() == (c, 1) r.restore() sample1.X.aMethod() assert sample1.X.aMethod() is c
def evaluate_bash_block(example): command, output = example.parsed def sample_script(dotted, func): sample = __import__('sample.' + dotted) obj = sample for name in dotted.split('.'): obj = getattr(obj, name) getattr(obj, func)() def do_nothing(*args): pass commands = { 'bin/db': (partial(sample_script, 'db', 'scripts'), False), 'bin/run': (partial(sample_script, 'run', 'main'), False), 'DB_URL=mysql://scott:tiger@localhost/test': (do_nothing, False), } command, args = command.split(None, 1) func, needs_ver = commands[command] with Replacer() as r: r.replace('sys.argv', [command] + args.split()) try: with OutputCapture() as o: func() except SystemExit as e: # pragma: no cover print("Output:") print(o.output.getvalue()) raise except Exception as e: # pragma: no cover actual = '...traceback...\n' + repr(e) else: actual = o.output.getvalue() actual = actual.replace(example.namespace['dir'].path, '').strip() compare(actual, expected=output.rstrip())
def test_is_connected(): """ Makes sure the QueueManager's 'is_connected' property works as expected. """ with Replacer() as r: queue_manager = uuid4().hex channel = uuid4().hex host = uuid4().hex port = "1431" conn_info = "%s(%s)" % (host, port) for expected in (True, False): def _connectTCPClient(*ignored_args, **ignored_kwargs): pass def _getattr(self, name): if expected: class _DummyMethod(object): pass # The mere fact of not raising an exception will suffice # for QueueManager._is_connected to understand it as an # all's OK condition. return _DummyMethod else: raise Exception() r.replace('pymqi.QueueManager.connectTCPClient', _connectTCPClient) r.replace('pymqi.PCFExecute.__getattr__', _getattr) qmgr = pymqi.QueueManager(None) qmgr.connectTCPClient(queue_manager, pymqi.cd(), channel, conn_info) eq_(qmgr.is_connected, expected)
def test_vol_swap_strike(): replace = Replacer() base = Cross('MA667', 'EURUSD') xrefs = replace('gs_quant.timeseries.measures.Asset.get_identifier', Mock()) xrefs.return_value = 'EURUSD' mock_asset_1 = GsAsset(asset_class='FX', id='MA123', type_='VolatilitySwap', name='Test_asset', parameters={"lastFixingDate": "1y"}) mock_asset_2 = GsAsset(asset_class='FX', id='MA123', type_='VolatilitySwap', name='Test_asset', parameters={"lastFixingDate": "2y"}) assets = replace('gs_quant.timeseries.measures.GsAssetApi.get_many_assets', Mock()) assets.return_value = [mock_asset_1, mock_asset_2] mock_data = replace( 'gs_quant.timeseries.measures.GsDataApi.get_market_data', Mock()) mock_data.return_value = mock_df() actual = tm_fxo.vol_swap_strike(base, "1y", location=PricingLocation.LDN, real_time=False) assert_series_equal( tm_rates._extract_series_from_df(mock_df(), QueryType.STRIKE_VOL), actual) actual = tm_fxo.vol_swap_strike(base, "1y", None, real_time=False) assert_series_equal( tm_rates._extract_series_from_df(mock_df(), QueryType.STRIKE_VOL), actual)
def test_gotcha(self): # Just because you replace an object in one context: from testfixtures.tests import sample1 from testfixtures.tests import sample2 assert sample1.z() == 'original z' def test_z(): return 'replacement z' r = Replacer() r.replace('testfixtures.tests.sample1.z',test_z) assert sample1.z() == 'replacement z' # Doesn't meant that it's replaced in all contexts: assert sample2.z() == 'original z' r.restore()