def setUp(self): self.symbols = [] # columns self.columns_count = -1 for i in range(0, 8, 1): symbol = Mock() symbol.location = ((0 + (7 - i) * 20, 0), ((7 - i) * 20, 10), (10 + (7 - i) * 20, 10), (10 + (7 - i) * 20, 0)) symbol.data = "__" self.symbols.append(symbol) self.columns_count += 1 # cards self.cards_count = 0 for i in range(0, 7, 1): symbol = Mock() symbol.location = ((5 + i * 20, 5), (5 + i * 20, 15), (15 + i * 20, 15), (15 + i * 20, 5)) symbol.data = "T" + str(i) * 5 self.symbols.append(symbol) self.cards_count += 1 # config symbol symbol = Mock() symbol.location = ((50, 50), (50, 60), (60, 60), (60, 50)) self.board_id = 1 symbol.data = "[%d,%d]" % (self.board_id, self.columns_count) self.symbols.append(symbol)
def test_n_amino_acids_invalid_fasta_description(): mock_field = Mock() mock_field.data = '>\nACDEFGHIK' mock_field.errors = [] mock_form = Mock() mock_form._fields = {'field1': mock_field} expected_message = u'Multiple sequence FASTA input ' + \ 'is currently not supported. ' + \ 'The first line of FASTA input should start ' + \ 'with ">" followed by a description.' try: NAminoAcids(25)(mock_form, mock_field) except ValidationError as ve: eq_(ve.message, expected_message) mock_field.data = '> test\nACDEFGHIK' mock_form = Mock() mock_form._fields = {'field1': mock_field} try: NAminoAcids(25)(mock_form, mock_field) except ValidationError as ve: eq_(ve.message, expected_message)
def test_subscriber_callback(self): data = Mock() data.data = True self.subscriber_callback(data) self.assertFalse(self.__callback_called) data.data = False self.subscriber_callback(data) self.assertTrue(self.__callback_called)
def _create_execution_mocks(self, pool, status, side=None, valid=True): response = Mock() pool.urlopen.return_value = response if valid: response.data = RESPONSE_DATA else: response.data = INVALID_RESPONSE_DATA response.status = status if side: pool.urlopen.side_effect = side return response
def _populate_field(self, field, hp_field_data=None, hash_control=None): field.private_key = 'private' field.timeout = 2000 first = Mock(name='first') first.data = hp_field_data first.name = u'first' control = Mock(control='control') now = datetime.now().strftime('%s') control.name = HoneyPotField.get_control_prefix() + now field.entries = [first] control.data = hash_control if hash_control else field.hash_entries(now) field.entries.append(control)
def test_not_required_if_one_of_no_field(): mock_field1 = Mock() mock_field1.data = '' mock_field1.errors = [] mock_field2 = Mock() mock_field2.data = '' mock_field2.errors = [] mock_form = Mock() mock_form._fields = {'field1': mock_field1, 'field2': mock_field2} NotRequiredIfOneOf(['field3'])(mock_form, mock_field1)
def test_get_redirect_history_from_task_when_suspicious_in_data(self, get_r_history_m, to_uni_m): task_mock = Mock(None) task_mock.data = { 'recheck': False, 'url': 'www.leningrad.spb.ru', 'url_id': 666, 'suspicious': 'whazzzup' } test_history_types = ['APPLE', 'BLACKBERRY'] test_history_urls = ['apple.com', 'blackberry.com'] test_counters = ['a', 'b'] get_r_history_m.return_value = test_history_types, test_history_urls, test_counters url_mock = Mock(None) to_uni_m.return_value = url_mock res_is_input, res_data = wr.get_redirect_history_from_task(task_mock, 42) self.assertFalse(res_is_input) test_data = { 'url_id': 666, 'result': [test_history_types, test_history_urls, test_counters], 'check_type': 'normal', 'suspicious': 'whazzzup' } self.assertEqual(res_data, test_data)
def test_incremental_crawl(self, bucket_mock, conn_mock): the_past = epoch.from_date(timezone.now() - timedelta(days=365)) # Test runs in under a second typically, so we need to be slightly # behind present time, so that we can see fbm.incremental_epoch # get updated present = epoch.from_date(timezone.now() - timedelta(seconds=30)) fbm = models.FBSyncMap.items.create( fbid_primary=self.fbid, fbid_secondary=self.fbid, token=self.token.token, back_filled=False, back_fill_epoch=the_past, incremental_epoch=present, status=models.FBSyncMap.COMPLETE, bucket='test_bucket_0' ) existing_key = Mock() existing_key.data = {"updated": 1, "data": [{"test": "testing"}]} bucket_mock.return_value = existing_key conn_mock.return_value = s3_feed.BucketManager() tasks.incremental_crawl(fbm.fbid_primary, fbm.fbid_secondary) new_fbm = models.FBSyncMap.items.get_item( fbid_primary=self.fbid, fbid_secondary=self.fbid) self.assertEqual(fbm.status, fbm.COMPLETE) self.assertGreater(int(new_fbm.incremental_epoch), present) self.assertTrue(existing_key.extend_s3_data.called) self.assertSequenceEqual( existing_key.extend_s3_data.call_args_list[0][0], (False,) )
def test_should_create_host_from_json(self, _): components = {} protocol_with_json_data = Mock() protocol_with_json_data.component = 'host://foobar42' protocol_with_json_data.data = '''{ "fqdn": "foobar42.acme.com", "next_artefacts": {}, "some_attribute": "some-value" }''' result_host = yadtshell._status.create_host(protocol_with_json_data, components) self.assertEqual(result_host.hostname, 'foobar42') self.assertEqual(result_host.next_artefacts, {}) self.assertEqual(result_host.is_uptodate(), True) self.assertEqual(result_host.some_attribute, "some-value") self.assertEqual( result_host.loc_type, { 'loc': 'foo', 'host': 'foobar42', 'type': 'bar', 'loctype': 'foobar', 'nr': '42' })
def test_handle_smart_errors(self): app = Flask(__name__) api = flask_restful.Api(app) view = flask_restful.Resource exception = Mock() exception.code = 404 exception.data = {"status": 404, "message": "Not Found"} api.add_resource(view, '/foo', endpoint='bor') api.add_resource(view, '/fee', endpoint='bir') api.add_resource(view, '/fii', endpoint='ber') with app.test_request_context("/faaaaa"): resp = api.handle_error(exception) self.assertEquals(resp.status_code, 404) self.assertEquals(resp.data, dumps({ "status": 404, "message": "Not Found", })) with app.test_request_context("/fOo"): resp = api.handle_error(exception) self.assertEquals(resp.status_code, 404) self.assertEquals(resp.data, dumps({ "status": 404, "message": "Not Found. You have requested this URI [/fOo] but did you mean /foo ?", })) with app.test_request_context("/fOo"): del exception.data["message"] resp = api.handle_error(exception) self.assertEquals(resp.status_code, 404) self.assertEquals(resp.data, dumps({ "status": 404, "message": "You have requested this URI [/fOo] but did you mean /foo ?", }))
def test_non_strict_response_matches(self): sample = _abe_wrap_response({ "status": 201, "body": { "id": 12, "name": "My Resource", "url": "http://example.com/resource/12", "author": { "name": "Slough", "url": "http://example.com/user/25" } } }) response = Mock() response.status_code = 201 response.data = { "id": 25, "name": "My Resource", "url": "http://example.com/resource/12312", "author": { "name": "Slough", "url": "http://testserver/25/" } } self.assert_matches_response( sample, response, non_strict=['id', 'url', 'author.url'] )
def test_download(self, mock_repo_controller, mock_dl_request): # Setup mock_catalog = Mock() mock_catalog.importer_id = 'mock_id' mock_catalog.url = 'http://dev.null/' mock_catalog.data = {'k': 'v'} mock_request = Mock() mock_data = {'catalog_entry': mock_catalog, 'client_request': mock_request} mock_responder = Mock() mock_importer = Mock() mock_importer_config = Mock() mock_downloader = mock_importer.get_downloader.return_value mock_repo_controller.get_importer_by_id.return_value = (mock_importer, mock_importer_config) # Test self.streamer._download(mock_catalog, mock_request, mock_responder) mock_repo_controller.get_importer_by_id.assert_called_once_with(mock_catalog.importer_id) mock_dl_request.assert_called_once_with(mock_catalog.url, mock_responder, data=mock_data) mock_importer.get_downloader.assert_called_once_with( mock_importer_config, mock_catalog.url, **mock_catalog.data) self.assertEqual(mock_request, mock_downloader.event_listener.request) self.assertEqual(self.config, mock_downloader.event_listener.streamer_config) mock_downloader.download_one.assert_called_once_with(mock_dl_request.return_value, events=True) mock_downloader.config.finalize.assert_called_once_with()
def create_push_campaign(status): campaign_push = Mock() campaign_push.rule = Mock() campaign_push.rule.campaign.status = status campaign_push.data = {} return campaign_push
def _dummy_urlopen(*args, **kwargs): dummy_response = Mock() dummy_response.headers = {} dummy_response.status = 200 dummy_response.data = response_body _dummy_urlopen.call_args = (args, kwargs) return dummy_response
def test_get_redirect_history_from_task_error_and_no_recheck3(self): task = Mock() task.data = dict(url='url', recheck=True, url_id='url_id') with patch('lib.worker.get_redirect_history', Mock(return_value=('ERROR', 'history_urls', 'counters'))): is_input, data = worker.get_redirect_history_from_task(task, 42) self.assertFalse(is_input)
def test_handle_error_signal(self): if not signals_available: # This test requires the blinker lib to run. print("Can't test signals without signal support") return app = Flask(__name__) api = flask_restful.Api(app) exception = Mock() exception.code = 400 exception.data = {'foo': 'bar'} recorded = [] def record(sender, exception): recorded.append(exception) got_request_exception.connect(record, app) try: with app.test_request_context("/foo"): api.handle_error(exception) self.assertEquals(len(recorded), 1) self.assertTrue(exception is recorded[0]) finally: got_request_exception.disconnect(record, app)
def test_download(self, mock_repo_controller, mock_dl_request): # Setup mock_catalog = Mock() mock_catalog.importer_id = 'mock_id' mock_catalog.url = 'http://dev.null/' mock_catalog.data = {'k': 'v'} mock_request = Mock() mock_data = { 'catalog_entry': mock_catalog, 'client_request': mock_request } mock_responder = Mock() mock_importer = Mock() mock_importer_config = Mock() mock_downloader = mock_importer.get_downloader.return_value mock_repo_controller.get_importer_by_id.return_value = ( mock_importer, mock_importer_config) # Test self.streamer._download(mock_catalog, mock_request, mock_responder) mock_repo_controller.get_importer_by_id.assert_called_once_with( mock_catalog.importer_id) mock_dl_request.assert_called_once_with(mock_catalog.url, mock_responder, data=mock_data) mock_importer.get_downloader.assert_called_once_with( mock_importer_config, mock_catalog.url, **mock_catalog.data) self.assertEqual(mock_request, mock_downloader.event_listener.request) self.assertEqual(self.config, mock_downloader.event_listener.streamer_config) mock_downloader.download_one.assert_called_once_with( mock_dl_request.return_value, events=True) mock_downloader.config.finalize.assert_called_once_with()
def test_update_comment(self): org = self.organization self.user.name = "Sentry Admin" self.user.save() self.login_as(self.user) integration = Integration.objects.create(provider="jira", name="Example Jira") integration.add_organization(org, self.user) installation = integration.get_installation(org.id) group_note = Mock() comment = "hello world\nThis is a comment.\n\n\n I've changed it" group_note.data = {} group_note.data["text"] = comment group_note.data["external_id"] = "123" with mock.patch.object(MockJiraApiClient, "update_comment") as mock_update_comment: def get_client(): return MockJiraApiClient() with mock.patch.object(installation, "get_client", get_client): installation.update_comment(1, self.user.id, group_note) assert mock_update_comment.call_args[0] == ( 1, "123", "Sentry Admin wrote:\n\n{quote}%s{quote}" % comment, )
def test_save(self, mock_dump, mock_open): core = Mock() ts = self.get_obj(core) queue = Mock() queue.empty = Mock(side_effect=Empty) ts.work_queue = queue mock_open.side_effect = IOError # test that save does _not_ raise an exception even when # everything goes pear-shaped ts._save() queue.empty.assert_any_call() mock_open.assert_called_with(ts.pending_file, 'w') queue.reset_mock() mock_open.reset_mock() queue.data = [] for hostname, xml in self.data: md = Mock() md.hostname = hostname queue.data.append((md, lxml.etree.XML(xml))) queue.empty.side_effect = lambda: len(queue.data) == 0 queue.get_nowait = Mock(side_effect=lambda: queue.data.pop()) mock_open.side_effect = None ts._save() queue.empty.assert_any_call() queue.get_nowait.assert_any_call() mock_open.assert_called_with(ts.pending_file, 'w') mock_open.return_value.close.assert_any_call() # the order of the queue data gets changed, so we have to # verify this call in an ugly way self.assertItemsEqual(mock_dump.call_args[0][0], self.data) self.assertEqual(mock_dump.call_args[0][1], mock_open.return_value)
def test_update_comment(self): org = self.organization self.user.name = 'Sentry Admin' self.user.save() self.login_as(self.user) integration = Integration.objects.create( provider='jira', name='Example Jira', ) integration.add_organization(org, self.user) installation = integration.get_installation(org.id) group_note = Mock() comment = 'hello world\nThis is a comment.\n\n\n I\'ve changed it' group_note.data = {} group_note.data['text'] = comment group_note.data['external_id'] = '123' with mock.patch.object(MockJiraApiClient, 'update_comment') as mock_update_comment: def get_client(): return MockJiraApiClient() with mock.patch.object(installation, 'get_client', get_client): installation.update_comment(1, self.user.id, group_note) assert mock_update_comment.call_args[0] == \ (1, '123', 'Sentry Admin wrote:\n\n{quote}%s{quote}' % comment)
def test_formats_group_data(self): data = {'group_name': 'bob', 'group_color': 'red'} user = Mock() user.data = {} message = Clue(text='Hello {group_name}, you like {group_color}?') response = format_message(message, user, Group(data=data)) self.assertEqual('Hello bob, you like red?', response.text)
def test_load_config_bad_data(self): with patch.object(self.driver, "_etcd_request") as m_etcd_req: m_resp = Mock() m_resp.data = "{garbage" m_etcd_req.return_value = m_resp self.assertRaises(ResyncRequired, self.driver._load_config, "/calico/v1/config")
def test_response_matches_strictly(self): sample = _abe_wrap_response({ "status": 201, "body": { "id": 12, "name": "My Resource", "url": "http://example.com/resource/12", "author": { "name": "Slough", "url": "http://example.com/user/25" } } }) response = Mock() response.status_code = 201 response.data = { "id": 12, "name": "My Resource", "url": "http://example.com/resource/12", "author": { "name": "Slough", "url": "http://example.com/user/25" } } self.assert_matches_response( sample, response )
def test_main(pclass, unpickle, pickle): p = Mock() pclass.return_value = p subsample = Mock() subsample.data = cars unpickle.return_value = subsample factor_analysis._main(['foo.subsample', '5', 'foo.famodel']) pclass.assert_called_once()
def _dict_mock(self, **kwargs): """ Get a mock that allows __getitem__ """ item = Mock() item.data = kwargs item.__getitem__ = lambda s, k: s.data[k] return item
def test_scanned_columns_count_is_equal_to_config_column_count(self): symbols = [] symbol = Mock() symbol.location = ((50, 50), (50, 60), (60, 60), (60, 50)) columns_count = 1 symbol.data = "[1,%d]" % (columns_count) symbols.append(symbol) self.assertRaises(IOError, mapper.Mapper, (symbols))
def mock_two_reflection_file_object(ids=[0, 2]): """Create a mock reflection_file_object with two datasets.""" fileobj = Mock() r = flex.reflection_table() r["id"] = flex.int([-1, ids[0], ids[0], ids[1], ids[1]]) r.experiment_identifiers()[ids[0]] = str(ids[0]) r.experiment_identifiers()[ids[1]] = str(ids[1]) fileobj.data = r return fileobj
def mock_reflection_file_object(id_=0, identifier=True): """Create a mock reflection_file_object.""" fileobj = Mock() r = flex.reflection_table() r["id"] = flex.int([-1, id_, id_]) if identifier: r.experiment_identifiers()[id_] = str(id_) fileobj.data = r return fileobj
def test_save_model_supervisor(self): """If supervisor provided, then set supervisor""" mock_form = Mock() mock_form.data = {"supervisor": self.superuser.pk} obj = ProfileFactory() self.assertIsNone(obj.supervisor) self.admin.save_model(self.request, obj, mock_form, None) profile_updated = UserProfile.objects.get(pk=obj.pk) self.assertEqual(profile_updated.supervisor, self.superuser)
def test_save_model_oic(self): """If OIC provided, then set OIC""" mock_form = Mock() mock_form.data = {"oic": self.superuser.pk} obj = ProfileFactory() self.assertIsNone(obj.oic) self.admin.save_model(self.request, obj, mock_form, None) profile_updated = UserProfile.objects.get(pk=obj.pk) self.assertEqual(profile_updated.oic, self.superuser)
def test_n_amino_acids(): mock_field = Mock() mock_field.data = '1 ACDEFGHIKLMNPQRSTVWXY 22acdefghiklmnpqrstvwxy\n\tA C' mock_field.errors = [] mock_form = Mock() mock_form._fields = {'field1': mock_field} eq_(NAminoAcids(25)(mock_form, mock_field), None)
def test_n_amino_acids_fasta(): mock_field = Mock() mock_field.data = '>test\r\n1 ACDEFGHIKLMNPQRSTVWXY 22acdefghik\r\n' mock_field.errors = [] mock_form = Mock() mock_form._fields = {'field1': mock_field} eq_(NAminoAcids(25)(mock_form, mock_field), None)
def assertAvailable(self, time, form=None): form = form or Mock() field = Mock() field.data = time with override_current_time(self.now): try: self.validator(form, field) except ValidationError as e: self.fail("{time} was not available at {now}: {exc}".format(time=time, now=self.now, exc=e))
def mock_api_call(self, github_api, url, method='GET', fields=None, headers={}): result = Mock() if method == 'GET': result.status = 200 else: result.status = 201 result.data = json.dumps(self.api_results.pop(0)).encode() result.headers.get.return_value = None return result
def test_validation_no_data(self): field = self.get_field() self._populate_field(field) field.entries = [] control = Mock(control='control') now = datetime.now().strftime('%s') control.name = HoneyPotField.get_control_prefix() + now control.data = None field.entries = [control] self.assertFalse(field.validate(None))
def assertAvailable(self, time, form=None): form = form or Mock() field = Mock() field.data = time with override_current_time(self.now): try: self.validator(form, field) except ValidationError as e: self.fail("{time} was not available at {now}: {exc}".format( time=time, now=self.now, exc=e))
def test_confirm_user_doesnt_match(self): doc = {"provider_id": "octocat_is_not"} v = Mock() v.data = RETURN_VALUE with patch.object(self.remote, "get") as getter: getter.return_value = v resp = self.provider.confirm(doc, "something")\ expect(resp).to.be(False) getter.assert_called_once_with("user")
def test_confirm_user_matches(self): v = Mock() v.data = RETURN_VALUE doc = {"provider_id": "themattharris"} with patch.object(self.remote, "get") as getter: getter.return_value = v resp = self.provider.confirm(doc, "something") expect(resp).to.be(True) getter.assert_called_once_with("me?fields=username")
def request(method, url): import pickle with open(RESPONSE_FILE_PATH, 'rb') as f: d = pickle.load(f) r = Mock() assert_equal(method, 'GET') if url not in d: raise Exception('url %s not in cache' % url) r.data = d[url] return r
def _learning_curve(learning_curve): X = np.array([[0, 1], [1, 0], [1, 1]] * 100, dtype=float) X[:, 1] += np.random.random((300)) - 0.5 y = np.array([0, 0, 1] * 100) dataset = Mock() dataset.train_test_split.return_value = train_test_split(X, y) dataset.data = X dataset.target = y return learning_curve(dataset, LogisticRegression(), steps=5, verbose=1)
def test_watch_etcd_error_from_etcd(self): m_queue = Mock() m_stop_ev = Mock() m_stop_ev.is_set.return_value = False with patch.object(self.driver, "get_etcd_connection") as m_get_conn: with patch.object(self.driver, "_etcd_request") as m_req: with patch.object(self.driver, "_check_cluster_id") as m_check: m_resp = Mock() m_resp.data = json.dumps({"errorCode": 100}) m_req.side_effect = iter([m_resp, AssertionError()]) self.driver.watch_etcd(10, m_queue, m_stop_ev)
def test_handle_error_401_no_challenge_by_default(self): app = Flask(__name__) api = flask_restful.Api(app) exception = Mock() exception.code = 401 exception.data = {'foo': 'bar'} with app.test_request_context('/foo'): resp = api.handle_error(exception) self.assertEquals(resp.status_code, 401) assert_false('WWW-Autheneticate' in resp.headers)
def test_that_router_receive_gets_called_with_parameters(self, mocked_requests_get): gearman_worker = None gearman_job = Mock() gearman_job.data = "url-parameters" worker = ThrottleWorker(self.get_app_config()) response = worker.call_router_receive(gearman_worker, gearman_job) mocked_requests_get.assert_called_with("http://random.address/router/receive?password=supersecret&url-parameters") self.assertEqual("ok", response)
def test_validated_not_raised(self, mock_get): mock_get.return_value.verify = Mock(return_value=False) consumer_id = 'test-consumer_id' document = Mock() document.data = {'consumer_id': consumer_id} # test authenticator = Authenticator() self.assertRaises(ValidationFailed, authenticator.validate, document, '', '') mock_get.assert_called_with(consumer_id)
def test_useful_reraise_in_flush_endpoint(self): error_mock = Mock() error_mock.data = six.b('{"status": 0, "error": "arbitrary error"}') broken_json = '{broken JSON' consumer = mixpanel.BufferedConsumer(2) with patch('mixpanel.urllib3.PoolManager.request', return_value=error_mock): consumer.send('events', broken_json) with pytest.raises(mixpanel.MixpanelException) as excinfo: consumer.flush() assert excinfo.value.message == '[%s]' % broken_json assert excinfo.value.endpoint == 'events'
def test_adds_type(self): sub = self.create_subscription(QuerySubscription.Status.CREATING) with patch("sentry.snuba.tasks._snuba_pool") as pool: resp = Mock() resp.status = 202 resp.data = json.dumps({"subscription_id": "123"}) pool.urlopen.return_value = resp create_subscription_in_snuba(sub.id) request_body = json.loads(pool.urlopen.call_args[1]["body"]) assert ["type", "=", "error"] in request_body["conditions"]
def test_should_notify_match(self): p = MailProcessor(min_level=None) group = Mock(spec=Group) group.level = 5 group.project = Project() group.logger = 'root' event = Mock() event.data = {} self.assertTrue (p.should_notify(group=group, event=event))
def test_out_received_should_append_data(self): mock_process_protocol = Mock(YadtProcessProtocol) mock_process_protocol.data = 'some-data-' mock_process_protocol.component = 'component' mock_process_protocol.out_log_level = 'info' mock_process_protocol.pi = None mock_logger = Mock() mock_process_protocol.logger = mock_logger YadtProcessProtocol.outReceived(mock_process_protocol, '-more-data') self.assertEqual(mock_process_protocol.data, 'some-data--more-data')
def test_handle_error_401_sends_challege_default_realm(self): app = Flask(__name__) api = flask_restful.Api(app) exception = Mock() exception.code = 401 exception.data = {'foo': 'bar'} with app.test_request_context('/foo'): resp = api.handle_error(exception) self.assertEquals(resp.status_code, 401) self.assertEquals(resp.headers['WWW-Authenticate'], 'Basic realm="flask-restful"')
def test_stop_waiting_for_item_when_loaded(self): image_loading_dialog_manager = Mock(spec=ImageLoadingDialogManager) self.controller.image_loading_dialog_manager = image_loading_dialog_manager displayable_item = Mock() event = Mock() event.data = displayable_item self.controller.on_image_loaded(event) image_loading_dialog_manager.set_item_done.assert_called_once_with( displayable_item)