コード例 #1
0
def test_get_yadisk_token_first_time(auth):
    auth._client_socket = Mock()
    code = "7905534"
    auth._handle_user_prompt = Mock(return_value=code)
    token_data = {
        "access_token": "very_secret_access_token",
        "refresh_token": "some_refresh_token",
        "expires_in": 31466940,
    }
    auth._get_yadisk_tokens_from_api = Mock(return_value=token_data)
    y_token_path = Path(TEST_YANDEX_TOKEN_PATH)
    if y_token_path.exists():
        y_token_path.unlink()
    access_token = auth.get_yadisk_token(TEST_YANDEX_TOKEN_PATH)
    keys = ["client_id", "response_type"]
    handle_prompt_args = auth._handle_user_prompt.call_args.args[0]
    for i in range(len(keys)):
        auth._handle_user_prompt.assert_called_once_with(Contains(keys[i]))
    assert "response_type=code" in handle_prompt_args
    get_tokens_args = auth._get_yadisk_tokens_from_api.call_args.args[0]
    #  call args returns tuple with called args
    keys = [
        "client_id",
        "client_secret",
        "code",
        "grant_type",
    ]
    for i in range(len(keys)):
        auth._get_yadisk_tokens_from_api.assert_called_once_with(
            Contains(keys[i]))
    assert get_tokens_args["code"] == code
    assert get_tokens_args["grant_type"] == "authorization_code"
    check_dump_token_data(token_data, TEST_YANDEX_TOKEN_PATH)
    assert isinstance(access_token, str)
    assert access_token == token_data["access_token"]
コード例 #2
0
    def test_get_labels_ids(self, mock_json_query, _):
        id1 = uuid.uuid4()
        id2 = uuid.uuid4()
        mock_json_query.return_value = {
            'objects': [
                {
                    "id": id1
                },
                {
                    "id": id2
                },
            ]
        }

        client = CentraClient(
            CentraSession("fakeaddr", "fakeuser", "fakepassword"))
        key = "a_key"
        value = "a_value"
        label_ids = client.get_labels_ids(key, value)

        assert set(label_ids) == {id1, id2}
        mock_json_query.assert_called_once_with(Contains("visibility/labels"),
                                                method="GET",
                                                params={
                                                    "key": key,
                                                    "value": value
                                                })
コード例 #3
0
    def test_add_label_to_assets(self, mock_json_query, _):
        # arrange
        fake_asset_id = str(uuid.uuid4())
        fake_asset_2_id = str(uuid.uuid4())
        fake_key = "key"
        fake_value = "value"

        mock_json_query.return_value = {
            "id": str(uuid.uuid4()),
            "key": fake_key,
            "value": fake_value,
            "name": f"{fake_key}: {fake_value}"
        }
        client = CentraClient(
            CentraSession("fakeaddr", "fakeuser", "fakepassword"))

        # act
        response = client.add_label_to_assets([fake_asset_id, fake_asset_2_id],
                                              fake_key, fake_value)

        # assert
        mock_json_query.assert_called_once_with(
            Contains(f'assets/labels/{fake_key}/{fake_value}'),
            method="POST",
            data={"vms": [fake_asset_id, fake_asset_2_id]})
コード例 #4
0
def test_gdrive_token_is_refreshed(auth):
    expired_token_data = {
        "access_token": "very_secret_access_token",
        "refresh_token": "some_refresh_token",
        "expire_time": datetime.datetime.now() - datetime.timedelta(0, 100)
    }
    with open(TEST_GOOGLE_TOKEN_PATH, "wb") as f:
        pickle.dump(expired_token_data, f)
    updated_token_data = {
        "refresh_token": expired_token_data["refresh_token"],
        "access_token": "another_secret_access_token",
        "expires_in": 3920
    }
    auth._get_gdrive_tokens_from_api = Mock(return_value=updated_token_data)
    access_token = auth.get_gdrive_token(TEST_GOOGLE_TOKEN_PATH)
    must_have_keys = [
        "client_id", "client_secret", "grant_type", "refresh_token"
    ]
    for i in range(len(must_have_keys)):
        auth._get_gdrive_tokens_from_api.assert_called_once_with(
            Contains(must_have_keys[i]))
    assert access_token != expired_token_data["access_token"]
    check_dump_token_data(updated_token_data, TEST_GOOGLE_TOKEN_PATH)
    assert isinstance(access_token, str)
    assert access_token == updated_token_data["access_token"]
コード例 #5
0
def test_ensure_daily_book(g_bot: GDGAjuBot, telebot: MockTeleBot):
    # given
    chat_id = 1234
    telebot.get_chat.return_value = telegram.Chat(chat_id, type="group")
    state = g_bot.states["daily_book"][chat_id]

    # when
    g_bot.ensure_daily_book()

    # then
    g_bot.updater.job_queue.run_once.assert_called_once_with(ANY, when=60)
    job_callback = g_bot.updater.job_queue.run_once.call_args[0][0]
    assert isinstance(job_callback, Callable)
    assert state["__memory__"]["first_call"] is True
    assert isinstance(state["__memory__"]["schedule_fn"], Callable)

    # given
    message = telegram.Message(0, g_bot.get_me(), datetime.now(),
                               telebot.get_chat.return_value)

    # when
    g_bot.ensure_daily_book(message, as_job=False)

    # then
    assert state["messages_since"] == 1

    # when
    g_bot.ensure_daily_book(message, as_job=True)

    # then
    last_time = state["last_time"].astimezone().timestamp()
    expected = datetime.utcnow().astimezone().timestamp()
    assert last_time == approx(expected, rel=0.1)

    # given
    g_bot.updater.job_queue.run_once.reset_mock()

    # when
    g_bot.ensure_daily_book(message, as_job=True)

    # then
    g_bot.updater.job_queue.run_once.assert_called_once_with(ANY, when=ANY)
    seconds = g_bot.updater.job_queue.run_once.call_args[1]["when"]
    assert seconds // 3600 in range(3, 12 + 1)

    # given
    state["last_time"] -= timedelta(hours=3)
    state["messages_since"] += 300

    # when
    g_bot.ensure_daily_book(message, as_job=True)

    # then
    telebot.send_message.assert_any_call(chat_id,
                                         Contains(" Mensagem automática do "),
                                         parse_mode="Markdown")
コード例 #6
0
    def test_delete_label_by_key_value(self, mock_json_query,
                                       mock_get_label_ids, _):
        first_id = "first_id"
        second_id = "second_id"
        mock_get_label_ids.return_value = [first_id, second_id]
        # This makes the call to json_query return the last part of the uri which is the label ID.
        # That's what the actual delete_label API returns.
        mock_json_query.side_effect = lambda uri, method: uri.split("/")[-1]

        client = CentraClient(
            CentraSession("fakeaddr", "fakeuser", "fakepassword"))
        key = "a_key"
        value = "a_value"
        client.delete_label_by_key_value(key, value)

        mock_json_query.assert_has_calls(calls=[
            call(Contains(first_id), method="DELETE"),
            call(Contains(second_id), method="DELETE")
        ],
                                         any_order=True)
コード例 #7
0
def test_get_gdrive_token_first_time(auth):
    """
    Test GDriveAuth.authenticate method when user have not operated with
    program yet or have deleted token.pickle file.
    """
    auth._client_socket = Mock()
    code = "4/0AY0e-g5asIaMQ1-_XXXXXNcKAel35qh2AjkGGBgAz9_zPXiyzHdw_XXXX"
    auth._handle_user_prompt = Mock(return_value=code)
    token_data = {
        "access_token": "very_secret_access_token",
        "refresh_token": "some_refresh_token",
        "expires_in": 3920,
    }
    auth._get_gdrive_tokens_from_api = Mock(return_value=token_data)
    g_token_path = Path(TEST_GOOGLE_TOKEN_PATH)
    if g_token_path.exists():
        g_token_path.unlink()
    access_token = auth.get_gdrive_token(TEST_GOOGLE_TOKEN_PATH)
    keys = [
        "client_id",
        "redirect_uri",
        "scope",
        "access_type",
    ]
    handle_prompt_args = auth._handle_user_prompt.call_args.args[0]
    for i in range(len(keys)):
        auth._handle_user_prompt.assert_called_once_with(Contains(keys[i]))
    assert "response_type=code" in handle_prompt_args
    get_tokens_args = auth._get_gdrive_tokens_from_api.call_args.args[0]
    #  call args returns tuple with called args
    keys = ["client_id", "client_secret", "code", "grant_type", "redirect_uri"]
    for i in range(len(keys)):
        auth._get_gdrive_tokens_from_api.assert_called_once_with(
            Contains(keys[i]))
    assert get_tokens_args["code"] == code
    assert get_tokens_args["grant_type"] == "authorization_code"
    assert get_tokens_args["redirect_uri"] == "http://127.0.0.1:8000"
    check_dump_token_data(token_data, TEST_GOOGLE_TOKEN_PATH)
    assert access_token == token_data["access_token"]
コード例 #8
0
def test_given_unsupported_resource_type_then_warning_is_logged(mock_logger):
    mock_mapper = Mock(spec=DataMapper)
    mock_mapper.can_map.return_value = False
    mock_config_client_factory = Mock()
    mock_config_client_factory.return_value \
                              .select_resource_config \
                              .return_value = { "NextToken": None,
                                                "Results": [ json.dumps({ "resourceType": "foobar" }) ] }

    reader = AwsConfigInventoryReader(lambda_context=MagicMock(), sts_client=Mock(), mappers=[mock_mapper])
    reader._get_config_client = mock_config_client_factory

    all_inventory = reader.get_resources_from_all_accounts()

    assert len(all_inventory) == 0, "no inventory should be returned since there was nothing to map"
    mock_logger.warning.assert_called_with(String() & Contains("skipping mapping"))
コード例 #9
0
def test_when_cli_context_given_and_exception_then_exception_intercepted_and_logged(
):
    config = Config(click=click, jsonschema=jsonschema)

    logger = MagicMock()
    logger.error = MagicMock()
    cli_context = MagicMock()
    cli_context.meta = MagicMock()
    cli_context.meta[LOGGER_ID] = logger

    exception_validator = RunnableExceptionValidator(
        lambda: config.from_cli_file_path_param(
            config_file_path=DUPLICATE_MONITOR_NAMES_CONFIG_FILE_NAME,
            cli_context=cli_context))
    exception_validator.verify_exception(click.BadParameter,
                                         'Error parsing config file')

    cli_context.meta[LOGGER_ID].error.assert_called_with(
        String() & Contains('Error parsing config file') & EndsWith('\n'))
コード例 #10
0
def test_given_error_from_boto_then_account_is_skipped_but_others_still_processed(mock_logger):
    os.environ["ACCOUNT_LIST"] = '[ { "name": "foo", "id": "210987654321" }, { "name": "bar", "id": "123456789012" } ]'
    mock_mapper = Mock(spec=DataMapper)
    mock_mapper.can_map.return_value = True
    mock_mapper.map.return_value = [ { "test": True }]
    mock_select_resource_config = Mock(side_effect=[ ClientError(error_response={'Error': {'Code': 'ResourceInUseException'}}, operation_name="select_resource_config"),
                                                    { "NextToken": None,
                                                      "Results": [ json.dumps({ "resourceType": "foobar" }) ] }])
    mock_config_client_factory = Mock()
    mock_config_client_factory.return_value \
                              .select_resource_config = mock_select_resource_config

    reader = AwsConfigInventoryReader(lambda_context=MagicMock(), sts_client=Mock(), mappers=[mock_mapper])
    reader._get_config_client = mock_config_client_factory
    
    all_inventory = reader.get_resources_from_all_accounts()

    assert len(all_inventory) == 1, "inventory from the successful call should be returned"
    assert len(mock_select_resource_config.mock_calls) == 2, "boto should have been called twice to page through results"
    mock_logger.error.assert_called_with(String() & Contains("moving onto next account"), ANY, ANY, exc_info=True)
コード例 #11
0
def test_error_while_cloning_skip(display, clone_from):
    error = GitCommandError(command='git clone etc ....', status=218)

    def raise_error_only_for_hierachy_project(*args, url=None, **kwargs):
        if 'Hierarchy' in url:
            raise error

    hierarchy = MOCK_HIERARCHY
    clone_from.side_effect = raise_error_only_for_hierachy_project

    cloner.clone_all(hierarchy)

    # THEN
    # - Error message was displayed
    display.assert_any_call(Contains('Hierarchy'),
                            variant='ERROR',
                            reason=error)
    # - But next repo is still processed
    clone_from.assert_called_with(
        url='[email protected]:FlorianKempenich/kata.git', to_path=mock.ANY)
コード例 #12
0
def test_submit_create(in_process, git_repo_path, init_sha):
    call_conduit.side_effect = (
        # ping
        dict(),
        [dict(userName="******", phid="PHID-USER-1")],
        # diffusion.repository.search
        dict(data=[dict(phid="PHID-REPO-1", fields=dict(vcs="git"))]),
        # differential.creatediff
        dict(dict(phid="PHID-DIFF-1", diffid="1")),
        # differential.setdiffproperty
        dict(),
        # differential.revision.edit
        dict(object=dict(id="123")),
    )
    testfile = git_repo_path / "X"
    testfile.write_text("ą")
    git_out("add", ".")
    msgfile = git_repo_path / "msg"
    msgfile.write_text("Ą r?alice")
    git_out("commit", "--file", "msg")
    testfile = git_repo_path / "untracked"
    testfile.write_text("a")

    mozphab.main(["submit", "--no-arc", "--yes", "--bug", "1", init_sha])

    log = git_out("log", "--format=%s%n%n%b", "-1")
    expected = """
Bug 1 - Ą r?alice

Differential Revision: http://example.test/D123
"""
    assert log.strip() == expected.strip()
    assert mock.call("conduit.ping", {}) in call_conduit.call_args_list
    assert (mock.call("user.query", dict(usernames=["alice"]))
            in call_conduit.call_args_list)
    assert (mock.call(
        "diffusion.repository.search",
        dict(limit=1, constraints=dict(callsigns=["TEST"])),
    ) in call_conduit.call_args_list)
    assert (mock.call(
        "differential.creatediff",
        {
            "sourceControlPath":
            "/",
            "sourceControlSystem":
            "git",
            "lintStatus":
            "none",
            "sourcePath":
            mock.ANY,
            "unitStatus":
            "none",
            "sourceMachine":
            "http://example.test",
            "sourceControlBaseRevision":
            mock.ANY,
            "repositoryPHID":
            "PHID-REPO-1",
            "branch":
            "HEAD",
            "changes": [{
                "commitHash":
                mock.ANY,
                "awayPaths": [],
                "newProperties": {
                    "unix:filemode": "100644"
                },
                "oldPath":
                None,
                "hunks": [{
                    "corpus": "+ą",
                    "addLines": 1,
                    "oldOffset": 0,
                    "newOffset": 1,
                    "newLength": 1,
                    "delLines": 0,
                    "isMissingOldNewline": False,
                    "oldLength": 0,
                    "isMissingNewNewline": False,
                }],
                "oldProperties": {},
                "currentPath":
                "X",
                "fileType":
                1,
                "type":
                1,
                "metadata": {},
            }],
            "creationMethod":
            "moz-phab-git",
        },
    ) in call_conduit.call_args_list)
    assert (mock.call(
        "differential.setdiffproperty",
        {
            "diff_id": "1",
            "name": "local:commits",
            "data": ~Contains('"rev":')
        },
    ) in call_conduit.call_args_list)
コード例 #13
0
    def test_show_commit_stack(self, mock_logger, m_whoami, m_get_revisions):
        class Repository:
            phab_url = "http://phab"
            path = "x"
            api_url = "x"
            dot_path = "x"

        repo = Repository()
        mozphab.conduit.set_repo(repo)

        m_whoami.return_value = dict(phid="PHID-USER-1")
        m_get_revisions.return_value = [{
            "fields": {
                "bugzilla.bug-id": "1",
                "authorPHID": "PHID-USER-1"
            }
        }]

        mozphab.show_commit_stack([])
        self.assertFalse(mock_logger.info.called,
                         "logger.info() shouldn't be called")
        self.assertFalse(mock_logger.warning.called,
                         "logger.warning() shouldn't be called")

        mozphab.show_commit_stack([{
            "name": "aaa000",
            "title-preview": "A"
        }],
                                  validate=False)
        mock_logger.info.assert_called_with("(New) aaa000 A")
        self.assertFalse(mock_logger.warning.called,
                         "logger.warning() shouldn't be called")
        mock_logger.reset_mock()

        mozphab.show_commit_stack(
            [{
                "name": "aaa000",
                "title-preview": "A",
                "rev-id": "12",
                "bug-id": "1"
            }],
            validate=False,
        )
        mock_logger.info.assert_called_with("(D12) aaa000 A")
        self.assertFalse(mock_logger.warning.called,
                         "logger.warning() shouldn't be called")
        mock_logger.reset_mock()

        mozphab.show_commit_stack(
            [
                {
                    "name": "aaa000",
                    "title-preview": "A"
                },
                {
                    "name": "bbb000",
                    "title-preview": "B"
                },
            ],
            validate=False,
        )
        self.assertEqual(2, mock_logger.info.call_count)
        self.assertEqual(
            [mock.call("(New) bbb000 B"),
             mock.call("(New) aaa000 A")],
            mock_logger.info.call_args_list,
        )
        mock_logger.reset_mock()

        mozphab.show_commit_stack(
            [{
                "name": "aaa000",
                "title-preview": "A",
                "bug-id-orig": 2,
                "bug-id": 1,
                "reviewers": {
                    "granted": [],
                    "request": ["one"]
                },
            }],
            validate=True,
        )
        mock_logger.info.assert_called_with("(New) aaa000 A")
        mock_logger.warning.assert_called_with("!! Bug ID changed from 2 to 1")
        mock_logger.reset_mock()

        mozphab.show_commit_stack(
            [{
                "name": "aaa000",
                "title-preview": "A",
                "bug-id": 1,
                "bug-id-orig": None,
                "reviewers": {
                    "granted": [],
                    "request": []
                },
            }],
            validate=True,
        )
        mock_logger.warning.assert_called_with("!! Missing reviewers")
        mock_logger.reset_mock()

        mozphab.show_commit_stack(
            [{
                "name": "aaa000",
                "title-preview": "A",
                "rev-id": "123",
                "bug-id": "1"
            }],
            validate=False,
            show_rev_urls=True,
        )
        mock_logger.warning.assert_called_with("-> http://phab/D123")

        m_get_revisions.reset_mock()
        m_get_revisions.return_value = [
            {
                "id": "1",
                "phid": "PHID-1",
                "fields": {
                    "bugzilla.bug-id": "1",
                    "authorPHID": "PHID-USER-1"
                },
            },
            {
                "id": "2",
                "phid": "PHID-2",
                "fields": {
                    "bugzilla.bug-id": "1",
                    "authorPHID": "PHID-USER-1"
                },
            },
        ]
        # we're changing bug id in the first revision to 2
        mozphab.show_commit_stack(
            [
                {
                    "name": "aaa000",
                    "title-preview": "A",
                    "bug-id-orig": 1,
                    "bug-id": "2",
                    "rev-id": "1",
                    "reviewers": {
                        "granted": [],
                        "request": [""]
                    },
                },
                {
                    "name": "bbb000",
                    "title-preview": "B",
                    "bug-id-orig": "1",
                    "bug-id": "1",
                    "rev-id": "2",
                    "reviewers": {
                        "granted": [],
                        "request": [""]
                    },
                },
            ],
            validate=True,
        )
        assert mock_logger.warning.call_args_list[1] == mock.call(
            "!! Bug ID in Phabricator revision will be changed from 1 to 2")
        assert m_get_revisions.call_count == 3
        mock_logger.reset_mock()

        m_whoami.return_value = dict(phid="PHID-USER-2")
        mozphab.show_commit_stack(
            [{
                "name": "aaa000",
                "title-preview": "A",
                "rev-id": "12",
                "bug-id-orig": "1",
                "bug-id": "1",
                "reviewers": {
                    "granted": ["alice"],
                    "request": []
                },
            }],
            validate=True,
        )
        mock_logger.warning.assert_called_once_with(Contains("Commandeer"))
コード例 #14
0
def test_submit_remove_cr(in_process, hg_repo_path):
    call_conduit.side_effect = (
        # CREATE
        dict(),
        dict(data=[dict(phid="PHID-REPO-1", fields=dict(vcs="hg"))]),
        [dict(userName="******", phid="PHID-USER-1")],
        dict(dict(phid="PHID-DIFF-1", diffid="1")),
        dict(),
        dict(object=dict(id="123")),
        # UPDATE
        # no need to ping (checked)
        # no need to check reviewer
        # no need to search for repository repository data is saved in .hg
        # differential.creatediff
        dict(dict(phid="PHID-DIFF-2", diffid="2")),
        # differential.setdiffproperty
        dict(),
        # differential.revision.edit
        dict(object=dict(id="124")),
    )
    test_a = hg_repo_path / "X"
    test_a.write_text("a\r\nb\n")
    hg_out("add")
    hg_out("commit", "--message", "A r?alice")
    mozphab.main(["submit", "--yes", "--bug", "1", "."])
    call_conduit.reset_mock()
    # removing CR, leaving LF
    test_a.write_text("a\nb\n")
    hg_out("commit", "--message", "B r?alice")
    mozphab.main(["submit", "--yes", "--bug", "1", "."])

    assert (
        mock.call(
            "differential.creatediff",
            {
                "changes": [
                    {
                        "metadata": {},
                        "oldPath": "X",
                        "currentPath": "X",
                        "awayPaths": [],
                        "oldProperties": {},
                        "newProperties": {},
                        "commitHash": mock.ANY,
                        "type": 2,
                        "fileType": 1,
                        "hunks": [
                            {
                                "oldOffset": 1,
                                "oldLength": 2,
                                "newOffset": 1,
                                "newLength": 2,
                                "addLines": 1,
                                "delLines": 1,
                                "isMissingOldNewline": False,
                                "isMissingNewNewline": False,
                                "corpus": "-a\r\n+a\n b\n",
                            }
                        ],
                    }
                ],
                "sourceMachine": "http://example.test",
                "sourceControlSystem": "hg",
                "sourceControlPath": "/",
                "sourceControlBaseRevision": mock.ANY,
                "creationMethod": "moz-phab-hg",
                "lintStatus": "none",
                "unitStatus": "none",
                "repositoryPHID": "PHID-REPO-1",
                "sourcePath": mock.ANY,
                "branch": "default",
            },
        )
        in call_conduit.call_args_list
    )
    assert (
        mock.call(
            "differential.setdiffproperty",
            {
                "diff_id": "2",
                "name": "local:commits",
                "data": Contains('"summary": "Bug 1 - B r?alice"')
                & Contains(
                    '"message": "'
                    "Bug 1 - B r?alice\\n\\n"
                    "Summary:\\n\\n\\n\\n\\n"
                    "Test Plan:\\n\\n"
                    "Reviewers: alice\\n\\n"
                    "Subscribers:\\n\\n"
                    'Bug #: 1"'
                ),
            },
        )
        in call_conduit.call_args_list
    )
コード例 #15
0
def test_submit_create(in_process, hg_repo_path):
    call_conduit.reset_mock()
    call_conduit.side_effect = (
        # ping
        dict(),
        # diffusion.repository.search
        dict(data=[dict(phid="PHID-REPO-1", fields=dict(vcs="hg"))]),
        [dict(userName="******", phid="PHID-USER-1")],
        # differential.creatediff
        dict(dict(phid="PHID-DIFF-1", diffid="1")),
        # differential.setdiffproperty
        dict(),
        # differential.revision.edit
        dict(object=dict(id="123")),
    )
    # test_a = hg_repo_path / "X"
    # test_a.write_text("a")
    # hg_out("add")
    # hg_out("commit", "--message", "Ą r?alice")
    # mozphab.main(["submit", "--yes", "--bug", "1", "."])

    test_a = hg_repo_path / "A to rename"
    test_a.write_text("rename me\nsecond line")
    test_b = hg_repo_path / "B to remove"
    test_b.write_text("remove me")
    test_c = hg_repo_path / "C to modify"
    test_c.write_text("modify me")
    hg_out("add")
    hg_out("commit", "-m", "first")
    subdir = hg_repo_path / "subdir"
    subdir.mkdir()
    test_d = hg_repo_path / "subdir" / "D add"
    test_d.write_text("added")
    test_a.rename(hg_repo_path / "A renamed")
    test_b.unlink()
    test_c.write_text("modified")
    hg_out("addremove")
    msgfile = hg_repo_path / "msg"
    msgfile.write_text("Ą r?alice")
    hg_out("commit", "-l", "msg")
    mozphab.main(["submit", "--yes", "--bug", "1", "."])

    log = hg_out("log", "--template", r"{desc}\n", "--rev", ".")
    expected = """
Bug 1 - Ą r?alice

Differential Revision: http://example.test/D123
"""
    assert log.strip() == expected.strip()
    assert mock.call("conduit.ping", {}) in call_conduit.call_args_list
    assert (
        mock.call("user.query", dict(usernames=["alice"]))
        in call_conduit.call_args_list
    )
    assert (
        mock.call(
            "diffusion.repository.search",
            dict(limit=1, constraints=dict(callsigns=["TEST"])),
        )
        in call_conduit.call_args_list
    )
    assert (
        mock.call(
            "differential.setdiffproperty",
            {"diff_id": "1", "name": "local:commits", "data": Contains('"rev": "')},
        )
        in call_conduit.call_args_list
    )
    assert (
        mock.call(
            "differential.creatediff",
            {
                "sourceControlPath": "/",
                "sourceControlSystem": "hg",
                "lintStatus": "none",
                "sourcePath": mock.ANY,
                "unitStatus": "none",
                "sourceMachine": "http://example.test",
                "sourceControlBaseRevision": mock.ANY,
                "repositoryPHID": "PHID-REPO-1",
                "branch": "default",
                "changes": [
                    {
                        "currentPath": "A renamed",
                        "type": 6,  # MOVE_HERE
                        "hunks": [
                            {
                                "oldOffset": 1,
                                "oldLength": 2,
                                "newOffset": 1,
                                "newLength": 2,
                                "addLines": 0,
                                "delLines": 0,
                                "isMissingOldNewline": False,
                                "isMissingNewNewline": False,
                                "corpus": " rename me\n second line",
                            }
                        ],
                        "oldProperties": {},
                        "oldPath": "A to rename",
                        "commitHash": mock.ANY,
                        "awayPaths": [],
                        "metadata": {},
                        "newProperties": {},
                        "fileType": 1,
                    },
                    {
                        "currentPath": "A to rename",
                        "type": 4,  # MOVE_AWAY
                        "hunks": [],
                        "oldProperties": {},
                        "oldPath": None,
                        "commitHash": mock.ANY,
                        "awayPaths": ["A renamed"],
                        "metadata": {},
                        "newProperties": {},
                        "fileType": 1,
                    },
                    {
                        "currentPath": "B to remove",
                        "type": 3,  # DELETE
                        "hunks": [
                            {
                                "oldOffset": 1,
                                "oldLength": 1,
                                "newOffset": 0,
                                "newLength": 0,
                                "addLines": 0,
                                "delLines": 1,
                                "isMissingOldNewline": False,
                                "isMissingNewNewline": False,
                                "corpus": "-remove me",
                            }
                        ],
                        "awayPaths": [],
                        "fileType": 1,
                        "oldPath": "B to remove",
                        "newProperties": {},
                        "commitHash": mock.ANY,
                        "metadata": {},
                        "oldProperties": {"unix:filemode": "100644"},
                    },
                    {
                        "currentPath": "C to modify",
                        "type": 2,  # CHANGE
                        "hunks": [
                            {
                                "oldOffset": 1,
                                "oldLength": 1,
                                "newOffset": 1,
                                "newLength": 1,
                                "addLines": 1,
                                "delLines": 1,
                                "isMissingOldNewline": True,
                                "isMissingNewNewline": True,
                                "corpus": (
                                    "-modify me\n\\ No newline at end of file\n"
                                    "+modified\n\\ No newline at end of file\n"
                                ),
                            }
                        ],
                        "commitHash": mock.ANY,
                        "metadata": {},
                        "fileType": 1,
                        "oldPath": "C to modify",
                        "newProperties": {},
                        "awayPaths": [],
                        "oldProperties": {},
                    },
                    {
                        "currentPath": "subdir/D add",
                        "type": 1,  # ADD
                        "hunks": [
                            {
                                "corpus": "+added",
                                "addLines": 1,
                                "oldOffset": 0,
                                "newOffset": 1,
                                "newLength": 1,
                                "delLines": 0,
                                "isMissingOldNewline": False,
                                "oldLength": 0,
                                "isMissingNewNewline": False,
                            }
                        ],
                        "commitHash": mock.ANY,
                        "awayPaths": [],
                        "newProperties": {"unix:filemode": "100644"},
                        "oldPath": None,
                        "oldProperties": {},
                        "fileType": 1,
                        "metadata": {},
                    },
                ],
                "creationMethod": "moz-phab-hg",
            },
        )
        in call_conduit.call_args_list
    )
コード例 #16
0
    def test_show_commit_stack(self, mock_logger, m_whoami, m_get_diffs,
                               m_get_revisions):
        class Repository:
            phab_url = "http://phab"
            path = "x"
            api_url = "x"
            dot_path = "x"

        def _commit(
            name="aaa000",
            node="aaa000aaa000",
            title="A",
            rev=None,
            bug="1",
            bug_orig="1",
            granted=None,
            request=None,
            wip=False,
        ):
            granted = granted or []
            request = request or []
            return {
                "name": name,
                "node": node,
                "submit": True,
                "title-preview": title,
                "rev-id": rev,
                "bug-id-orig": bug_orig,
                "bug-id": bug,
                "reviewers": {
                    "granted": granted,
                    "request": request
                },
                "has-reviewers": len(granted + request) > 0,
                "wip": wip,
            }

        repo = Repository()
        submit.conduit.set_repo(repo)

        m_whoami.return_value = dict(phid="PHID-USER-1")
        m_get_revisions.return_value = [search_rev()]
        m_get_diffs.return_value = {"PHID-DIFF-1": search_diff()}

        submit.show_commit_stack([])
        self.assertFalse(mock_logger.info.called,
                         "logger.info() shouldn't be called")
        self.assertFalse(mock_logger.warning.called,
                         "logger.warning() shouldn't be called")

        submit.show_commit_stack([{
            "name": "aaa000",
            "title-preview": "A"
        }],
                                 validate=False)
        mock_logger.info.assert_called_with("%s %s %s", "(New)", "aaa000", "A")
        self.assertFalse(mock_logger.warning.called,
                         "logger.warning() shouldn't be called")
        mock_logger.reset_mock()

        submit.show_commit_stack([_commit(rev="12")], validate=False)
        mock_logger.info.assert_called_with("%s %s %s", "(D12)", "aaa000", "A")
        self.assertFalse(mock_logger.warning.called,
                         "logger.warning() shouldn't be called")
        mock_logger.reset_mock()

        submit.show_commit_stack(
            [_commit(), _commit(name="bbb000", title="B")],
            validate=False,
        )
        self.assertEqual(2, mock_logger.info.call_count)
        self.assertEqual(
            [
                mock.call("%s %s %s", "(New)", "bbb000", "B"),
                mock.call("%s %s %s", "(New)", "aaa000", "A"),
            ],
            mock_logger.info.call_args_list,
        )
        mock_logger.reset_mock()

        submit.show_commit_stack(
            [_commit(bug_orig="2", bug="1", granted=["alice"])], validate=True)
        mock_logger.info.assert_called_with("%s %s %s", "(New)", "aaa000", "A")
        mock_logger.warning.assert_called_with(
            "!! Bug ID changed from %s to %s", "2", "1")
        mock_logger.reset_mock()
        submit.show_commit_stack([_commit()], validate=True)
        mock_logger.warning.assert_called_with(Contains("Missing reviewers"))
        mock_logger.reset_mock()

        submit.show_commit_stack(
            [_commit(rev="123")],
            validate=False,
            show_rev_urls=True,
        )
        mock_logger.warning.assert_called_with("-> %s/D%s", "http://phab",
                                               "123")

        # Do not update not changed commits
        m_get_revisions.reset_mock()
        m_get_revisions.return_value = [
            search_rev(),
            search_rev(rev="2", phid="PHID-REV-2", diff="PHID-DIFF-2"),
        ]
        # we're changing bug id in the first revision to 2
        submit.show_commit_stack(
            [
                _commit(rev="1", bug="2", bug_orig="1", granted=["alice"]),
                _commit(
                    name="bbb000",
                    node="bbb000bbb000",
                    title="B",
                    rev="2",
                    granted=["alice"],
                ),
            ],
            validate=True,
        )
        assert mock_logger.warning.call_args_list[1] == mock.call(
            "!! Bug ID in Phabricator revision will change from %s to %s", "1",
            "2")
        assert m_get_revisions.call_count == 3
        mock_logger.reset_mock()

        m_whoami.return_value = dict(phid="PHID-USER-2")
        submit.show_commit_stack(
            [_commit(rev="1", granted=["alice"])],
            validate=True,
        )
        mock_logger.warning.assert_called_once_with(Contains("Commandeer"))

        # Information about not updating the commit if not changed
        mock_logger.reset_mock()
        m_whoami.return_value = dict(phid="PHID-USER-1")
        m_get_revisions.return_value = [search_rev(reviewers=["PHID-USER-2"])]
        m_get_diffs.return_value = {"PHID-DIFF-1": search_diff()}

        submit.show_commit_stack([_commit(rev="1", granted=["alice"])],
                                 validate=True)
        assert mock_logger.info.call_args_list[1] == mock.call(
            Contains("revision has not changed"))

        # Removing the WIP state from the revision without changing the commit's SHA1
        mock_logger.reset_mock()
        m_get_revisions.return_value = [search_rev(status="changes-planned")]
        submit.show_commit_stack([_commit(rev="1", granted=["alice"])],
                                 validate=True)
        mock_logger.warning.assert_called_once_with(
            Contains('"Changes Planned" status will change'))

        # Adding the WIP state to the revision without changing the commit's SHA1
        mock_logger.reset_mock()
        m_get_revisions.return_value = [search_rev()]
        submit.show_commit_stack(
            [_commit(rev="1", granted=["alice"], wip=True)], validate=True)
        mock_logger.warning.assert_called_with(
            Contains('status will change to "Changes Planned"'))