Example #1
1
    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.decode(), 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.decode(),
                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.decode(),
                dumps({"status": 404, "message": "You have requested this URI [/fOo] but did you mean /foo ?"}),
            )
Example #2
1
    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)
Example #3
0
 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)
Example #4
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
Example #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,))
Example #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()
Example #7
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")
Example #8
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)
Example #9
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
Example #10
0
def test_main(pclass, unpickle, pickle):
    p = Mock()
    pclass.return_value = p
    subsample = Mock()
    subsample.data = cars
    unpickle.return_value = subsample
    pca._main(["foo.subsample", "5", "foo.famodel"])
    pclass.assert_called_once()
Example #11
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))
Example #12
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"')
Example #13
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)
Example #14
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
Example #15
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)
Example #16
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))
Example #17
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)
Example #18
0
 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)
Example #19
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")
Example #20
0
    def test_handle_error(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        exception = Mock()
        exception.code = 400
        exception.data = {"foo": "bar"}

        with app.test_request_context("/foo"):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 400)
            self.assertEquals(resp.data.decode(), dumps({"foo": "bar"}))
Example #21
0
    def test_not_validated(self, mock_get):
        message = "hello"
        consumer_id = "test-consumer_id"
        document = Mock()
        document.data = {"consumer_id": consumer_id}
        key = RSA.load_key_bio(BIO.MemoryBuffer(OTHER_KEY))

        mock_get.return_value = RSA.load_pub_key_bio(BIO.MemoryBuffer(RSA_PUB))

        authenticator = Authenticator()
        self.assertRaises(ValidationFailed, authenticator.validate, document, message, key.sign(message))
        mock_get.assert_called_with(consumer_id)
Example #22
0
def test_search(grid_search, Dataset, main):
    from ..learn import search

    dataset = Mock()
    dataset.data = np.array([[1], [2]])
    dataset.target = np.array([1, 2])
    Dataset.return_value = dataset
    main.arguments = {"<model_name>": "lr"}
    result = search()
    assert result is grid_search.return_value
    assert grid_search.call_args[0][0] is dataset
    assert isinstance(grid_search.call_args[0][1], Pipeline)
    assert isinstance(grid_search.call_args[0][2], dict)
Example #23
0
    def test_download_started_canceled(self):
        batch = Mock()
        batch.is_canceled = True
        batch.listener = Mock()
        report = Mock()
        report.data = Mock()

        # test
        listener = NectarListener(batch)
        listener.download_started(report)

        # validation
        self.assertFalse(batch.listener.download_started.called)
    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)
Example #25
0
    def test_hmac_calculation(self):
        """
        Test HMAC calculation.
        """
        auth = HmacAuth("public", "key")

        r = Mock()
        r.method = "patch"
        r.path_url = "/path/?foo=bar"
        r.data = "data body"
        r.headers = {}

        self.assertEqual("ApiKey public:2b989ffc81712758d070fb46055b55f18a245d15", auth(r).headers["Authorization"])
Example #26
0
def test_grid_search():
    from ..grid_search import grid_search

    dataset = Mock()
    dataset.data = np.array([[1, 2, 3], [3, 3, 3]] * 20)
    dataset.target = np.array([0, 1] * 20)
    pipeline = LogisticRegression()
    parameters = dict(C=[1.0, 3.0])

    result = grid_search(dataset, pipeline, parameters)
    assert isinstance(result, GridSearchCV)
    assert hasattr(result, "best_estimator_")
    assert hasattr(result, "best_score_")
Example #27
0
    def test_download_started(self, event):
        batch = Mock()
        batch.listener = Mock()
        report = Mock()
        report.data = Mock()

        # test
        listener = NectarListener(batch)
        listener.download_started(report)

        # validation
        event.assert_called_once_with(report.data)
        event.return_value.assert_called_once_with(batch.listener)
Example #28
0
 def test_watch_etcd_error_from_etcd_index_cleared(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:
                 with patch.object(driver.ETCD_INDEX_CLEARED, "inc") as inc:
                     m_resp = Mock()
                     m_resp.data = json.dumps({"errorCode": 401})
                     m_req.side_effect = iter([m_resp, AssertionError()])
                     self.driver.watch_etcd(10, m_queue, m_stop_ev)
                     inc.assert_called_once_with()
Example #29
0
    def test_should_create_host_with_update_needed_when_next_artefacts_is_not_empty(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-artefact": "another-artefact"},
"some_attribute": "some-value"
}"""

        result_host = yadtshell._status.create_host(protocol_with_json_data, components)

        self.assertEqual(result_host.is_update_needed(), True)
Example #30
0
    def test_handle_auth(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.data.decode(), dumps({"foo": "bar"}))

            self.assertTrue("WWW-Authenticate" in resp.headers)