Ejemplo n.º 1
0
 def test_show(self, *, rmock: requests_mock.Mocker) -> None:
     rmock.get(
         "http://test/api/packages/Pamd64%20authserver%200.1.14~dev0-1%201cc572a93625a9c9",
         text="""{"Architecture":"amd64",
              "Depends":"python3, python3-pip, python3-virtualenv, adduser, cron-daemon",
              "Description":" no description given\\n",
              "Filename":"authserver_0.1.14~dev0-1.deb",
              "FilesHash":"1cc572a93625a9c9",
              "Homepage":"http://example.com/no-uri-given",
              "Installed-Size":"74927",
              "Key":"Pamd64 authserver 0.1.14~dev0-1 1cc572a93625a9c9",
              "License":"unknown",
              "MD5sum":"03cca0794e63cf147b879e0a3695f523",
              "Maintainer":"Jonas Maurus",
              "Package":"authserver",
              "Priority":"extra",
              "Provides":"maurusnet-authserver",
              "SHA1":"9a77a31dba51f612ee08ee096381f0c7e8f97a42",
              "SHA256":"63555a135bf0aa1762d09fc622881aaf352cdb3b244da5d78278c7efa2dba8b7",
              "SHA512":"01f9ca888014599374bf7a2c8c46f895d7ef0dfea99dfd092007f9fc5d5fe57a2755b843eda296b65"""
         """cb6ac0f64b9bd88b507221a71825f5329fdda0e58728cd7",
              "Section":"default",
              "ShortKey":"Pamd64 authserver 0.1.14~dev0-1",
              "Size":"26623042",
              "Vendor":"root@test",
              "Version":"0.1.14~dev0-1"}""")
     pkg = self.papi.show(
         "Pamd64 authserver 0.1.14~dev0-1 1cc572a93625a9c9")
     self.assertEqual(
         pkg,
         Package(
             key='Pamd64 authserver 0.1.14~dev0-1 1cc572a93625a9c9',
             short_key='Pamd64 authserver 0.1.14~dev0-1',
             files_hash='1cc572a93625a9c9',
             fields={
                 'Architecture':
                 'amd64',
                 'Depends':
                 'python3, python3-pip, python3-virtualenv, adduser, cron-daemon',
                 'Description':
                 ' no description given\n',
                 'Filename':
                 'authserver_0.1.14~dev0-1.deb',
                 'FilesHash':
                 '1cc572a93625a9c9',
                 'Homepage':
                 'http://example.com/no-uri-given',
                 'Installed-Size':
                 '74927',
                 'Key':
                 'Pamd64 authserver 0.1.14~dev0-1 1cc572a93625a9c9',
                 'License':
                 'unknown',
                 'MD5sum':
                 '03cca0794e63cf147b879e0a3695f523',
                 'Maintainer':
                 'Jonas Maurus',
                 'Package':
                 'authserver',
                 'Priority':
                 'extra',
                 'Provides':
                 'maurusnet-authserver',
                 'SHA1':
                 '9a77a31dba51f612ee08ee096381f0c7e8f97a42',
                 'SHA256':
                 '63555a135bf0aa1762d09fc622881aaf352cdb3b244da5d78278c7efa2dba8b7',
                 'SHA512':
                 '01f9ca888014599374bf7a2c8c46f895d7ef0dfea99dfd092007f9fc5d5fe57a2755b843eda296b65cb6ac'
                 '0f64b9bd88b507221a71825f5329fdda0e58728cd7',
                 'Section':
                 'default',
                 'ShortKey':
                 'Pamd64 authserver 0.1.14~dev0-1',
                 'Size':
                 '26623042',
                 'Vendor':
                 'root@test',
                 'Version':
                 '0.1.14~dev0-1'
             }))
 def test_drop(self, *, rmock: requests_mock.Mocker) -> None:
     rmock.delete("http://test/api/publish/s3%3Amyendpoint%3Atest_a__1/test?force=1", text='{}')
     self.papi.drop(prefix='s3:myendpoint:test/a_1', distribution='test', force_delete=True)
Ejemplo n.º 3
0
    def test_adding_mobile_afterwards(
            self, mock_requests: requests_mock.Mocker) -> None:
        """Adding the mobile information after already syncing."""

        self._user_db.user.insert_many([
            {
                'registeredAt': '2018-09-03T10:57:12Z',
                'clientMetrics': {
                    'amplitudeId': 'Not Found'
                },
            },
            {
                '_id': mongomock.ObjectId('7ed900dbfbebd00000000004'),
                'registeredAt': '2018-09-03T10:57:12Z',
                'clientMetrics': {
                    'amplitudeId': '1234',
                    'firstSessionDurationSeconds': 5,
                },
            },
            {
                '_id': mongomock.ObjectId('7ed900dbfbebd00000000999'),
                'registeredAt': '2018-09-03T10:58:12Z',
                'clientMetrics': {
                    'amplitudeId': '5678',
                    'firstSessionDurationSeconds': 10,
                },
            },
            {
                'registeredAt': '2018-09-03T10:58:12Z',
                'clientMetrics': {
                    'amplitudeId': 'REDACTED',
                    'firstSessionDurationSeconds': 10,
                },
            },
        ])

        mock_requests.get(
            'https://amplitude.com/api/2/useractivity?user=1234&limit=5',
            json={
                'events': [
                    {
                        'event_time': '2017-10-24 10:41:00.412000',
                        'event_properties': {
                            'Mobile Version': True,
                        },
                    },
                ]
            })
        mock_requests.get(
            'https://amplitude.com/api/2/useractivity?user=5678&limit=5',
            json={'events': []})

        sync_amplitude.main([
            '--registered-from', '2018-08-14', '--registered-to', '2018-09-04',
            '--disable-sentry', '--no-dry-run'
        ])

        user = user_pb2.User()
        proto.parse_from_mongo(
            self._user_db.user.find_one(
                mongomock.ObjectId('7ed900dbfbebd00000000004')), user)
        self.assertEqual('1234', user.client_metrics.amplitude_id)
        self.assertEqual(5, user.client_metrics.first_session_duration_seconds)
        self.assertEqual(boolean_pb2.TRUE,
                         user.client_metrics.is_first_session_mobile)
Ejemplo n.º 4
0
 def test_upload_failed(self, *, rmock: requests_mock.Mocker) -> None:
     rmock.post("http://test/api/files/test", text='["test/testpkg.deb"]',
                status_code=500)
     with self.assertRaises(AptlyAPIException):
         self.fapi.upload("test", os.path.join(os.path.dirname(__file__), "testpkg.deb"))
Ejemplo n.º 5
0
 def test_list_dir(self, *, rmock: requests_mock.Mocker) -> None:
     rmock.get("http://test/api/files/dir",
               text='["dir/aptly_0.9~dev+217+ge5d646c_i386.deb"]')
     self.assertListEqual(self.fapi.list("dir"),
                          ["dir/aptly_0.9~dev+217+ge5d646c_i386.deb"])
Ejemplo n.º 6
0
async def test_options_flow(
    hass: HomeAssistant,
    mock_mjpeg_requests: Mocker,
    init_integration: MockConfigEntry,
) -> None:
    """Test options config flow."""
    result = await hass.config_entries.options.async_init(
        init_integration.entry_id)

    assert result.get("type") == FlowResultType.FORM
    assert result.get("step_id") == "init"
    assert "flow_id" in result

    # Register a second camera
    mock_mjpeg_requests.get("https://example.com/second_camera", text="resp")
    mock_second_config_entry = MockConfigEntry(
        title="Another Camera",
        domain=DOMAIN,
        data={},
        options={
            CONF_AUTHENTICATION: HTTP_BASIC_AUTHENTICATION,
            CONF_MJPEG_URL: "https://example.com/second_camera",
            CONF_PASSWORD: "",
            CONF_STILL_IMAGE_URL: None,
            CONF_USERNAME: None,
            CONF_VERIFY_SSL: True,
        },
    )
    mock_second_config_entry.add_to_hass(hass)

    # Try updating options to already existing secondary camera
    result2 = await hass.config_entries.options.async_configure(
        result["flow_id"],
        user_input={
            CONF_MJPEG_URL: "https://example.com/second_camera",
        },
    )

    assert result2.get("type") == FlowResultType.FORM
    assert result2.get("step_id") == "init"
    assert result2.get("errors") == {"mjpeg_url": "already_configured"}
    assert "flow_id" in result2

    assert mock_mjpeg_requests.call_count == 1

    # Test connectione error on MJPEG url
    mock_mjpeg_requests.get("https://example.com/invalid_mjpeg",
                            exc=requests.exceptions.ConnectionError)
    result3 = await hass.config_entries.options.async_configure(
        result2["flow_id"],
        user_input={
            CONF_MJPEG_URL: "https://example.com/invalid_mjpeg",
            CONF_STILL_IMAGE_URL: "https://example.com/still",
        },
    )

    assert result3.get("type") == FlowResultType.FORM
    assert result3.get("step_id") == "init"
    assert result3.get("errors") == {"mjpeg_url": "cannot_connect"}
    assert "flow_id" in result3

    assert mock_mjpeg_requests.call_count == 2

    # Test connectione error on still url
    mock_mjpeg_requests.get("https://example.com/invalid_still",
                            exc=requests.exceptions.ConnectionError)
    result4 = await hass.config_entries.options.async_configure(
        result3["flow_id"],
        user_input={
            CONF_MJPEG_URL: "https://example.com/mjpeg",
            CONF_STILL_IMAGE_URL: "https://example.com/invalid_still",
        },
    )

    assert result4.get("type") == FlowResultType.FORM
    assert result4.get("step_id") == "init"
    assert result4.get("errors") == {"still_image_url": "cannot_connect"}
    assert "flow_id" in result4

    assert mock_mjpeg_requests.call_count == 4

    # Invalid credentials
    mock_mjpeg_requests.get("https://example.com/invalid_auth",
                            text="Access Denied!",
                            status_code=401)
    result5 = await hass.config_entries.options.async_configure(
        result4["flow_id"],
        user_input={
            CONF_MJPEG_URL: "https://example.com/invalid_auth",
            CONF_PASSWORD: "******",
            CONF_USERNAME: "******",
        },
    )

    assert result5.get("type") == FlowResultType.FORM
    assert result5.get("step_id") == "init"
    assert result5.get("errors") == {"username": "******"}
    assert "flow_id" in result5

    assert mock_mjpeg_requests.call_count == 6

    # Finish
    result6 = await hass.config_entries.options.async_configure(
        result5["flow_id"],
        user_input={
            CONF_MJPEG_URL: "https://example.com/mjpeg",
            CONF_PASSWORD: "******",
            CONF_USERNAME: "******",
        },
    )

    assert result6.get("type") == FlowResultType.CREATE_ENTRY
    assert result6.get("data") == {
        CONF_AUTHENTICATION: HTTP_BASIC_AUTHENTICATION,
        CONF_MJPEG_URL: "https://example.com/mjpeg",
        CONF_PASSWORD: "******",
        CONF_STILL_IMAGE_URL: None,
        CONF_USERNAME: "******",
        CONF_VERIFY_SSL: True,
    }

    assert mock_mjpeg_requests.call_count == 7
def cf_endpoint(requests_mock: Mocker):
    requests_mock.put(TEST_RESPONSE_URL)
    return requests_mock
Ejemplo n.º 8
0
 def test_returns_nothing_if_activated(self, m: rm.Mocker):
     scene = create_scene()
     m.get('/planet/activate/planetscope/test-scene-id', text='')
     url = scenes.activate(scene, 'test-planet-api-key', 'test-user-id')
     self.assertIsNone(url)
Ejemplo n.º 9
0
def mock_nrc_oas_get(m: Mocker) -> None:
    oas_url = "https://notificaties-api.vng.cloud/api/v1/schema/openapi.yaml?v=3"
    with open(NRC_API_SPEC, "rb") as api_spec:
        m.get(oas_url, content=api_spec.read())
 def init(self, requests_mock: Mocker):
     self.requests_mocker = requests_mock
     requests_mock.register_uri(rq_mock.ANY,
                                rq_mock.ANY,
                                text=self._mock_all)
     cm._ngshare_url = NGSHARE_URL
Ejemplo n.º 11
0
 def test_activates_if_inactive(self, m: rm.Mocker):
     scene = create_scene()
     m.get('/planet/activate/planetscope/test-scene-id', text='')
     scenes.activate(scene, 'test-planet-api-key', 'test-user-id')
     self.assertEqual(1, len(m.request_history))
Ejemplo n.º 12
0
def mock_service_oas_get(m: Mocker, url: str, service: str, oas_url: str = "") -> None:
    if not oas_url:
        oas_url = f"{url}schema/openapi.yaml?v=3"
    content = read_schema(service)
    m.get(oas_url, content=content)
Ejemplo n.º 13
0
def test_download_file_400(tmp_path: Path, requests_mock: Mocker):
    requests_mock.get("http://foo.bar", status_code=400)
    tmp_file = tmp_path / "file.json"
    with pytest.raises(HTTPError):
        mtgjson_downloader.download_file(url="http://foo.bar", path=tmp_file)
    assert not tmp_file.exists()
Ejemplo n.º 14
0
def test_download_file(tmp_path: Path, requests_mock: Mocker):
    requests_mock.get("http://foo.bar", json={"ok": True})
    tmp_file = tmp_path / "file.json"
    mtgjson_downloader.download_file(url="http://foo.bar", path=tmp_file)
    assert tmp_file.is_file()
Ejemplo n.º 15
0
 def setup_mock_data(self, mocker: requests_mock.Mocker) -> None:
     """Setup mock handler for pushshift requests."""
     url = 'https://mediacloud.pushshift.io/rs/_search'
     mocker.get(url, text=_mock_pushshift)
Ejemplo n.º 16
0
 def test_delete(self, *, rmock: requests_mock.Mocker) -> None:
     rmock.delete("http://test/api/snapshots/aptly-repo-1", text='{}')
     self.sapi.delete("aptly-repo-1", force=True)
Ejemplo n.º 17
0
async def test_connection_error(
    hass: HomeAssistant,
    mock_mjpeg_requests: Mocker,
    mock_setup_entry: AsyncMock,
) -> None:
    """Test connection error."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": SOURCE_USER})

    assert result.get("type") == FlowResultType.FORM
    assert result.get("step_id") == SOURCE_USER
    assert "flow_id" in result

    # Test connectione error on MJPEG url
    mock_mjpeg_requests.get("https://example.com/mjpeg",
                            exc=requests.exceptions.ConnectionError)
    result2 = await hass.config_entries.flow.async_configure(
        result["flow_id"],
        user_input={
            CONF_NAME: "My cam",
            CONF_MJPEG_URL: "https://example.com/mjpeg",
            CONF_STILL_IMAGE_URL: "https://example.com/still",
        },
    )

    assert result2.get("type") == FlowResultType.FORM
    assert result2.get("step_id") == SOURCE_USER
    assert result2.get("errors") == {"mjpeg_url": "cannot_connect"}
    assert "flow_id" in result2

    assert len(mock_setup_entry.mock_calls) == 0
    assert mock_mjpeg_requests.call_count == 1

    # Reset
    mock_mjpeg_requests.get("https://example.com/mjpeg", text="resp")

    # Test connectione error on still url
    mock_mjpeg_requests.get("https://example.com/still",
                            exc=requests.exceptions.ConnectionError)
    result3 = await hass.config_entries.flow.async_configure(
        result2["flow_id"],
        user_input={
            CONF_NAME: "My cam",
            CONF_MJPEG_URL: "https://example.com/mjpeg",
            CONF_STILL_IMAGE_URL: "https://example.com/still",
        },
    )

    assert result3.get("type") == FlowResultType.FORM
    assert result3.get("step_id") == SOURCE_USER
    assert result3.get("errors") == {"still_image_url": "cannot_connect"}
    assert "flow_id" in result3

    assert len(mock_setup_entry.mock_calls) == 0
    assert mock_mjpeg_requests.call_count == 3

    # Reset
    mock_mjpeg_requests.get("https://example.com/still", text="resp")

    # Finish
    result4 = await hass.config_entries.flow.async_configure(
        result3["flow_id"],
        user_input={
            CONF_NAME: "My cam",
            CONF_MJPEG_URL: "https://example.com/mjpeg",
            CONF_STILL_IMAGE_URL: "https://example.com/still",
        },
    )

    assert result4.get("type") == FlowResultType.CREATE_ENTRY
    assert result4.get("title") == "My cam"
    assert result4.get("data") == {}
    assert result4.get("options") == {
        CONF_AUTHENTICATION: HTTP_BASIC_AUTHENTICATION,
        CONF_MJPEG_URL: "https://example.com/mjpeg",
        CONF_PASSWORD: "",
        CONF_STILL_IMAGE_URL: "https://example.com/still",
        CONF_USERNAME: None,
        CONF_VERIFY_SSL: True,
    }

    assert len(mock_setup_entry.mock_calls) == 1
    assert mock_mjpeg_requests.call_count == 5
Ejemplo n.º 18
0
    def test_list_packages_details(self, *,
                                   rmock: requests_mock.Mocker) -> None:
        rmock.get(
            "http://test/api/snapshots/aptly-repo-1/packages",
            text=
            '[{"Architecture":"all","Depends":"postgresql-9.6-postgis-2.3-scripts",'
            '"Description":" transitional dummy package\\n This is a transitional dummy package. '
            'It can safely be removed.\\n",'
            '"Filename":"postgresql-9.6-postgis-scripts_2.3.2+dfsg-1~exp2.pgdg90+1_all.deb",'
            '"FilesHash":"5f70af798690300d",'
            '"Homepage":"http://postgis.net/",'
            '"Installed-Size":"491",'
            '"Key":"Pall postgresql-9.6-postgis-scripts 2.3.2+dfsg-1~exp2.pgdg90+1 5f70af798690300d",'
            '"MD5sum":"56de7bac497e4ac34017f4d11e75fffb",'
            '"Maintainer":"Debian GIS Project \[email protected]\u003e",'
            '"Package":"postgresql-9.6-postgis-scripts",'
            '"Priority":"extra",'
            '"SHA1":"61bb9250e7a35be9b78808944e8cfbae1e70f67d",'
            '"SHA256":"01c0c4645e9100f7ddb6d05a9d36ad3866ac8d2e412b7c04163a9e65397ce05e",'
            '"Section":"oldlibs",'
            '"ShortKey":"Pall postgresql-9.6-postgis-scripts 2.3.2+dfsg-1~exp2.pgdg90+1",'
            '"Size":"468824","Source":"postgis","Version":"2.3.2+dfsg-1~exp2.pgdg90+1"}]'
        )
        parsed = self.sapi.list_packages(
            "aptly-repo-1",
            query="Name (% postgresql-9.6.-postgis-sc*)",
            detailed=True,
            with_deps=True)[0]
        expected = Package(
            key=
            'Pall postgresql-9.6-postgis-scripts 2.3.2+dfsg-1~exp2.pgdg90+1 5f70af798690300d',
            short_key=
            'Pall postgresql-9.6-postgis-scripts 2.3.2+dfsg-1~exp2.pgdg90+1',
            files_hash='5f70af798690300d',
            fields={
                'Maintainer':
                'Debian GIS Project <*****@*****.**>',
                'Size':
                '468824',
                'MD5sum':
                '56de7bac497e4ac34017f4d11e75fffb',
                'ShortKey':
                'Pall postgresql-9.6-postgis-scripts 2.3.2+dfsg-1~exp2.pgdg90+1',
                'FilesHash':
                '5f70af798690300d',
                'Filename':
                'postgresql-9.6-postgis-scripts_2.3.2+dfsg-1~exp2.pgdg90+1_all.deb',
                'Section':
                'oldlibs',
                'Homepage':
                'http://postgis.net/',
                'Description':
                ' transitional dummy package\n This is a transitional dummy package. '
                'It can safely be removed.\n',
                'Architecture':
                'all',
                'Priority':
                'extra',
                'Source':
                'postgis',
                'SHA1':
                '61bb9250e7a35be9b78808944e8cfbae1e70f67d',
                'Installed-Size':
                '491',
                'Version':
                '2.3.2+dfsg-1~exp2.pgdg90+1',
                'Depends':
                'postgresql-9.6-postgis-2.3-scripts',
                'Key':
                'Pall postgresql-9.6-postgis-scripts 2.3.2+dfsg-1~exp2.pgdg90+1 5f70af798690300d',
                'SHA256':
                '01c0c4645e9100f7ddb6d05a9d36ad3866ac8d2e412b7c04163a9e65397ce05e',
                'Package':
                'postgresql-9.6-postgis-scripts'
            })

        # mypy should detect this as ensuring that parsed.fields is not None, but it doesn't
        self.assertIsNotNone(parsed.fields)
        self.assertIsNotNone(expected.fields)

        self.assertDictEqual(
            parsed.fields if parsed.fields else
            {},  # make sure that mypy doesn't error on this being potentially None
            expected.fields if expected.fields else
            {},  # this can't happen unless Package.__init__ is fubared
        )
Ejemplo n.º 19
0
async def test_full_flow_with_authentication_error(
    hass: HomeAssistant,
    mock_mjpeg_requests: Mocker,
    mock_setup_entry: AsyncMock,
) -> None:
    """Test the full user configuration flow with invalid credentials.

    This tests tests a full config flow, with a case the user enters an invalid
    credentials, but recovers by entering the correct ones.
    """
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": SOURCE_USER})

    assert result.get("type") == FlowResultType.FORM
    assert result.get("step_id") == SOURCE_USER
    assert "flow_id" in result

    mock_mjpeg_requests.get("https://example.com/mjpeg",
                            text="Access Denied!",
                            status_code=401)
    result2 = await hass.config_entries.flow.async_configure(
        result["flow_id"],
        user_input={
            CONF_NAME: "Sky cam",
            CONF_MJPEG_URL: "https://example.com/mjpeg",
            CONF_PASSWORD: "******",
            CONF_USERNAME: "******",
        },
    )

    assert result2.get("type") == FlowResultType.FORM
    assert result2.get("step_id") == SOURCE_USER
    assert result2.get("errors") == {"username": "******"}
    assert "flow_id" in result2

    assert len(mock_setup_entry.mock_calls) == 0
    assert mock_mjpeg_requests.call_count == 2

    mock_mjpeg_requests.get("https://example.com/mjpeg", text="resp")
    result3 = await hass.config_entries.flow.async_configure(
        result2["flow_id"],
        user_input={
            CONF_NAME: "Sky cam",
            CONF_MJPEG_URL: "https://example.com/mjpeg",
            CONF_PASSWORD: "******",
            CONF_USERNAME: "******",
        },
    )

    assert result3.get("type") == FlowResultType.CREATE_ENTRY
    assert result3.get("title") == "Sky cam"
    assert result3.get("data") == {}
    assert result3.get("options") == {
        CONF_AUTHENTICATION: HTTP_BASIC_AUTHENTICATION,
        CONF_MJPEG_URL: "https://example.com/mjpeg",
        CONF_PASSWORD: "******",
        CONF_STILL_IMAGE_URL: None,
        CONF_USERNAME: "******",
        CONF_VERIFY_SSL: True,
    }

    assert len(mock_setup_entry.mock_calls) == 1
    assert mock_mjpeg_requests.call_count == 3
Ejemplo n.º 20
0
def test_list_project(
    api_url: str,
    iguazio_client: mlrun.api.utils.clients.iguazio.Client,
    requests_mock: requests_mock_package.Mocker,
):
    mock_projects = [
        {"name": "project-name-1"},
        {"name": "project-name-2", "description": "project-description-2"},
        {"name": "project-name-3", "owner": "some-owner"},
        {"name": "project-name-4", "labels": {"key": "value"}},
        {
            "name": "project-name-5",
            "annotations": {"annotation-key": "annotation-value"},
        },
        {
            "name": "project-name-6",
            "description": "project-description-4",
            "owner": "some-owner",
            "labels": {"key2": "value2"},
            "annotations": {"annotation-key2": "annotation-value2"},
        },
    ]
    response_body = {
        "data": [
            _build_project_response(
                iguazio_client,
                _generate_project(
                    mock_project["name"],
                    mock_project.get("description", ""),
                    mock_project.get("labels", {}),
                    mock_project.get("annotations", {}),
                    owner=mock_project.get("owner", None),
                ),
            )
            for mock_project in mock_projects
        ]
    }
    requests_mock.get(f"{api_url}/api/projects", json=response_body)
    projects, latest_updated_at = iguazio_client.list_projects(None)
    for index, project in enumerate(projects):
        assert project.metadata.name == mock_projects[index]["name"]
        assert project.spec.description == mock_projects[index].get("description")
        assert project.spec.owner == mock_projects[index].get("owner")
        assert (
            deepdiff.DeepDiff(
                mock_projects[index].get("labels"),
                project.metadata.labels,
                ignore_order=True,
            )
            == {}
        )
        assert (
            deepdiff.DeepDiff(
                mock_projects[index].get("annotations"),
                project.metadata.annotations,
                ignore_order=True,
            )
            == {}
        )
    assert (
        latest_updated_at.isoformat()
        == response_body["data"][-1]["attributes"]["updated_at"]
    )
Ejemplo n.º 21
0
 def test_upload_file(self, *, rmock: requests_mock.Mocker) -> None:
     rmock.post("http://test/api/files/test", text='["test/testpkg.deb"]')
     self.assertSequenceEqual(
         self.fapi.upload("test", os.path.join(os.path.dirname(__file__), "testpkg.deb")),
         ['test/testpkg.deb'],
     )
Ejemplo n.º 22
0
def test_create_project_failures(
    api_url: str,
    iguazio_client: mlrun.api.utils.clients.iguazio.Client,
    requests_mock: requests_mock_package.Mocker,
):
    """
    The exception handling is generic so no need to test it for every action (read/update/delete).
    There are basically 2 options:
    1. Validations failure - in this case job won't be triggered, and we'll get an error (http) response from iguazio
    2. Processing failure - this will happen inside the job, so we'll see the job finishing with failed state, sometimes
    the job result will have nice error messages for us
    """
    session = "1234"
    project = _generate_project()

    # mock validation failure
    error_message = "project name invalid or something"
    requests_mock.post(
        f"{api_url}/api/projects",
        status_code=http.HTTPStatus.BAD_REQUEST.value,
        json={
            "errors": [
                {"status": http.HTTPStatus.BAD_REQUEST.value, "detail": error_message}
            ]
        },
    )

    with pytest.raises(
        mlrun.errors.MLRunBadRequestError, match=rf"(.*){error_message}(.*)"
    ):
        iguazio_client.create_project(
            session, project,
        )

    # mock job failure - with nice error message in result
    job_id = "1d4c9d25-9c5c-4a34-b052-c1d3665fec5e"

    requests_mock.post(
        f"{api_url}/api/projects",
        json=functools.partial(
            _verify_creation, iguazio_client, project, session, job_id
        ),
    )
    error_message = "failed creating project in Nuclio for example"
    job_result = json.dumps(
        {"status": http.HTTPStatus.BAD_REQUEST.value, "message": error_message}
    )
    _mock_job_progress(
        api_url,
        requests_mock,
        session,
        job_id,
        mlrun.api.utils.clients.iguazio.JobStates.failed,
        job_result,
    )

    with pytest.raises(
        mlrun.errors.MLRunBadRequestError, match=rf"(.*){error_message}(.*)"
    ):
        iguazio_client.create_project(
            session, project,
        )

    # mock job failure - without nice error message (shouldn't happen, but let's test)
    _mock_job_progress(
        api_url,
        requests_mock,
        session,
        job_id,
        mlrun.api.utils.clients.iguazio.JobStates.failed,
    )

    with pytest.raises(mlrun.errors.MLRunRuntimeError):
        iguazio_client.create_project(
            session, project,
        )
Ejemplo n.º 23
0
 def test_list(self, *, rmock: requests_mock.Mocker) -> None:
     rmock.get("http://test/api/files", text='["aptly-0.9"]')
     self.assertListEqual(self.fapi.list(), ["aptly-0.9"])
Ejemplo n.º 24
0
def test_match_not_found(table, mock_response_single):
    params = urlencode({"FilterByFormula": "{Value}='abc'"})
    with Mocker() as mock:
        mock.get(table.url_table + "?" + params, status_code=200, json={"records": []})
        resp = table.match("Value", "abc")
    assert resp == {}
Ejemplo n.º 25
0
 def test_delete(self, *, rmock: requests_mock.Mocker) -> None:
     rmock.delete("http://test/api/files/test", text='{}')
     self.fapi.delete("test")
Ejemplo n.º 26
0
def test_find_branch_point_raise_error(fx_session: scoped_session, code: int):
    node = Node(url='http://test.neko')
    with raises(NodeUnavailable), Mocker() as m:
        m.get('http://test.neko/blocks/1', status_code=500)
        find_branch_point(node, fx_session, 1, 1)
Ejemplo n.º 27
0
    def test_get_cube_info(self, m: requests_mock.Mocker):
        m.post(f'{self.ENDPOINT_URL}oauth/token',
               json={
                   "access_token": "4ccsstkn983456jkfde",
                   "token_type": "bearer"
               })

        m.post(f'{self.ENDPOINT_URL}cubegens/info',
               json={
                   "status": "ok",
                   "result": {
                       "dataset_descriptor": {
                           "data_id": "CHL",
                           "data_type": "dataset",
                           "crs": "WGS84",
                           "bbox": [12.2, 52.1, 13.9, 54.8],
                           "time_range": ["2018-01-01", "2010-01-06"],
                           "time_period": "4D",
                           "data_vars": {
                               "B01": {
                                   "name": "B01",
                                   "dtype": "float32",
                                   "dims": ["time", "lat", "lon"],
                               },
                               "B02": {
                                   "name": "B02",
                                   "dtype": "float32",
                                   "dims": [
                                       "time",
                                       "lat",
                                       "lon"
                                   ],
                               },
                               "B03": {
                                   "name": "B03",
                                   "dtype": "float32",
                                   "dims": ["time", "lat", "lon"],
                               }
                           },
                           "spatial_res": 0.05,
                           "dims": {"time": 0, "lat": 54, "lon": 34}
                       },
                       "size_estimation": {
                           "image_size": [34, 54],
                           "tile_size": [34, 54],
                           "num_variables": 3,
                           "num_tiles": [1, 1],
                           "num_requests": 0,
                           "num_bytes": 0
                       },
                       "cost_estimation": {
                           'required': 3782,
                           'available': 234979,
                           'limit': 10000
                       }
                   }
               })

        result = self.generator.get_cube_info(self.REQUEST)
        self.assertIsInstance(result, CubeInfoWithCostsResult)
        cube_info = result.result
        self.assertIsInstance(cube_info, CubeInfoWithCosts)
        self.assertIsInstance(cube_info.dataset_descriptor, DatasetDescriptor)
        self.assertIsInstance(cube_info.size_estimation, dict)
        self.assertIsInstance(cube_info.cost_estimation, CostEstimation)
        self.assertEqual(3782, cube_info.cost_estimation.required)
        self.assertEqual(234979, cube_info.cost_estimation.available)
        self.assertEqual(10000, cube_info.cost_estimation.limit)
 def test_api_key_good_but_callhub_misbehaving(self):
     with Mocker() as mock:
         mock.get("https://api.callhub.io/v1/agents/", json={'garbagedata': 'callhub api misbehaving'})
         self.assertRaises(RuntimeError, CallHub, "https://api.callhub.io", api_key="G00D4P1K3YBUTC4LLHUB1S4CT1NGUP")
Ejemplo n.º 29
0
 def _setUp(self):
     self._requests = Mocker()
     self._requests.start()
     self.addCleanup(self._requests.stop)
Ejemplo n.º 30
0
def req_mock():
    with Mocker() as m:
        yield m