def __init__(self): self.figure = MagicMock() self.figure.canvas = MagicMock()
def test_console_rpc_call(self, mock_write, mock_rcv, mock_parse): self.dev._tty.nc.rpc = MagicMock(side_effect=self._mock_manager) op = self.dev.rpc.get_chassis_inventory() self.assertEqual(op.tag, "chassis-inventory")
# # You should have received a copy of the GNU Affero General Public License # along with PyBossa. If not, see <http://www.gnu.org/licenses/>. import json from pybossa.jobs import webhook from default import Test, with_context, FakeResponse, db from factories import ProjectFactory from factories import TaskFactory from factories import TaskRunFactory from redis import StrictRedis from mock import patch, MagicMock from datetime import datetime from pybossa.repositories import ResultRepository queue = MagicMock() queue.enqueue.return_value = True result_repo = ResultRepository(db) class TestWebHooks(Test): def setUp(self): super(TestWebHooks, self).setUp() self.connection = StrictRedis() self.connection.flushall() self.project = ProjectFactory.create() self.webhook_payload = dict(project_id=self.project.id, project_short_name=self.project.short_name)
def test_main_loop(self, redis_rules, traptor, tweets): """Ensure we can loop through the streaming Twitter data.""" traptor._setup() traptor.redis_conn = redis_rules traptor.redis_rules = [rule for rule in traptor._get_redis_rules()] traptor.twitter_rules = traptor._make_twitter_rules( traptor.redis_rules) if traptor.traptor_type == 'locations': traptor.locations_rule = traptor._get_locations_traptor_rule() # The birdy_stream will just look like whatever tweet has been loaded traptor.birdy_stream = MagicMock(return_value=tweets) traptor.birdy_stream.stream = traptor.birdy_stream tweet = traptor.birdy_stream.stream() # Do the rule matching against the redis rules enriched_data = traptor._enrich_tweet(tweet) # This is actually testing the rule matching if traptor.traptor_type == 'track': assert enriched_data['traptor'][ 'created_at_iso'] == '2016-02-22T01:34:53+00:00' assert enriched_data['traptor']['collection_rules'][0][ 'rule_tag'] == 'test' assert enriched_data['traptor']['collection_rules'][0][ 'rule_value'] == 'happy' assert enriched_data['traptor']['collection_rules'][0][ 'rule_type'] == 'track' assert enriched_data['traptor']['collection_rules'][0][ 'tag'] == 'test' assert enriched_data['traptor']['collection_rules'][0][ 'value'] == 'happy' assert enriched_data['traptor']['collection_rules'][0][ 'status'] == 'active' assert enriched_data['traptor']['collection_rules'][0][ 'description'] == 'Tweets for a hashtag' assert enriched_data['traptor']['collection_rules'][0][ 'appid'] == 'test-appid' if traptor.traptor_type == 'follow': assert enriched_data['traptor'][ 'created_at_iso'] == '2016-02-20T03:52:59+00:00' assert enriched_data['traptor']['collection_rules'][0][ 'rule_tag'] == 'test' assert enriched_data['traptor']['collection_rules'][0][ 'rule_value'] == '17919972' assert enriched_data['traptor']['collection_rules'][0][ 'rule_type'] == 'follow' assert enriched_data['traptor']['collection_rules'][0][ 'tag'] == 'test' assert enriched_data['traptor']['collection_rules'][0][ 'value'] == '17919972' assert enriched_data['traptor']['collection_rules'][0][ 'status'] == 'active' assert enriched_data['traptor']['collection_rules'][0][ 'description'] == 'Tweets from some user' assert enriched_data['traptor']['collection_rules'][0][ 'appid'] == 'test-appid' if traptor.traptor_type == 'locations': assert enriched_data['traptor'][ 'created_at_iso'] == '2016-02-23T02:02:54+00:00' assert enriched_data['traptor']['collection_rules'][0][ 'rule_tag'] == 'test' assert enriched_data['traptor']['collection_rules'][0][ 'rule_value'] == '-122.75,36.8,-121.75,37.8' assert enriched_data['traptor']['collection_rules'][0][ 'rule_type'] == 'locations' assert enriched_data['traptor']['collection_rules'][0][ 'tag'] == 'test' assert enriched_data['traptor']['collection_rules'][0][ 'value'] == '-122.75,36.8,-121.75,37.8' assert enriched_data['traptor']['collection_rules'][0][ 'status'] == 'active' assert enriched_data['traptor']['collection_rules'][0][ 'description'] == 'Tweets from some continent' assert enriched_data['traptor']['collection_rules'][0][ 'appid'] == 'test-appid'
def GetCompletionsUserMayHaveCompleted_ReturnEmptyIfNotDone_test(self): with self._SetupForCsharpCompletionDone([]): self.ycm._latest_completion_request.Done = MagicMock( return_value=False) eq_([], self.ycm.GetCompletionsUserMayHaveCompleted())
def test_should_not_add_contact_when_rapid_pro_off(self): requests.post = MagicMock() ContactService.add_or_update_rapid_pro_contact(CONTACT) self.assertFalse(requests.post.called)
def test_should_search_contact_by_phone(self): requests.get = MagicMock(return_value=MagicMock(status_code=200, json=MagicMock(return_value=CONTACT))) response = ContactService.get(CONTACT['phone']) self.assertEqual(response, CONTACT)
def test_startshell_close(self, mock_connect): self.shell._chan = MagicMock() self.shell._client = MagicMock() self.shell.close() self.shell._client.close.assert_called_once()
def test_startshell_run(self, mock_wait): self.shell._chan = MagicMock() self.shell.run('ls') self.assertTrue(call.send('echo $?') in self.shell._chan.mock_calls)
def _test(self, module_name, shouldBelongToToil=False, expectedContents=None, allowExtraContents=True): module = ModuleDescriptor.forModule(module_name) # Assert basic attributes and properties self.assertEqual(module.belongsToToil, shouldBelongToToil) self.assertEquals(module.name, module_name) if shouldBelongToToil: self.assertTrue(module.dirPath.endswith('/src')) # Before the module is saved as a resource, localize() and globalize() are identity # methods. This should log warnings. self.assertIs(module.localize(), module) self.assertIs(module.globalize(), module) # Create a mock job store ... jobStore = MagicMock() # ... to generate a fake URL for the resource ... url = 'file://foo.zip' jobStore.getSharedPublicUrl.return_value = url # ... and save the resource to it. resource = module.saveAsResourceTo(jobStore) # Ensure that the URL generation method is actually called, ... jobStore.getSharedPublicUrl.assert_called_once_with( sharedFileName=resource.pathHash) # ... and that ensure that writeSharedFileStream is called. jobStore.writeSharedFileStream.assert_called_once_with( sharedFileName=resource.pathHash, isProtected=False) # Now it gets a bit complicated: Ensure that the context manager returned by the # jobStore's writeSharedFileStream() method is entered and that the file handle yielded # by the context manager is written to once with the zipped source tree from which # 'toil.resource' was orginally imported. Keep the zipped tree around such that we can # mock the download later. file_handle = jobStore.writeSharedFileStream.return_value.__enter__.return_value # The first 0 index selects the first call of write(), the second 0 selects positional # instead of keyword arguments, and the third 0 selects the first positional, i.e. the # contents. This is a bit brittle since it assumes that all the data is written in a # single call to write(). If more calls are made we can easily concatenate them. zipFile = file_handle.write.call_args_list[0][0][0] self.assertTrue( zipFile.startswith('PK')) # the magic header for ZIP files # Check contents if requested if expectedContents is not None: with ZipFile(BytesIO(zipFile)) as _zipFile: actualContents = set(_zipFile.namelist()) if allowExtraContents: self.assertTrue( actualContents.issuperset(expectedContents)) else: self.assertEqual(actualContents, expectedContents) self.assertEquals(resource.url, url) # Now we're on the worker. Prepare the storage for localized resources Resource.prepareSystem() try: # Register the resource for subsequent lookup. resource.register() # Lookup the resource and ensure that the result is equal to but not the same as the # original resource. Lookup will also be used when we localize the module that was # originally used to create the resource. localResource = Resource.lookup(module._resourcePath) self.assertEquals(resource, localResource) self.assertIsNot(resource, localResource) # Now show that we can localize the module using the registered resource. Set up a mock # urlopen() that yields the zipped tree ... mock_urlopen = MagicMock() mock_urlopen.return_value.read.return_value = zipFile with patch('toil.resource.urlopen', mock_urlopen): # ... and use it to download and unpack the resource localModule = module.localize() # The name should be equal between original and localized resource ... self.assertEquals(module.name, localModule.name) # ... but the directory should be different. self.assertNotEquals(module.dirPath, localModule.dirPath) # Show that we can 'undo' localization. This is necessary when the user script's jobs # are invoked on the worker where they generate more child jobs. self.assertEquals(localModule.globalize(), module) finally: Resource.cleanSystem()
def setUp(self): self.component = Component(position=[50, 50], bounds=[100, 100]) self.component.request_redraw = MagicMock() self.command = ResizeCommand(self.component, (25, 25, 150, 150), (50, 50, 100, 100))
def _mock_get_compress_module(compression_type): m = MagicMock() # simulate module.compress() method that does not compress input data string m.compress = lambda data, compression_level: data return m
def test_get_overlays(self, mock_projector_overlays): mock_overlay = MagicMock() mock_overlay.name = 'mock_overlay' mock_projector_overlays.send.return_value = ((None, mock_overlay), ) value = projector_api.get_overlays() self.assertEqual(value, {'mock_overlay': mock_overlay})
def setup_method(self, method): self.axes = MagicMock() self.roi = self._roi_factory()
def test_should_not_delete_contact_when_rapid_pro_off(self): phone = '+8618192235667' requests.delete = MagicMock(return_value=MagicMock(status_code=HTTP_204_NO_CONTENT)) ContactService.delete_rapid_pro_contact(phone) self.assertFalse(requests.delete.called)
def test_startshell_wait_for(self, mock_select): mock_select.return_value = ['> ', 2, 3] self.shell._chan = MagicMock() self.shell._chan.recv.return_value = '> ' self.assertTrue(self.shell.wait_for('> ')[0].endswith('> '))
def test_should_not_get_contact_when_rapid_pro_off(self): phone = '+8618192235667' requests.get = MagicMock() ContactService.get_rapid_pro_contact(phone) self.assertFalse(requests.get.called)
def test_startshell_context(self, mock_open, mock_close): with StartShell(self.dev) as shell: shell._chan = MagicMock() shell.send('test') mock_close.assert_called_once(call())
def test_should_get_contact_by_user_id(self): requests.get = MagicMock(return_value=MagicMock(status_code=200, json=MagicMock(return_value=CONTACT))) response = ContactService.get_by_user_id('17') self.assertEqual(response, CONTACT)
def make_one(self): from kotti_boxes.views.edit.boxes.banner import BannerBoxEditForm return BannerBoxEditForm(MagicMock(), DummyRequest())
def test_ensure_traptor_builds_the_correct_filter_string(self, traptor): traptor.logger = MagicMock() traptor.traptor_type = 'track' traptor.twitter_rules = traptor._make_twitter_rules([{ "rule_id": u"1", "value": u"happy", "rule_type": u"track", "orig_type": u"keyword" }, { "rule_id": u"2", "value": u"summer", "rule_type": u"track", "orig_type": u"hashtag" }, { "rule_id": u"3", "value": u"#apple", "rule_type": u"track", "orig_type": u"hashtag" }, { "rule_id": u"4", "value": u"#sliding door", "rule_type": u"track", "orig_type": u"hashtag" }, { "rule_id": u"5", "value": u"summer", "rule_type": u"track", "orig_type": u"hashtag" }, { "rule_id": u"6", "value": u"今日中国", "rule_type": u"track", "orig_type": u"keyword" }]) given_set = set(traptor.twitter_rules.split(',')) expected_set = set( u'#apple,#sliding #door,#summer,今日中国,happy'.split(',')) assert len(given_set.difference(expected_set)) == 0 assert len(expected_set.difference(given_set)) == 0
def test_unique_store_action_first_call(): mock_parser = MagicMock() mock_namespace = MagicMock(special_attribute=None) action = arg_parsing.UniqueStoreAction(option_strings=sentinel.option_strings, dest="special_attribute") action(parser=mock_parser, namespace=mock_namespace, values=sentinel.values, option_string="SPECIAL_ATTRIBUTE") assert mock_namespace.special_attribute is sentinel.values
def OnCompleteDone_WithActionCallsIt_test(self, *args): action = MagicMock() self.ycm._complete_done_hooks["txt"] = action self.ycm.OnCompleteDone() ok_(action.called)
def setUp(self): self.channel = Channel(MagicMock(Connection)(), 0, None) self.channel._state = Channel.OPEN self.callback = MagicMock()
def setUp(self): self.ycm = YouCompleteMe(MagicMock(spec_set=dict))
def test_two_basic_get_with_callback(self): self.channel.basic_get('test-queue', self.callback) self.channel._on_getok(MagicMock(Method)(), MagicMock(Header)(), '') self.channel.basic_get('test-queue', self.callback) self.channel._on_getok(MagicMock(Method)(), MagicMock(Header)(), '') self.assertEqual(self.callback.call_count, 2)
def test_copy_elb(): cloud_connection = MagicMock() connection = MagicMock() cloud_connection.get_connection.return_value = connection def describe_load_balancers(LoadBalancerNames=None): if LoadBalancerNames == ['test-elb']: return get_aws_data('elb--describe-load-balancers') if LoadBalancerNames == ['copied_elb']: return None raise Exception( 'describe_load_balancers : Invalid parameter LoadBalancerNames') connection.describe_load_balancers.side_effect = describe_load_balancers connection.describe_tags.return_value = get_aws_data('elb--describe-tags') connection.describe_load_balancer_attributes.return_value = get_aws_data( 'elb--describe-load-balancers-attributes') connection.create_load_balancer.return_value.__getitem__.side_effect = { "DNSName": "test-dns" }.__getitem__ dns = AwsClbManager(cloud_connection, 'region').copy_lb('copied_elb', 'test-elb', {'foo': 'bar'}, LOG_FILE) assert dns == "test-dns" assert connection.describe_load_balancers.call_count == 2 connection.describe_tags.assert_called_once_with( LoadBalancerNames=['test-elb']) connection.describe_load_balancer_attributes.assert_called_once_with( LoadBalancerName='test-elb') connection.create_load_balancer.assert_called_once_with( LoadBalancerName='copied_elb', Listeners=[{ "LoadBalancerPort": 80, "Protocol": "HTTP", "InstancePort": 80, "InstanceProtocol": "HTTP" }, { "LoadBalancerPort": 443, "Protocol": "HTTPS", "InstancePort": 80, "InstanceProtocol": "HTTP", "SSLCertificateId": "arn:aws:iam::0123456789:server-certificate/test-certificate" }], Subnets=["subnet-test"], SecurityGroups=["sg-test"], Scheme="internet-facing", Tags=[ { "Key": "test-key", "Value": "test-value" }, { "Key": "foo", "Value": "bar" }, ]) connection.configure_health_check.assert_called_once_with( LoadBalancerName='copied_elb', HealthCheck={ "Interval": 20, "Timeout": 6, "Target": "TCP:80", "UnhealthyThreshold": 4, "HealthyThreshold": 2 }) connection.modify_load_balancer_attributes.assert_called_once_with( LoadBalancerName='copied_elb', LoadBalancerAttributes={ "AccessLog": { "Enabled": False }, "CrossZoneLoadBalancing": { "Enabled": True }, "ConnectionDraining": { "Enabled": True, "Timeout": 400 }, "ConnectionSettings": { "IdleTimeout": 400 } })
def test_should_not_add_or_update_contact_when_rapid_pro_off(self): requests.get = MagicMock() requests.post = MagicMock() self.assertFalse(requests.get.called) self.assertFalse(requests.post.called)
def testSetsExceptionWhenSeverityProperlySet_Info(self): self.validator.get_severity = MagicMock(return_value=0) self.validator.setup() self.assertEqual(loggers.ElectionInfo, self.validator.exception)
def setUp(self): self.imap_protocol = IMAP4ClientProtocol(None) self.imap_protocol._handle_line = MagicMock(return_value=None)