Ejemplo n.º 1
0
def test_validate_meta_not_added_when_there(config):
    responses.add(responses.POST,
                  f"{config.ds_url}/validation-requests",
                  status=200,
                  json={"success": True},
                  match=[matchers.json_params_matcher({})])
    assert dsctl.validate(config, {}, "", "event", True) is True
Ejemplo n.º 2
0
def test_promote_sends_the_right_body_validated_prod(config, deployment):
    responses.add(responses.POST,
                  f"{config.ds_url}/deployment-requests",
                  status=200,
                  json={"success": True},
                  match=[
                      matchers.json_params_matcher({
                          "name":
                          deployment.data_structure.name,
                          "vendor":
                          deployment.data_structure.vendor,
                          "format":
                          deployment.data_structure.format,
                          "version":
                          str(deployment.version),
                          "source":
                          "DEV",
                          "target":
                          "PROD",
                          "message":
                          "message"
                      })
                  ])

    assert dsctl.promote(
        config, deployment, "abcd", "message", to_production=True) is True
Ejemplo n.º 3
0
def test_main_flow_promote_to_prod(mocker, args, config, token_url,
                                   deployment):
    mocker.patch.object(args, 'promote_to_dev', False)
    mocker.patch.object(args, 'promote_to_prod', True)
    responses.add(responses.GET,
                  token_url,
                  json={"accessToken": "abcd"},
                  status=200)
    responses.add(responses.POST,
                  f"{config.ds_url}/deployment-requests",
                  status=200,
                  json={"success": True},
                  match=[
                      matchers.json_params_matcher({
                          "name":
                          deployment.data_structure.name,
                          "vendor":
                          deployment.data_structure.vendor,
                          "format":
                          deployment.data_structure.format,
                          "version":
                          str(deployment.version),
                          "source":
                          "DEV",
                          "target":
                          "PROD",
                          "message":
                          "No message provided"
                      })
                  ])
    assert dsctl.flow(args, config) is True
 def test_comfort_temperature_gets_changed(self):
     responses.add(
         responses.PUT,
         self.scheduler_endpoint,
         match=[json_params_matcher({"comfortTemperature": 20.5})],
     )
     self.client.set_comfort_temperature(20.5)
     self.assertEqual(1, len(responses.calls))
Ejemplo n.º 5
0
def test_scan_delete_many(nessus):
    responses.add(responses.DELETE,
                  'https://localhost:8834/scans',
                  json={'deleted': [1, 2, 3]},
                  match=[
                      matchers.json_params_matcher({'ids': [1, 2, 3]})
                  ]
                  )
    assert nessus.scans.delete_many([1, 2, 3]) == [1, 2, 3]
Ejemplo n.º 6
0
def test_create_template_for_tier_scope_ignore_type(
    fs,
    get_sync_templates_env,
    mocked_templates_response,
    mocked_responses,
):
    get_sync_templates_env['Templates']['C2'] = 'create'
    get_sync_templates_env['Templates']['A2'] = None
    get_sync_templates_env['Templates']['D2'] = 'tier1'
    get_sync_templates_env['Templates']['E2'] = 'fulfillment'

    get_sync_templates_env.save(f'{fs.root_path}/test.xlsx')

    stats = SynchronizerStats()
    synchronizer = TemplatesSynchronizer(
        client=ConnectClient(
            use_specs=False,
            api_key='ApiKey SU:123',
            endpoint='https://localhost/public/v1',
        ),
        silent=True,
        stats=stats,
    )

    mocked_responses.add(
        method='POST',
        url='https://localhost/public/v1/products/PRD-276-377-545/templates',
        match=[
            matchers.json_params_matcher({
                'name':
                'Template 1',
                'scope':
                'tier1',
                'body':
                ('# Template 1\n\n'
                 'This is **template 1** with the following parameters:\n\n'
                 '1. t0_o_email = {{ t0_o_email }}\n'
                 '2. t0_f_password = {{ t0_f_password }}\n'
                 '3. t0_f_text = {{ t0_f_text }}\n\n'
                 'Have a nice day!'),
            }),
        ],
        json=mocked_templates_response[0],
    )

    synchronizer.open(f'{fs.root_path}/test.xlsx', 'Templates')
    synchronizer.sync()

    assert stats['Templates'].get_counts_as_dict() == {
        'processed': 1,
        'created': 1,
        'updated': 0,
        'deleted': 0,
        'skipped': 0,
        'errors': 0,
    }
Ejemplo n.º 7
0
def test_policy_import(nessus):
    test_file = BytesIO(b'something to see here')
    responses.add(responses.POST,
                  'https://localhost:8834/file/upload',
                  json={'fileuploaded': 'example'})
    responses.add(responses.POST,
                  'https://localhost:8834/policies/import',
                  match=[matchers.json_params_matcher({'file': 'example'})],
                  json={'example': 'value'})
    assert nessus.policies.import_policy(test_file) == {'example': 'value'}
 def test_interval_can_be_added_for_tuesday_2_30_pm(self):
     tuesday = 60 * 24
     two_thirty = 14 * 60 + 30
     responses.add(
         responses.POST,
         self.scheduler_endpoint + "/intervals",
         match=[
             json_params_matcher({
                 "startTimeInMinutes": tuesday + two_thirty,
                 "durationInMinutes": 90,
             })
         ],
     )
     self.client.add_interval(Day.TUESDAY, 14, 30, 90)
     self.assertEqual(1, len(responses.calls))
Ejemplo n.º 9
0
def test_main_flow_validate(mocker, args, config, token_url, data_structure,
                            data_structure_with_meta):
    mocker.patch.object(args, 'promote_to_dev', False)
    mocker.patch.object(args, 'promote_to_prod', False)
    responses.add(responses.GET,
                  token_url,
                  json={"accessToken": "abcd"},
                  status=200)
    responses.add(
        responses.POST,
        f"{config.ds_url}/validation-requests",
        status=200,
        json={"success": True},
        match=[matchers.json_params_matcher(data_structure_with_meta)])
    assert dsctl.flow(args, config) is True
Ejemplo n.º 10
0
def test_validate_meta_added_when_not_there(config):
    responses.add(responses.POST,
                  f"{config.ds_url}/validation-requests",
                  status=200,
                  json={"success": True},
                  match=[
                      matchers.json_params_matcher({
                          "meta": {
                              "hidden": False,
                              "schemaType": "event",
                              "customData": {}
                          },
                          "data": {}
                      })
                  ])
    assert dsctl.validate(config, {}, "", "event", False) is True
Ejemplo n.º 11
0
def test_policy_edit(nessus):
    responses.add(responses.PUT,
                  'https://localhost:8834/policies/1',
                  json={'example': 'value'},
                  match=[
                      matchers.json_params_matcher({
                          'uuid': 'abcdef',
                          'settings': {
                              'name': 'example'
                          }
                      })
                  ])
    assert nessus.policies.edit(1, uuid='abcdef',
                                settings={'name': 'example'}) == {
                                    'example': 'value'
                                }
Ejemplo n.º 12
0
def test_retrigger_should_retrigger(responses, create_task):
    rev = "a" * 40
    branch = "autoland"
    push = Push(rev, branch)

    decision_task_url = f"{PRODUCTION_TASKCLUSTER_ROOT_URL}/api/index/v1/task/gecko.v2.{branch}.revision.{rev}.taskgraph.decision"
    responses.add(
        responses.GET, decision_task_url, status=200, json={"taskId": "a" * 10}
    )

    responses.add(
        responses.GET,
        get_artifact_url(push.decision_task.id, "public/actions.json"),
        status=200,
        json=RETRIGGER_ACTIONS_ARTIFACT_EXTRACT,
    )

    config._config["taskcluster_firefox_ci"] = {
        "client_id": "a client id",
        "access_token": "an access token",
    }

    task = create_task(label="foobar", tags={"retrigger": "true"})

    hookGroupId = RETRIGGER_ACTIONS_ARTIFACT_EXTRACT["actions"][0]["hookGroupId"]
    hookId = RETRIGGER_ACTIONS_ARTIFACT_EXTRACT["actions"][0]["hookId"].replace(
        "/", "%2F"
    )
    hookPayload = copy.deepcopy(
        RETRIGGER_ACTIONS_ARTIFACT_EXTRACT["actions"][0]["hookPayload"]
    )
    hookPayload["user"] = {
        "input": {"times": 3},
        "taskGroupId": push.decision_task.id,
        "taskId": task.id,
    }
    responses.add(
        responses.POST,
        f"{PRODUCTION_TASKCLUSTER_ROOT_URL}/api/hooks/v1/hooks/{hookGroupId}/{hookId}/trigger",
        status=200,
        json={"status": {"taskId": "new-retrigger-task"}},
        match=[matchers.json_params_matcher(hookPayload)],
    )

    assert task.retrigger(push) == "new-retrigger-task"
Ejemplo n.º 13
0
def test_scan_export(nessus):
    test_file = BytesIO(b'something to see here')
    responses.add(responses.POST,
                  'https://localhost:8834/scans/1/export',
                  match=[
                      matchers.json_params_matcher({
                          'format': 'nessus'
                      })
                  ],
                  json={'token': 'abcdef'}
                  )
    responses.add(responses.GET,
                  'https://localhost:8834/tokens/abcdef/status',
                  json={'status': 'ready'}
                  )
    responses.add(responses.GET,
                  'https://localhost:8834/tokens/abcdef/download',
                  body=test_file.read()
                  )
    test_file.seek(0)
    assert nessus.scans.export_scan(1).read() == test_file.read()
Ejemplo n.º 14
0
def test_scan_create(nessus):
    responses.add(responses.POST,
                  'https://localhost:8834/scans',
                  json={'example': 'value'},
                  match=[
                      matchers.json_params_matcher({
                          'uuid': 'abcdef12345667890abcdef',
                          'settings': {
                              'name': 'Example Scan',
                              'enabled': False,
                              'text_targets': '192.168.1.1'
                          }
                      })
                  ]
                  )
    assert nessus.scans.create(uuid='abcdef12345667890abcdef',
                               settings={
                                   'name': 'Example Scan',
                                   'enabled': False,
                                   'text_targets': '192.168.1.1'
                               }
                               ) == {'example': 'value'}
Ejemplo n.º 15
0
    def run():
        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            rsps.add(
                "POST",
                "http://example.com",
                match=[matchers.urlencoded_params_matcher({"foo": "bar"})],
            )
            rsps.add(
                "POST",
                "http://example.com",
                match=[matchers.json_params_matcher({"fail": "json"})],
            )

            with pytest.raises(ConnectionError) as excinfo:
                requests.post("http://example.com", data={"id": "bad"})

            msg = str(excinfo.value)
            assert (
                "request.body doesn't match: {id: bad} doesn't match {foo: bar}" in msg
            )

            assert (
                "request.body doesn't match: JSONDecodeError: Cannot parse request.body"
                in msg
            )

        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            rsps.add(
                "GET",
                "http://111.com",
                match=[matchers.query_param_matcher({"my": "params"})],
            )

            rsps.add(
                method=responses.GET,
                url="http://111.com/",
                body="two",
                match=[matchers.json_params_matcher({"page": "one"})],
            )

            with pytest.raises(ConnectionError) as excinfo:
                requests.get(
                    "http://111.com", params={"id": "bad"}, json={"page": "two"}
                )

            msg = str(excinfo.value)
            assert (
                "Parameters do not match. {id: bad} doesn't match {my: params}" in msg
            )
            assert (
                "request.body doesn't match: {page: two} doesn't match {page: one}"
                in msg
            )

        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            req_kwargs = {
                "stream": True,
                "verify": False,
            }
            rsps.add(
                "GET",
                "http://111.com",
                match=[matchers.request_kwargs_matcher(req_kwargs)],
            )

            with pytest.raises(ConnectionError) as excinfo:
                requests.get("http://111.com", stream=True)

            msg = str(excinfo.value)
            assert (
                "Arguments don't match: "
                "{stream: True, verify: True} doesn't match {stream: True, verify: False}"
            ) in msg
Ejemplo n.º 16
0
def test_create_product(
    mocked_responses,
    mocked_categories_response,
    mocked_product_response,
):
    config = Config()
    config.load('/tmp')
    config.add_account('VA-000', 'Account 0', 'Api 0', 'https://localhost/public/v1')

    stats = SynchronizerStats()
    cloner = ProductCloner(
        config=config,
        source_account='VA-000',
        destination_account='VA-000',
        product_id='PRD-123',
        stats=stats,
    )

    mocked_responses.add(
        method='GET',
        url='https://localhost/public/v1/categories?limit=100&offset=0',
        json=mocked_categories_response,
    )
    mocked_responses.add(
        method='POST',
        url='https://localhost/public/v1/products',
        match=[
            matchers.json_params_matcher({
                'name': 'Clone of PRD-123 2022-04-05-20:15:00',
                'category': {
                    'id': 'CAT-59128',
                },
                'translations': [
                    {'locale': {'id': 'FA'}, 'primary': True},
                ],
            }),
        ],
        json=mocked_product_response,
    )

    os.mkdir(
        os.path.join(
            cloner.fs.root_path,
            'PRD-123',
        ),
    )
    wb = load_workbook('./tests/fixtures/comparation_product.xlsx')
    wb.save(
        os.path.join(
            cloner.fs.root_path,
            'PRD-123',
            'PRD-123.xlsx',
        ),
    )
    cloner.load_wb()
    cloner.create_product()

    wb = load_workbook(
        os.path.join(
            cloner.fs.root_path,
            'PRD-123',
            'PRD-123.xlsx',
        ),
    )

    assert wb['General Information']['B5'].value == 'PRD-276-377-545'
Ejemplo n.º 17
0
    def run():
        with responses.RequestsMock(assert_all_requests_are_fired=True) as rsps:
            # test that both json and urlencoded body are empty in matcher and in request
            rsps.add(
                method=responses.POST,
                url="http://example.com/",
                body="one",
                match=[matchers.json_params_matcher(None)],
            )

            rsps.add(
                method=responses.POST,
                url="http://example.com/",
                body="two",
                match=[matchers.urlencoded_params_matcher(None)],
            )

            resp = requests.request("POST", "http://example.com/")
            assert_response(resp, "one")

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

        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            # test exception raise if matcher body is None but request data is not None
            rsps.add(
                method=responses.POST,
                url="http://example.com/",
                body="one",
                match=[matchers.json_params_matcher(None)],
            )

            with pytest.raises(ConnectionError) as excinfo:
                requests.request(
                    "POST",
                    "http://example.com/",
                    json={"my": "data"},
                    headers={"Content-Type": "application/json"},
                )

            msg = str(excinfo.value)
            assert "request.body doesn't match: {my: data} doesn't match {}" in msg

        with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
            rsps.add(
                method=responses.POST,
                url="http://example.com/",
                body="two",
                match=[matchers.urlencoded_params_matcher(None)],
            )
            with pytest.raises(ConnectionError) as excinfo:
                requests.request(
                    "POST",
                    "http://example.com/",
                    headers={"Content-Type": "x-www-form-urlencoded"},
                    data={"page": "second", "type": "urlencoded"},
                )
            msg = str(excinfo.value)
            assert (
                "request.body doesn't match: {page: second, type: urlencoded} doesn't match {}"
                in msg
            )