Esempio n. 1
0
    def test_create_new_component(self):
        lib = SW360(self.MYURL, self.MYTOKEN, False)
        lib.force_no_session = True
        self._add_login_response()
        actual = lib.login_api()
        self.assertTrue(actual)

        responses.add(
            responses.POST,
            url=self.MYURL + "resource/api/components",
            json={
                # server returns complete component, here we only mock a part of it
                'name': 'NewComponent',
                '_links': {
                    'self': {
                        'href': self.MYURL+'resource/api/components/2402'
                    }
                }
            },
            match=[
              responses.json_params_matcher({
                "name": "NewComponent",
                "componentType": "OSS",
                "description": "Illustrative example component",
                "homepage": "https://www.github.com/NewComponent"
              })
            ]
        )
        lib.create_new_component(
            name="NewComponent",
            component_type="OSS",
            description="Illustrative example component",
            homepage="https://www.github.com/NewComponent"
        )
Esempio n. 2
0
 def test_create_new_project_already_exists(self):
     lib = self.get_logged_in_lib()
     responses.add(
         responses.POST,
         url=self.MYURL + "resource/api/projects",
         json={
           "timestamp": "2020-12-13T20:32:17.799234Z", "status": 409,
           "error": "Conflict",
           "message": "sw360 project with name \'NewProduct\' already exists."
         },
         status=409,
         match=[
           responses.json_params_matcher({
             "name": "NewProduct", "version": "42",
             "description": "Example Product",
             "projectType": "PRODUCT", "visibility": "EVERYONE",
           })
         ]
     )
     with self.assertRaises(SW360Error) as context:
         lib.create_new_project(
             name="NewProduct", version="42",
             description="Example Product",
             project_type="PRODUCT", visibility="EVERYONE",
         )
     self.assertEqual(409, context.exception.response.status_code)
Esempio n. 3
0
    def test_create_new_component_fail(self):
        lib = SW360(self.MYURL, self.MYTOKEN, False)
        lib.force_no_session = True
        self._add_login_response()
        actual = lib.login_api()
        self.assertTrue(actual)

        responses.add(
            responses.POST,
            url=self.MYURL + "resource/api/components",
            json={
                "timestamp": "2020-12-12T19:15:18.702505Z",
                "error": "Conflict",
                "message": "sw360 component with name \'NewComponent\' already exists."
            },
            status=409,
            match=[
              responses.json_params_matcher({
                "name": "NewComponent",
                "componentType": "OSS",
                "description": "Illustrative example component",
                "homepage": "https://www.github.com/NewComponent"
              })
            ]
        )

        with self.assertRaises(SW360Error) as context:
            lib.create_new_component(
                name="NewComponent",
                component_type="OSS",
                description="Illustrative example component",
                homepage="https://www.github.com/NewComponent"
            )
        self.assertEqual(409, context.exception.response.status_code)
Esempio n. 4
0
    def test_update_component_external_id_no_extids_yet(self):
        lib = SW360(self.MYURL, self.MYTOKEN, False)
        lib.force_no_session = True
        self._add_login_response()
        actual = lib.login_api()
        self.assertTrue(actual)

        responses.add(
            responses.GET,
            url=self.MYURL + "resource/api/components/bc75c910ca9866886cb4d7b3a301061f",  # noqa
            body='{"name": "debootstrap", "componentType": "OSS"}',  # noqa
            status=200,
            content_type="application/json",
            adding_headers={"Authorization": "Token " + self.MYTOKEN},
        )

        # add fresh id
        responses.add(
            responses.PATCH,
            url=self.MYURL + "resource/api/components/bc75c910ca9866886cb4d7b3a301061f",
            body="4",
            match=[
              responses.json_params_matcher({"externalIds": {"package-url": "pkg:deb/debian/debootstrap?type=source"}})  # noqa
            ]
        )

        lib.update_component_external_id(
            "package-url",
            "pkg:deb/debian/debootstrap?type=source",
            "bc75c910ca9866886cb4d7b3a301061f")
Esempio n. 5
0
    def test_update_component_external_id_no_exist(self):
        lib = SW360(self.MYURL, self.MYTOKEN, False)
        lib.force_no_session = True
        self._add_login_response()
        actual = lib.login_api()
        self.assertTrue(actual)

        responses.add(
            method=responses.GET,
            url=self.MYURL + "resource/api/components/bc75c910ca9866886cb4d7b3a301061f",  # noqa
            body='{"name": "debootstrap", "componentType": "OSS", "externalIds": {"already-existing": "must-be-kept"}}',  # noqa
            status=200,
            content_type="application/json",
            adding_headers={"Authorization": "Token " + self.MYTOKEN},
        )

        # assure patch request doesn't happen if deleting non-existent id
        responses.add(
            responses.PATCH,
            url=self.MYURL + "resource/api/components/bc75c910ca9866886cb4d7b3a301061f",
            body="4",
            match=[
                responses.json_params_matcher(
                    {
                        "externalIds": {"xxx": "pkg:deb/debian/debootstrap?type=source"}
                    }
                )
            ]
        )

        lib.update_component_external_id(
            "package-url",
            "",
            "bc75c910ca9866886cb4d7b3a301061f",
            update_mode="delete")
Esempio n. 6
0
    def test_update_project_external_id_add_fresh_id(self):
        lib = self.get_logged_in_lib()

        responses.add(
            method=responses.GET,
            url=self.MYURL + "resource/api/projects/123",  # noqa
            body='{"name": "Tethys.Logging", "version": "1.4.0", "externalIds": {"already-existing": "must-be-kept"}}',  # noqa
            status=200,
            content_type="application/json",
            adding_headers={"Authorization": "Token " + self.MYTOKEN},
        )

        # add fresh id
        responses.add(
            responses.PATCH,
            url=self.MYURL + "resource/api/projects/123",
            body="4",
            match=[
              responses.json_params_matcher({"externalIds": {"already-existing": "must-be-kept", "package-url": "pkg:deb/debian/debootstrap?type=source"}})  # noqa
            ]
        )

        lib.update_project_external_id(
            "package-url",
            "pkg:deb/debian/debootstrap?type=source",
            "123")
Esempio n. 7
0
 def test_create_new_project(self):
     lib = self.get_logged_in_lib()
     responses.add(
         responses.POST,
         url=self.MYURL + "resource/api/projects",
         json={
             # server returns complete project, here we only mock a part of it
             'name': 'NewProduct',
             '_links': {
                 'self': {
                     'href': self.MYURL+'resource/api/projects/0206'
                 }
             }
         },
         match=[
           responses.json_params_matcher({
             "name": "NewProduct", "version": "42",
             "description": "Example Product",
             "projectType": "PRODUCT", "visibility": "EVERYONE",
           })
         ]
     )
     lib.create_new_project(
         name="NewProduct", version="42",
         description="Example Product",
         project_type="PRODUCT", visibility="EVERYONE",
     )
Esempio n. 8
0
 def test_post(self):
     responses.add(responses.POST,
                   'https://d.qualtrics.com/API/v3/hello',
                   match=[responses.json_params_matcher({'a': 'a'})],
                   json={'result': {
                       'r': 'r'
                   }})
     self.assertEqual(self.q.post('hello', {'a': 'a'}), {'r': 'r'})
Esempio n. 9
0
def add_mock_detector_creation_response(**kwargs):
    match = [responses.json_params_matcher({"configuration": kwargs})
             ] if kwargs else []
    responses.add(responses.POST,
                  api_url('detectors/'),
                  json={'id': 'foobar'},
                  status=201,
                  match=match)
Esempio n. 10
0
 def test_post_create(self):
     responses.add(responses.POST,
                   'https://d.qualtrics.com/API/v3/hello',
                   match=[responses.json_params_matcher({'a': 'a'})],
                   json={'result': {
                       'doesntMatter': 'theId'
                   }})  # the key used for the id returned varies.
     self.assertEqual(self.q.postCreate('hello', {'a': 'a'}), 'theId')
Esempio n. 11
0
 def test_delete_consumed_items(self):
     # noinspection PyTypeChecker
     responses.add(
         method=responses.DELETE,
         url=self.client.BASE_URL + f"/user/consumed-items",
         match=[responses.json_params_matcher([UUID])],
     )
     response = self.client.delete_consumed_items(UUID)
     self.assertIsInstance(response, Response)
Esempio n. 12
0
    def test_create_run(self):
        run = CourseRunFactory()

        expected_data = self.make_studio_data(run)
        responses.add(responses.POST,
                      f'{self.studio_url}api/v1/course_runs/',
                      match=[responses.json_params_matcher(expected_data)])

        self.api.create_course_run_in_studio(run)
Esempio n. 13
0
    def test_create_rerun(self):
        run1 = CourseRunFactory()
        run2 = CourseRunFactory(course=run1.course)

        expected_data = self.make_studio_data(run2)
        responses.add(responses.POST,
                      f'{self.studio_url}api/v1/course_runs/{run1.key}/rerun/',
                      match=[responses.json_params_matcher(expected_data)])

        self.api.create_course_rerun_in_studio(run2, run1.key)
Esempio n. 14
0
def test_tiebreak_call():
    responses.add(responses.POST,
                  'http://padkp.net/api/tiebreak/',
                  match=[
                      responses.json_params_matcher(
                          {'characters': ['bob', 'ted', 'tom']})
                  ])

    resp = api_client.tiebreak(['bob', 'ted', 'tom'], '')

    assert resp.status_code == 200
Esempio n. 15
0
    def test_update_run(self):
        run = CourseRunFactory()

        expected_data = self.make_studio_data(run,
                                              add_pacing=False,
                                              add_schedule=False)
        responses.add(responses.PATCH,
                      f'{self.studio_url}api/v1/course_runs/{run.key}/',
                      match=[responses.json_params_matcher(expected_data)])

        self.api.update_course_run_details_in_studio(run)
Esempio n. 16
0
 def test_call(self):
     # Check logging and basic requests work OK:
     with self.assertLogs(level='INFO') as logs:
         responses.add(responses.PUT,
                       'https://a',
                       match=[responses.json_params_matcher({'a': 'a'})])
         self.q.put('https://a',
                    {'a': 'a'})  # Use PUT as the simplest with params
     self.assertEqual(len(logs.output), 1)
     self.assertRegex(logs.output[0],
                      "SimpleQualtrics.*https://a.*\{'a': 'a'\}")
Esempio n. 17
0
    def test_create_success(self, acme_id, response_headers, args, request_params):
        """The function should return the created ACME ID."""

        # Setup the mocked response
        responses.add(responses.POST, self.api_url, headers=response_headers,
                      match=[responses.json_params_matcher(request_params)],
                      status=201)

        acme = ACMEAccount(client=self.client)
        response = acme.create(*args)

        self.assertEqual(response, {"id": acme_id})
Esempio n. 18
0
def test_save_content(resp: RequestsMock, job_type: JobType, url: str,
                      item: ContentItem) -> None:
    with Api(job_type=job_type, url=url, api_key="aaa") as api:
        full_url = routes.content(job_type=job_type, url=api.url)
        resp.add(
            responses.POST,
            url=full_url,
            json=item.dict(),
            match=[responses.json_params_matcher(item.dict(by_alias=True))],
            status=200,
        )
        api.save(item)
Esempio n. 19
0
def test_api_post_success(resp: RequestsMock, api: Api,
                          json_dict: Any) -> None:
    url = f"{api.url}test"

    resp.add(
        responses.POST,
        url=url,
        json=json_dict,
        match=[responses.json_params_matcher(json_dict)],
        status=200,
    )

    assert api.post(url, json_dict) == json_dict
Esempio n. 20
0
def load_responses_fixtures(path) -> None:
    """Load a JSON fixture containing all the API response examples."""
    def _load_json_fixtures(path: str) -> List[Dict[str, Any]]:
        """Load JSON fixtures from file."""
        cwd: str = os.path.dirname(os.path.realpath(__file__))
        fixtures: str = os.path.join(os.path.join(cwd, 'fixtures'), path)
        with open(fixtures) as fixture:
            return json.load(fixture)

    def _get_responses_method(method: str) -> str:
        """Returns the responses method based upon the supplied method.

        Args:
            method (str): The response method.

        Raises:
            ValueError: if the specified method is invalid.
        """
        method = method.upper()
        if method == "GET":
            return responses.GET
        elif method == "POST":
            return responses.POST
        elif method == "DELETE":
            return responses.DELETE
        elif method == "PUT":
            return responses.PUT
        elif method == "PATCH":
            return responses.PATCH
        raise ValueError(f"Unable to find method '{method}' in responses")

    fixtures: List[Dict[str, Any]] = _load_json_fixtures(path)
    for fixture in fixtures:
        # Add the matchers for the request parameters or JSON body
        matchers: List[Any] = []
        if fixture.get('match_json_params'):
            matchers.append(
                responses.json_params_matcher(fixture['match_json_params']))
        if fixture.get('match_urlencoded_params'):
            matchers.append(
                responses.urlencoded_params_matcher(
                    fixture['match_urlencoded_params']))

        # Register the mocked response
        responses.add(_get_responses_method(fixture["method"]),
                      url=fixture["url"],
                      json=fixture.get("json"),
                      status=fixture["status"],
                      content_type=fixture.get("content_type",
                                               "application/json"),
                      match=matchers)
Esempio n. 21
0
    def test_create_failure_http_error(self, _, __, args, request_params):
        """
        The function should return an error code and description if the ACME
        Account creation failed.
        """

        # Setup the mocked response
        responses.add(responses.POST, self.api_url, json=self.error_response,
                      match=[responses.json_params_matcher(request_params)],
                      status=400)

        acme = ACMEAccount(client=self.client)

        self.assertRaises(HTTPError, acme.create, *args)
Esempio n. 22
0
    async def test_trigger_data_importer_validate_and_save_event_overwrite(
            self, monkeypatch):
        bot = 'test_events_bot_1'
        user = '******'
        event_url = "http://url.event2"
        monkeypatch.setitem(Utility.environment['model']['data_importer'],
                            "event_url", event_url)

        responses.add(
            "POST",
            event_url,
            json={"message": "Event triggered successfully!"},
            status=200,
            match=[
                responses.json_params_matcher([{
                    'name': 'BOT',
                    'value': bot
                }, {
                    'name': 'USER',
                    'value': user
                }, {
                    'name': 'IMPORT_DATA',
                    'value': '--import-data'
                }, {
                    'name': 'OVERWRITE',
                    'value': '--overwrite'
                }])
            ],
        )
        responses.start()
        await EventsTrigger.trigger_data_importer(bot, user, True, True)
        responses.stop()
        request = json.loads(responses.calls[1].request.body)

        logs = list(DataImporterLogProcessor.get_logs(bot))
        assert len(logs) == 1
        assert not logs[0].get('intents').get('data')
        assert not logs[0].get('stories').get('data')
        assert not logs[0].get('utterances').get('data')
        assert not logs[0].get('http_actions').get('data')
        assert not logs[0].get('training_examples').get('data')
        assert not logs[0].get('domain').get('data')
        assert not logs[0].get('config').get('data')
        assert not logs[0].get('exception')
        assert logs[0]['is_data_uploaded']
        assert logs[0]['start_timestamp']
        assert not logs[0].get('end_timestamp')
        assert not logs[0].get('status')
        assert logs[0]['event_status'] == EVENT_STATUS.TASKSPAWNED.value
Esempio n. 23
0
def test_fallback_count_range_with_kairon_client(mock_auth,
                                                 mock_mongo_processor):
    responses.add(
        responses.GET,
        f"https://localhost:8083/api/history/{pytest.bot}/trends/fallback",
        status=200,
        match=[
            responses.json_params_matcher({
                'month':
                6,
                'action_fallback':
                'action_default_fallback',
                'nlu_fallback':
                'utter_please_rephrase'
            })
        ],
        json={
            "data": {
                'fallback_count_rate': {
                    1: 25,
                    2: 24,
                    3: 28,
                    4: 26,
                    5: 20,
                    6: 25
                }
            }
        })

    response = client.get(
        f"/api/history/{pytest.bot}/metrics/trend/user/fallback",
        headers={
            "Authorization": pytest.token_type + " " + pytest.access_token
        },
    )

    actual = response.json()
    assert actual["error_code"] == 0
    assert actual["data"]["fallback_count_rate"] == {
        '1': 25,
        '2': 24,
        '3': 28,
        '4': 26,
        '5': 20,
        '6': 25
    }
    assert actual["message"] is None
    assert actual["success"]
    def test_profileSync_non_language_fields(self):
        """
        The view should retrieve the value of the Turn field and set the RapidPro
        field to match
        """
        connection = TurnRapidproConnection.objects.create(
            description="test connection",
            turn_url="https://turn_example.org",
            turn_api_token="test-token",
            rp_api_token="some-token",
            rp_url="https://rp_example.org",
            hmac_secret="test-secret",
        )
        turn_field = "test_turn_field"
        rp_field = "test_rp_field"

        responses.add(
            method=responses.GET,
            url="https://turn_example.org/v1/contacts/16505551234/profile",
            json={"fields": {
                turn_field: "turn_value"
            }})

        expected_data = {"fields": {rp_field: "turn_value"}}
        responses.add(
            method=responses.POST,
            url=
            "https://rp_example.org/api/v2/contacts.json?urn=whatsapp:16505551234",
            match=[responses.json_params_matcher(expected_data)])

        url = "{}?turn_field={}&rp_field={}".format(
            reverse("profileSync-profileSync", args=[connection.pk]),
            turn_field, rp_field)
        data = {
            "contacts": [{
                "profile": {
                    "name": "Example User"
                },
                "wa_id": "16505551234"
            }]
        }
        body = json.dumps(data, separators=(",", ":"))
        signature = generate_hmac_signature(body, connection.hmac_secret)
        response = self.client.post(url,
                                    data,
                                    format="json",
                                    HTTP_X_TURN_HOOK_SIGNATURE=signature)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
Esempio n. 25
0
 def test_add_product_to_favorites(self):
     # noinspection PyTypeChecker
     responses.add(
         method=responses.POST,
         url=self.client.BASE_URL + "/user/favorites/products",
         match=[
             responses.json_params_matcher({
                 "id": UUID,
                 "product_id": UUID,
                 "amount": 10
             })
         ],
     )
     response = self.client.add_product_to_favorites(id=UUID,
                                                     product_id=UUID,
                                                     amount=10)
     self.assertIsInstance(response, Response)
Esempio n. 26
0
 def test_add_product_to_favorites(self):
     # noinspection PyTypeChecker
     responses.add(
         method=responses.POST,
         url=self.client.BASE_URL + "/user/favorites/recipes",
         match=[
             responses.json_params_matcher({
                 "id": UUID,
                 "recipe_id": UUID,
                 "portion_count": 2
             })
         ],
     )
     response = self.client.add_recipe_to_favorites(id=UUID,
                                                    recipe_id=UUID,
                                                    portion_count=2)
     self.assertIsInstance(response, Response)
Esempio n. 27
0
    def run():
        responses.add(
            method=responses.POST,
            url="http://example.com/",
            body="one",
            match=[
                responses.json_params_matcher(
                    {"page": {
                        "name": "first",
                        "type": "json"
                    }})
            ],
        )
        responses.add(
            method=responses.POST,
            url="http://example.com/",
            body="two",
            match=[
                responses.urlencoded_params_matcher({
                    "page": "second",
                    "type": "urlencoded"
                })
            ],
        )

        resp = requests.request(
            "POST",
            "http://example.com/",
            headers={"Content-Type": "x-www-form-urlencoded"},
            data={
                "page": "second",
                "type": "urlencoded"
            },
        )
        assert_response(resp, "two")

        resp = requests.request(
            "POST",
            "http://example.com/",
            headers={"Content-Type": "application/json"},
            json={"page": {
                "name": "first",
                "type": "json"
            }},
        )
        assert_response(resp, "one")
Esempio n. 28
0
    def test_create_failure_http_status_unexpected(self, _, __, args,
                                                   request_params):
        """
        The function should return an error code and description if the ACME
        Account creation failed with ACMEAccountCreationResponseError
        (unexpected HTTP status code).
        """

        # Setup the mocked response
        responses.add(responses.POST, self.api_url, json=self.error_response,
                      match=[responses.json_params_matcher(request_params)],
                      status=200)  # unexpected status

        acme = ACMEAccount(client=self.client)

        self.assertRaises(ACMEAccountCreationResponseError, acme.create,
                          *args)
Esempio n. 29
0
def test_visitor_hit_fallback_with_kairon_client(mock_auth,
                                                 mock_mongo_processor):
    responses.add(
        responses.GET,
        f"https://localhost:8083/api/history/{pytest.bot}/metrics/fallback",
        status=200,
        json={"data": {
            'fallback_count': 10,
            'total_count': 90
        }},
        match=[
            responses.json_params_matcher({
                'month':
                1,
                'action_fallback':
                'action_default_fallback',
                'nlu_fallback':
                'utter_please_rephrase'
            })
        ],
    )

    steps = [{
        "name": "nlu_fallback",
        "type": "INTENT"
    }, {
        "name": "utter_please_rephrase",
        "type": "BOT"
    }]
    rule = {'name': 'fallback_rule', 'steps': steps, 'type': 'RULE'}
    MongoProcessor().add_complex_story(rule, pytest.bot, 'test')

    response = client.get(
        f"/api/history/{pytest.bot}/metrics/fallback",
        headers={
            "Authorization": pytest.token_type + " " + pytest.access_token
        },
    )

    actual = response.json()
    assert actual["error_code"] == 0
    assert actual["data"]["fallback_count"] == 10
    assert actual["data"]["total_count"] == 90
    assert actual["message"] is None
    assert actual["success"]
Esempio n. 30
0
    def test_create_failure_acme_id_not_found(self, _, response_headers, args,
                                              request_params):
        """
        The function should return an error code and description if the ACME
        Account creation failed with ACMEAccountCreationResponseError
        (ACME ID not found in response).
        """

        # Setup the mocked response
        responses.add(responses.POST, self.api_url, json=self.error_response,
                      headers=response_headers,
                      match=[responses.json_params_matcher(request_params)],
                      status=201)

        acme = ACMEAccount(client=self.client)

        self.assertRaises(ACMEAccountCreationResponseError, acme.create,
                          *args)