Exemplo n.º 1
0
    def mock_kubectl(self, cluster_name: str, command: str, return_value: E.Either[Any, Any]):
        cmd = '{cwd}/{cache_dir_name}/kubectl ' \
              '--kubeconfig {cwd}/{cache_dir_name}/{cluster_name}-kubeconfig.yaml {command}' \
            .format(cache_dir_name=Config.cache_folder_name(), cwd=MockFileSystem.cwd(),
                    cluster_name=cluster_name, command=command)

        PyMock.mock(self.os_system.run, args=[cmd, MatchArg.any()], return_values=[return_value])
Exemplo n.º 2
0
    def mock_with_temp_file(self):
        def _t(x):
            filepath = '/temp/' + x['kwargs']['filename']
            self.file_system.write(filepath, x['kwargs']['contents'])
            return x['kwargs']['runner'](filepath)

        PyMock.mock(self.file_system.with_temp_file, call_fake=_t)
Exemplo n.º 3
0
def test_can_get_mock_calls():
    mock = Mock(name="test_class.prop1")
    PyMock.mock(mock, return_values=[1])
    mock(4)
    mock(5)
    calls = PyMock.calls(mock)
    assert calls[0]['args'][0] == 4
    assert calls[1]['args'][0] == 5
Exemplo n.º 4
0
    def mock_create_kube_config(self, cluster_name: str, return_value: E.Either[Any, Any]):
        cmd = '{script_dir}/create-kube-config.sh {cluster_name} {cwd}/{cache_dir_name} ' \
              '{cwd}/{cache_dir_name}/service_account.json ' \
              '"{cwd}/{cache_dir_name}/{cluster_name}-kubeconfig.yaml" project1' \
            .format(cache_dir_name=Config.cache_folder_name(), cwd=MockFileSystem.cwd(),
                    cluster_name=cluster_name, script_dir=MockFileSystem.script_dir())

        PyMock.mock(self.os_system.run, args=[cmd, MatchArg.any()], return_values=[return_value])
Exemplo n.º 5
0
    def mock_download_install_kubectl(self, version: str, return_value: E.Either[Any, Any]):
        os = 'darwin' if self.os_system.is_macos() else 'linux'
        cmd = 'curl -L https://storage.googleapis.com/kubernetes-release/release' \
              '/{version}/bin/{os}/amd64/kubectl > {cwd}/{cache_dir_name}/kubectl && ' \
              'chmod u+x {cwd}/{cache_dir_name}/kubectl'\
            .format(version=version, cache_dir_name=Config.cache_folder_name(), cwd=MockFileSystem.cwd(), os=os)

        PyMock.mock(self.os_system.run, args=[cmd, MatchArg.any()], return_values=[return_value])
Exemplo n.º 6
0
    def mock_gcloud_download(self, return_value: E.Either[Any, Any]):
        os = 'darwin' if self.os_system.is_macos() else 'linux'
        cmd = 'cd {cwd}/{cache_dir_name} && ' \
              'curl -L https://dl.google.com/dl/cloudsdk/channels/rapid/' \
              'downloads/google-cloud-sdk-284.0.0-{os}-x86_64.tar.gz | tar zx' \
              .format(cache_dir_name=Config.cache_folder_name(), cwd=MockFileSystem.cwd(), os=os)

        PyMock.mock(self.os_system.run, args=[cmd, MatchArg.any()], return_values=[return_value])
Exemplo n.º 7
0
    def mock_clusters_list(self, cluster_names: List[str]):
        for cluster_name in cluster_names:
            self.mock_create_kube_config(cluster_name, return_value=E.success())
            self.mock_kubectl_apply_temp_file(cluster_name, return_value=E.success())

        cmd = '{cwd}/{cache_dir_name}/google-cloud-sdk/bin/gcloud container clusters list --format=\"value(name)\"' \
            .format(cache_dir_name=Config.cache_folder_name(), cwd=MockFileSystem.cwd())

        PyMock.mock(self.os_system.run, args=[cmd, MatchArg.any()], return_values=[E.success('\n'.join(cluster_names))])
Exemplo n.º 8
0
def test_can_match_any_arg():
    mock = Mock(name="test_class.prop1")
    PyMock.mock(mock, return_values=[1])
    mock(1, 4)
    assert_that(mock).was_called(with_args=[1, MatchArg.any()])

    assert_exception(
        lambda: assert_that(mock).was_called(with_args=[2, MatchArg.any()]),
        "Expected to have been called 1 or more times. But call count was: 0")
Exemplo n.º 9
0
 def mock_glob_kubeconfigs(self, cluster_configs: List[str]):
     PyMock.mock(self.file_system.glob,
                 args=[
                     '{cwd}/{cache_dir}/*kubeconfig.yaml'.format(
                         cwd=self.file_system.cwd(),
                         cache_dir=Config.cache_folder_name())
                 ],
                 return_values=[cluster_configs])
     return self
Exemplo n.º 10
0
def test_can_match_custom_matcher():
    mock = Mock(name="test_class.prop1")
    PyMock.mock(mock, return_values=[1])
    mock(4)
    assert_that(mock).was_called(with_args=[MatchArg.match(lambda x: x == 4)])

    assert_exception(
        lambda: assert_that(mock).was_called(
            with_args=[MatchArg.match(lambda x: x == 5)]),
        "Expected to have been called 1 or more times. But call count was: 0")
Exemplo n.º 11
0
def test_can_make_negative_assertion():
    mock = Mock(name="test_class.prop1")
    PyMock.mock(mock, args=[1], return_values=[1])

    assert_that(mock).was_not_called(with_args=[1])

    mock(1)
    assert_exception(
        lambda: assert_that(mock).was_not_called(with_args=[1]),
        "Expected to not have been called 1 or more times. But call count was: 1"
    )
Exemplo n.º 12
0
def test_can_match_dict_arg():
    mock = Mock(name="test_class.prop1")
    PyMock.mock(mock, return_values=[1])
    mock({'a': 1, 'b': {'d': 6}})
    assert_that(mock).was_called(with_args=[{'a': 1, 'b': {'d': 6}}])

    assert_exception(
        lambda: assert_that(mock).was_called(with_args=[{
            'c': 3,
            'd': 4
        }]),
        "Expected to have been called 1 or more times. But call count was: 0")
Exemplo n.º 13
0
def test_can_assert_mock_call_count():
    prop1 = PyMock.new_mock(name="test_class.prop1", return_values=[1])
    prop1()
    prop1()
    assert_that(prop1).call_count(2)

    assert_exception(lambda: assert_that(prop1).call_count(1),
                     "Expect call count 1. Got 2")
Exemplo n.º 14
0
    def _run_dsl(args):
        mock_fs: MockFileSystem = args['file_system']
        project_id = "project1"
        cluster_name = 'prod-us-east1'
        service_account_b64 = b64encode(
            json.dumps({
                'key': 'someKey'
            }).encode('utf-8'))
        service_defaults_path = '{}/service_defaults.yaml'.format(
            fs.dirname(__file__))
        PyMock.mock(mock_fs.get_mock().read,
                    call_fake=lambda path: read(path['args'][0])
                    if path['args'][0] == service_defaults_path else '')

        _, result = run_in_cluster(
            conn=gke_conn(cluster_name, project_id, service_account_b64),
            templates=[from_file(service_defaults_path)])

        yamls = find_write_template_calls(mock_fs)
        assert yamls[0]['kind'] == 'Service'
Exemplo n.º 15
0
def test_can_assert_different_setups():
    mock = Mock(name="test_class.prop1")
    PyMock.mock(mock, args=[1, 1], return_values=[1])
    PyMock.mock(mock, args=[2, 2], return_values=[2])
    mock(1, 1)
    mock(1, 1)
    mock(2, 2)

    assert_that(mock).was_called(with_args=[1, 1], exactly_times=2)

    assert_exception(
        lambda: assert_that(mock).was_called(with_args=[1, 1], exactly_times=1
                                             ),
        "Expected to have been called exactly 1 times. But call count was: 2")

    assert_that(mock).was_called(with_args=[2, 2], exactly_times=1)

    assert_exception(
        lambda: assert_that(mock).was_called(with_args=[2, 2], exactly_times=2
                                             ),
        "Expected to have been called exactly 2 times. But call count was: 1")
Exemplo n.º 16
0
def find_write_template_calls(fs: MockFileSystem,
                              cluster: str = None) -> List[dict]:
    calls = PyMock.calls(fs.file_system.write)
    matches = []
    for call in calls:
        if cluster is not None and call['args'][
                0] == '/var/app-root/output/' + cluster + '/k8s.yaml':
            matches = matches + load_all(call['args'][1])
        if call['args'][0] == '/temp/template.yaml':
            matches = matches + load_all(call['args'][1])
        if call['args'][0] == '/var/app-root/output/k8s.yaml':
            matches = matches + load_all(call['args'][1])
    if len(matches) > 0:
        return matches
    raise Exception('fs.write not used to write template')
Exemplo n.º 17
0
 def mock_kubernetes_release(self, return_value: E.Either[Any, Any]):
     cmd = 'curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt'
     PyMock.mock(self.os_system.run, args=[cmd, MatchArg.any()], return_values=[return_value])
Exemplo n.º 18
0
def test_can_mock_method():
    prop1 = Mock(name="test_class.prop1")
    PyMock.mock(prop1, return_values=[1])
    assert prop1() == 1
Exemplo n.º 19
0
def test_can_mock_any_arg():
    mock = Mock(name="test_class.prop1")
    PyMock.mock(mock, args=[1, MatchArg.any()], return_values=[1])
    result = mock(1, 4)
    assert result == 1
Exemplo n.º 20
0
 def mock_write(self):
     mock = PyMock.new_mock(name='file_system.write', return_values=[''])
     self.file_system.write = mock
Exemplo n.º 21
0
 def mock_path_rel_to_app_dir(self):
     mock = PyMock.new_mock(name='file_system.path_rel_to_app_dir',
                            call_fake=lambda x: MockFileSystem.krogon_dir()
                            + '/' + x['args'][0])
     self.file_system.path_rel_to_app_dir = mock
Exemplo n.º 22
0
    def mock_activate_service_account(self, key_file_path: str, return_values: List[E.Either[Any, Any]]):
        cmd = '{cwd}/{cache_dir_name}/google-cloud-sdk/bin/gcloud auth activate-service-account --key-file ' \
              '{cwd}/{cache_dir_name}/{key_file}' \
            .format(cache_dir_name=Config.cache_folder_name(), cwd=MockFileSystem.cwd(), key_file=key_file_path)

        PyMock.mock(self.os_system.run, args=[cmd, MatchArg.any()], return_values=return_values)
Exemplo n.º 23
0
    def mock_set_project_id(self, project_id: str, return_values: List[E.Either[Any, Any]]):
        cmd = '{cwd}/{cache_dir_name}/google-cloud-sdk/bin/gcloud config set project {project}' \
            .format(cache_dir_name=Config.cache_folder_name(), cwd=MockFileSystem.cwd(), project=project_id)

        PyMock.mock(self.os_system.run, args=[cmd, MatchArg.any()], return_values=return_values)
Exemplo n.º 24
0
 def mock_path_rel_to_cwd(self):
     mock = PyMock.new_mock(
         name='file_system.path_rel_to_cwd',
         call_fake=lambda x: '/rel_to_cwd/' + x['args'][0])
     self.file_system.path_rel_to_cwd = mock
Exemplo n.º 25
0
 def mock_get_env(self, key, return_values):
     PyMock.mock(self.os_system.get_env, args=[key], return_values=return_values)
Exemplo n.º 26
0
def test_can_setup_and_create_mock_in_one_step():
    prop1 = PyMock.new_mock(name="test_class.prop1", return_values=[1])
    assert prop1() == 1