Example #1
0
    def test_load(self, _open, listdir):
        files = ["a.conf", "b.conf", "c.other"]

        fp0 = Mock()
        fp0.buffer = StringIO(self.FILE % tuple(range(0, 4)))
        fp0.readline.side_effect = fp0.buffer.readline
        fp0.__enter__ = Mock(return_value=fp0)
        fp0.__exit__ = Mock()

        fp1 = Mock()
        fp1.buffer = StringIO(self.FILE % tuple(range(4, 8)))
        fp1.readline.side_effect = fp1.buffer.readline
        fp1.__enter__ = Mock(return_value=fp1)
        fp1.__exit__ = Mock()

        _open.side_effect = [fp0, fp1]

        listdir.return_value = files

        # test
        table = AliasTable()
        table.load()

        # validation
        for fp in (fp0, fp1):
            fp.__enter__.assert_called_once_with()
            fp.__exit__.assert_called_once_with(None, None, None)
        self.assertEqual(_open.call_args_list, [call("/etc/httpd/conf.d/{n}".format(n=n)) for n in files[:-1]])
        self.assertEqual(table.table, {"0": "1", "2": "3", "4": "5", "6": "7"})
Example #2
0
    def setUp(self):
        AddPatch(self, patch.dict("os.environ", {"NACL_SDK_ROOT": "/sdk/root"}))
        AddPatch(self, patch("naclports.util.GetPlatform", Mock(return_value="linux")))
        AddPatch(self, patch("naclports.util.GetInstallRoot", Mock(return_value="/package/install/path")))
        AddPatch(self, patch("naclports.util.GetSDKRoot", Mock(return_value="/sdk/root")))

        mock_lock = Mock()
        mock_lock.__enter__ = lambda s: s
        mock_lock.__exit__ = Mock(return_value=False)
        AddPatch(self, patch("naclports.util.InstallLock", Mock(return_value=mock_lock)))

        mock_lock = Mock()
        mock_lock.__enter__ = lambda s: s
        mock_lock.__exit__ = Mock(return_value=False)
        AddPatch(self, patch("naclports.util.BuildLock", Mock(return_value=mock_lock)))
    def test_get_pod_config_response_code(self, m_json_load, m_secure, m_session):
        """Test _get_api_path with incorrect status_code
        """
        # Set up class member
        self.plugin.pod_name = "pod-1"
        self.plugin.namespace = "a"
        pod1 = '{"metadata": {"namespace": "a", "name": "pod-1"}}'

        # Set up mock objects
        m_secure.return_value = True
        self.plugin.auth_token = "TOKEN"

        get_obj = Mock()
        get_obj.status_code = 404

        m_session_obj = Mock()
        m_session_obj.headers = Mock()
        m_session_obj.get.return_value = get_obj

        m_session.return_value = m_session_obj
        m_session_obj.__enter__ = Mock(return_value=m_session_obj)
        m_session_obj.__exit__ = Mock(return_value=False)

        # Call method under test
        assert_raises(SystemExit, self.plugin._get_pod_config)
    def test_get_pod_config(self, m_json_load, m_secure, m_session):
        """Test _get_pod_config Success

        Test for correct calls in _get_api_path.
        """
        # Set up class member
        self.plugin.pod_name = "pod-1"
        self.plugin.namespace = "a"
        pod1 = '{"metadata": {"namespace": "a", "name": "pod-1"}}'

        # Set up mock objects
        m_secure.return_value = True
        self.plugin.auth_token = "TOKEN"

        get_obj = Mock()
        get_obj.status_code = 200
        get_obj.text = pod1

        m_session_obj = Mock()
        m_session_obj.headers = Mock()
        m_session_obj.get.return_value = get_obj

        m_session.return_value = m_session_obj
        m_session_obj.__enter__ = Mock(return_value=m_session_obj)
        m_session_obj.__exit__ = Mock(return_value=False)

        # Call method under test
        api_root = "http://kubernetesapi:8080/api/v1/"
        self.plugin.api_root = api_root
        self.plugin._get_pod_config()

        # Assert correct data in calls.
        m_session_obj.headers.update.assert_called_once_with({"Authorization": "Bearer " + "TOKEN"})
        m_session_obj.get.assert_called_once_with(api_root + "namespaces/a/pods/pod-1", verify=False)
        m_json_load.assert_called_once_with(pod1)
Example #5
0
def test_catter():
    fs = Filesystem(DB(":memory:"))
    fs.root().add_file("zeroes", [test_asset_ids])

    asset = Mock()
    asset.__enter__ = Mock(return_value=asset)
    asset.__exit__ = Mock(return_value=False)
    asset.status = Mock(return_value=proto.AssetStatus(size=1024 * 1024, status=proto.SUCCESS))
    asset.__iter__ = Mock(return_value=("\x00" * (128 * 1024) for _ in range(8)))

    bithorde = Mock()
    bithorde.open = Mock(return_value=asset)
    cat = Cat(fs, bithorde)

    sha = sha1()
    for chunk in cat(P("zeroes")):
        sha.update(chunk)
    assert_equals(sha.hexdigest(), "3b71f43ff30f4b15b5cd85dd9e95ebc7e84eb5a3")

    with assert_raises(FNotFound):
        for chunk in cat(P("NON-EXISTING")):
            pass

    asset.status = Mock(return_value=proto.AssetStatus(status=proto.NOTFOUND))
    with assert_raises(NotFoundError):
        for chunk in cat(P("zeroes")):
            pass
Example #6
0
def test_DBExporter():
    path = u"apa/movie"
    xt = u"tree:tiger:ASDASDSADASDASDSADASDASDSADASDASDSADASD"
    db = DB(":memory:")
    db.update(Object(u"dir:apa", {u"directory": ValueSet(u"dir:/apa")}))
    db.update(Object("some_file", {u"directory": ValueSet(u"dir:apa/movie"), u"xt": ValueSet(xt)}))

    asset = Mock()
    asset.__enter__ = Mock(return_value=asset)
    asset.__exit__ = Mock(return_value=False)
    asset.status = Mock(return_value=proto.AssetStatus(status=proto.SUCCESS))

    bithorde = Mock()
    bithorde.open = Mock(return_value=asset)
    bithorde.pool = Mock(return_value=itertools)

    writer = Mock()

    magnet = u"magnet:?xt=urn:" + xt
    exp = links.DBExporter(db, bithorde, writer)
    exp.export(False)
    writer.assert_called_once_with(path, magnet)
    writer.reset_mock()

    exp.export(False)
    writer.assert_not_called()

    exp.export(True)
    writer.assert_called_once_with(path, magnet)
    def test_build_manifest(self, mock_chdir, mock_digest, mock_open, mock_getsize, mock_listdir):
        parsed_options = {"output_dir": "/tmp/output"}

        options = Values(defaults=parsed_options)

        files = ["file_1%s" % builder.ARCHIVE_SUFFIX, "file_2%s" % builder.ARCHIVE_SUFFIX, "file_3"]  # not a module

        digests = ["hash_1", "hash_2"]
        mock_digest.side_effect = digests
        mock_listdir.return_value = files
        mock_getsize.side_effect = [10, 20]

        manifest = []
        mock_fp = Mock()
        mock_fp.write = manifest.append
        mock_fp.__enter__ = Mock(return_value=mock_fp)
        mock_fp.__exit__ = Mock()
        mock_open.return_value = mock_fp

        # test

        builder.build_manifest(options)

        # validation

        _manifest = ["file_1.tar.gz", ",hash_1", ",10\n", "file_2.tar.gz", ",hash_2", ",20\n"]

        mock_open.assert_called_with("PULP_MANIFEST", "w+")
        mock_chdir.assert_called_with(os.getcwd())
        self.assertEqual(manifest, _manifest)
Example #8
0
def test_run_interactive(capfd):
    """Ensure the calls to run a command on a list of hosts interactively."""

    runner = Bladerunner({"threads": 14})
    fake_result = Mock()
    fake_result.result = Mock(return_value="fake results")

    mock_con = Mock()
    runner.interactive_hosts = {"fake host": mock_con}

    fake_thread = Mock()
    fake_thread.__enter__ = fake_context
    fake_thread.__exit__ = fake_context
    fake_thread.submit = Mock(return_value=fake_result)

    threadpool_mock = patch.object(
        base,
        "ThreadPoolExecutor",
        return_value=fake_thread,
    )

    with patch.object(runner, "setup_interactive") as mock_setup:
        with threadpool_mock as mock_threadpool:
            runner.run_interactive("fake cmd", "fake host")

    mock_setup.assert_called_once_with("fake host")
    mock_threadpool.assert_called_once_with(max_workers=14)

    stdout, stderr = capfd.readouterr()
    assert stdout == "fake host: fake results\n"
    assert stderr == ""
Example #9
0
    def test_get_api_pod_parse_error(self, m_json_load, m_session):
        # Set up driver.
        self.driver.pod_name = "pod-1"
        self.driver.namespace = "a"
        pod1 = '{"metadata": {"namespace": "a", "name": "pod-1"}}'

        api_root = "http://kubernetesapi:8080/api/v1/"
        self.driver.api_root = api_root

        # Set up mock objects
        self.driver.auth_token = "TOKEN"

        m_json_load.side_effect = TypeError

        get_obj = Mock()
        get_obj.status_code = 200
        get_obj.text = pod1

        m_session_obj = Mock()
        m_session_obj.headers = Mock()
        m_session_obj.get.return_value = get_obj

        m_session.return_value = m_session_obj
        m_session_obj.__enter__ = Mock(return_value=m_session_obj)
        m_session_obj.__exit__ = Mock(return_value=False)

        # Call method under test
        assert_raises(ApplyProfileError, self.driver._get_api_pod)
Example #10
0
    def test_get_api_pod_with_client_certs(self, m_json_load, m_session):
        # Set up driver.
        self.driver.pod_name = "pod-1"
        self.driver.namespace = "a"
        pod1 = '{"metadata": {"namespace": "a", "name": "pod-1"}}'

        api_root = "http://kubernetesapi:8080/api/v1/"
        self.driver.api_root = api_root
        self.driver.client_certificate = "cert.pem"
        self.driver.client_key = "key.pem"
        self.driver.certificate_authority = "ca.pem"

        get_obj = Mock()
        get_obj.status_code = 200
        get_obj.text = pod1

        m_session_obj = Mock()
        m_session_obj.headers = Mock()
        m_session_obj.get.return_value = get_obj

        m_session.return_value = m_session_obj
        m_session_obj.__enter__ = Mock(return_value=m_session_obj)
        m_session_obj.__exit__ = Mock(return_value=False)

        # Call method under test
        self.driver._get_api_pod()

        # Assert correct data in calls.
        m_session_obj.get.assert_called_once_with(
            api_root + "namespaces/a/pods/pod-1", verify="ca.pem", cert=("cert.pem", "key.pem")
        )
        m_json_load.assert_called_once_with(pod1)
Example #11
0
    def test_get_api_pod(self, m_json_load, m_session):
        # Set up driver.
        self.driver.pod_name = "pod-1"
        self.driver.namespace = "a"
        pod1 = '{"metadata": {"namespace": "a", "name": "pod-1"}}'

        api_root = "http://kubernetesapi:8080/api/v1/"
        self.driver.api_root = api_root

        # Set up mock objects
        self.driver.auth_token = "TOKEN"

        get_obj = Mock()
        get_obj.status_code = 200
        get_obj.text = pod1

        m_session_obj = Mock()
        m_session_obj.headers = Mock()
        m_session_obj.get.return_value = get_obj

        m_session.return_value = m_session_obj
        m_session_obj.__enter__ = Mock(return_value=m_session_obj)
        m_session_obj.__exit__ = Mock(return_value=False)

        # Call method under test
        self.driver._get_api_pod()

        # Assert correct data in calls.
        m_session_obj.headers.update.assert_called_once_with({"Authorization": "Bearer " + "TOKEN"})
        m_session_obj.get.assert_called_once_with(api_root + "namespaces/a/pods/pod-1", verify=False)
        m_json_load.assert_called_once_with(pod1)
Example #12
0
def test_run_interactive_returns():
    """Confirm the dict return when print_results is False."""

    runner = Bladerunner({"threads": 17})
    fake_result = Mock()
    fake_result.result = Mock(return_value="some result")

    mock_con = Mock()
    runner.interactive_hosts = {"host": mock_con}

    fake_thread = Mock()
    fake_thread.__enter__ = fake_context
    fake_thread.__exit__ = fake_context
    fake_thread.submit = Mock(return_value=fake_result)

    threadpool_mock = patch.object(
        base,
        "ThreadPoolExecutor",
        return_value=fake_thread,
    )

    with patch.object(runner, "setup_interactive") as mock_setup:
        with threadpool_mock as mock_threadpool:
            results = runner.run_interactive("ok", "host", print_results=False)

    mock_setup.assert_called_once_with("host")
    mock_threadpool.assert_called_once_with(max_workers=17)

    assert results == {"host": "some result"}
Example #13
0
 def create_file_context_manager(*args, **kwargs):
     path = args[0]
     file_mock = Mock()
     file_mock.read = Mock(return_value=file_map[path])
     cm = Mock()
     cm.__enter__ = Mock(return_value=file_mock)
     cm.__exit__ = Mock()
     return cm
Example #14
0
 def test_write_data(self, m_open):
     mock_fp = Mock()
     mock_fp.__enter__ = lambda x: mock_fp
     mock_fp.__exit__ = lambda w, x, y, z: None
     m_open.return_value = mock_fp
     c.write_to_file("data", "outfile")
     m_open.assert_called_once_with("outfile", "w")
     mock_fp.write.assert_called_once_with("data")
Example #15
0
def global_reader_bis(path=""):
    reader = Mock(spec=RasterReader)
    reader.shape = (361, 720)
    reader.affine = Affine(-180.0, 0.5, 0.0, 90.0, 0.0, -0.5)

    context = Mock()
    context.__enter__ = Mock(return_value=reader)
    context.__exit__ = Mock(return_value=False)
    return context
Example #16
0
    def testContextManagerMocking(self):
        mock = Mock()
        mock.__enter__ = Mock()
        mock.__exit__ = Mock()
        mock.__exit__.return_value = False

        with mock as m:
            self.assertEqual(m, mock.__enter__.return_value)
        mock.__enter__.assert_called_with()
        mock.__exit__.assert_called_with(None, None, None)
Example #17
0
 def test_update_unlocked(self):
     """ til; How to mock a context generator """
     job = {"app_id": 6380}
     self.master.apphandlerlocks = {6380: None}
     nblc = Mock()
     nblc.__enter__ = Mock(return_value=False)
     nblc.__exit__ = Mock()
     nblc_mock = Mock(return_value=nblc)
     with patch("master.NBLockContext", nblc_mock, create=True):
         self.assertFalse(self.master.api_update(job, Mock()))
 def test_execute_playbook_fail(self):
     self.task_config.update(dict(playbook=[]))
     task = self.klass(self.ctx, self.task_config)
     task.setup()
     with patch.object(ansible.pexpect, "run") as m_run:
         with patch("teuthology.task.ansible.open") as m_open:
             fake_failure_log = Mock()
             fake_failure_log.__enter__ = Mock()
             fake_failure_log.__exit__ = Mock()
             m_open.return_value = fake_failure_log
             m_run.return_value = ("", 1)
             with raises(CommandFailedError):
                 task.execute_playbook()
    def test_should_report_failed_tests_to_ci_server(self, proxy):
        project = Project("basedir")
        mock_proxy = Mock()
        proxy.return_value = mock_proxy
        mock_proxy.and_test_name.return_value = mock_proxy
        mock_proxy.__enter__ = Mock(return_value=mock_proxy)
        mock_proxy.__exit__ = Mock(return_value=False)
        result = Mock()
        result.test_names = ["test1", "test2", "test3"]
        result.failed_test_names_and_reasons = {"test2": "Something went very wrong"}

        report_to_ci_server(project, result)

        mock_proxy.fails.assert_called_with("Something went very wrong")
    def testErrorResultAndActiveModelInScrubInferernceResults(self, repoMock, *_args):
        """Calling _scrubInferenceResultsAndInitMetricData with a failed inference
    result and ACTIVE model should set the model to ERROR state and raise
    RejectedInferenceResultBatch.
    """

        class MetricRowSpec(object):
            uid = None
            status = None
            parameters = None
            server = None

        metricRowMock = Mock(spec_set=MetricRowSpec, status=MetricStatus.ACTIVE, parameters=None, uid=0)

        class MetricDataRowSpec(object):
            uid = None
            rowid = None
            metric_value = None
            timestamp = None
            raw_anomaly_score = None

        metricRowDataMock = Mock(
            spec_set=MetricDataRowSpec, uid=0, rowid=0, timestamp=None, metric_value=0, raw_anomaly_score=None
        )

        engineMock = Mock(spec_set=sqlalchemy.engine.Engine)

        cmMock = Mock()
        engineMock.connect.return_value = cmMock
        cmMock.__enter__ = cmMock
        cmMock.__exit__ = cmMock

        connMock = Mock(spec_set=sqlalchemy.engine.Connection)
        cmMock.return_value = connMock

        runner = anomaly_service.AnomalyService()

        with self.assertRaises(anomaly_service.RejectedInferenceResultBatch) as cm:
            runner._scrubInferenceResultsAndInitMetricData(
                engine=engineMock,
                inferenceResults=[
                    ModelInferenceResult(rowID=0, status=MetricStatus.ERROR, errorMessage="bad inference")
                ],
                metricDataRows=[metricRowDataMock],
                metricObj=metricRowMock,
            )

        repoMock.setMetricStatus.assert_called_with(connMock, 0, MetricStatus.ERROR, "bad inference")
        self.assertIn("promoted to ERROR state", cm.exception.args[0])
Example #21
0
 def _create_zmq_execution_mocks(self, patch, side=None, valid=True, response=ZMQ_ERROR_RESPONSE):
     socket = Mock()
     context = Mock()
     context.__enter__ = Mock()
     context.__enter__.return_value = socket
     context.__exit__ = Mock()
     context.__exit__.return_value = valid
     patch.return_value = context
     if valid:
         socket.recv.return_value = ZMQ_RESPONSE
     else:
         socket.recv.return_value = response
     if side:
         socket.recv.side_effect = side
     return socket, context
    def test_should_report_passed_tests_to_ci_server(self, teamcity, proxy):
        teamcity.return_value = False
        project = Project("basedir")
        mock_proxy = Mock()
        proxy.return_value = mock_proxy
        mock_proxy.and_test_name.return_value = mock_proxy
        mock_proxy.__enter__ = Mock(return_value=mock_proxy)
        mock_proxy.__exit__ = Mock(return_value=False)
        result = Mock()
        result.test_names = ["test1", "test2", "test3"]
        result.failed_test_names_and_reasons = {}

        report_to_ci_server(project, result)

        mock_proxy.fails.assert_not_called()
Example #23
0
    def test_load(self, mock_open):
        mock_fp = Mock()
        mock_fp.read = Mock(return_value=RSA_KEY)
        mock_fp.__enter__ = Mock(return_value=mock_fp)
        mock_fp.__exit__ = Mock()
        mock_open.return_value = mock_fp

        # test

        authenticator = Authenticator()
        authenticator.load()

        # validation

        self.assertTrue(mock_fp.__exit__.called)
        self.assertTrue(isinstance(authenticator.rsa_key, RSA.RSA))
Example #24
0
    def test_get_pod_config_error(self, m_json_load, m_session):
        """Test _get_api_path with API Access Error
        """
        # Set up mock objects
        self.driver.auth_token = "TOKEN"

        m_session_obj = Mock()
        m_session_obj.headers = Mock()
        m_session_obj.get.side_effect = BaseException

        m_session.return_value = m_session_obj
        m_session_obj.__enter__ = Mock(return_value=m_session_obj)
        m_session_obj.__exit__ = Mock(return_value=False)

        # Call method under test
        assert_raises(ApplyProfileError, self.driver._get_api_pod)
Example #25
0
    def test_storage_dir(self, storage):
        url = "url-123"
        repo = Mock(id="id-123")
        config = {importer_constants.KEY_FEED: url}
        st = Mock()
        st.__enter__ = Mock(return_value=st)
        st.__exit__ = Mock()
        storage.return_value = st

        # test
        step = Main(repo=repo, config=config)
        path = step.storage_dir
        storage.assert_called_once_with(constants.STORAGE_PROVIDER, step.remote_id)
        st.__enter__.assert_called_once_with()
        st.__exit__.assert_called_once_with(None, None, None)
        self.assertEqual(path, st.content_dir)
Example #26
0
 def setUp(self):
     self.pcmd = taskqueue.daemonlib.parse_cmdline
     opts = Mock()
     opts.foreground = True
     taskqueue.daemonlib.parse_cmdline = Mock(return_value=opts)
     self.config = ConfigParser()
     taskqueue.daemonlib.pika = Mock()
     fake_ctx = Mock()
     fake_ctx.__exit__ = Mock()
     fake_ctx.__enter__ = Mock()
     taskqueue.daemonlib.daemon.DaemonContext = Mock(return_value=fake_ctx)
     taskqueue.daemonlib.logging.config = Mock()
     config = Mock()
     config.items = Mock(return_value=[])
     taskqueue.daemonlib.ConfigParser = Mock(return_value=config)
     self.daemon = taskqueue.daemonlib.Daemon(self.config)
Example #27
0
    def test_default_paths(self, mock_config, mock_validate, mock_open, *unused):
        mock_config.return_value = INIConfig()

        mock_fp = Mock()
        mock_fp.__enter__ = Mock(return_value=mock_fp)
        mock_fp.__exit__ = Mock()
        mock_open.return_value = mock_fp

        # test
        read_config(validate=False)

        # validation
        paths = ["/etc/pulp/consumer/consumer.conf", os.path.expanduser("~/.pulp/consumer.conf")]
        mock_open.assert_any(paths[0])
        mock_open.assert_any(paths[1])
        self.assertFalse(mock_validate.called)
Example #28
0
    def test_read(self, _open):
        path = "/tmp/xx"
        fp = Mock()
        fp.__enter__ = Mock(return_value=fp)
        fp.__exit__ = Mock()
        _open.return_value = fp

        # test
        content = cudl.read(path)

        # validation
        _open.assert_called_once_with(path)
        fp.__enter__.assert_called_once_with()
        fp.__exit__.assert_called_once_with(None, None, None)
        fp.read.assert_called_once_with()
        self.assertEqual(content, fp.read.return_value)
    def test_get_pod_config_error(self, m_json_load, m_secure, m_session):
        """Test _get_api_path with API Access Error
        """
        # Set up mock objects
        m_secure.return_value = True
        self.plugin.auth_token = "TOKEN"

        m_session_obj = Mock()
        m_session_obj.headers = Mock()
        m_session_obj.get.side_effect = BaseException

        m_session.return_value = m_session_obj
        m_session_obj.__enter__ = Mock(return_value=m_session_obj)
        m_session_obj.__exit__ = Mock(return_value=False)

        # Call method under test
        assert_raises(SystemExit, self.plugin._get_pod_config)
Example #30
0
    def test_import_content(self, file_storage, isfile):
        path = "/tmp/working/file"
        isfile.return_value = True
        storage = Mock()
        storage.__enter__ = Mock(return_value=storage)
        storage.__exit__ = Mock()
        file_storage.return_value = storage

        # test
        unit = TestFileContentUnit.TestUnit()
        unit._last_updated = 1234
        unit.import_content(path)

        # validation
        file_storage.assert_called_once_with()
        storage.__enter__.assert_called_once_with()
        storage.__exit__.assert_called_once_with(None, None, None)
        storage.put.assert_called_once_with(unit, path, None)