Beispiel #1
0
 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)
Beispiel #3
0
    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)
Beispiel #4
0
    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)
Beispiel #5
0
 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,)
     )
Beispiel #6
0
    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_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_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_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)
Beispiel #10
0
    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)
Beispiel #11
0
 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")
Beispiel #12
0
    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']
        )
Beispiel #14
0
 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_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()
Beispiel #16
0
 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 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))
Beispiel #18
0
 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_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 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")
Beispiel #21
0
 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 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 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)
Beispiel #24
0
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)
Beispiel #25
0
    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))
Beispiel #26
0
    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)
Beispiel #27
0
    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)
Beispiel #28
0
    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"')
Beispiel #29
0
    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')
Beispiel #30
0
    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)