Example #1
0
def test_lazylist_map_no_call():
    mock_func = Mock()
    double_func = lambda x: x * 2
    ll = LazyList([mock_func])
    ll_mapped = ll.map(double_func)
    assert id(ll) != id(ll_mapped)
    mock_func.assert_not_called()
    def test_execute_with_ids(self):
        engine = Mock()
        engine.log = Mock()
        engine.log.info = MagicMock()
        engine.log.failed = MagicMock()

        topics1 = [Mock()]
        get_topics_mock1 = Mock(return_value=topics1)

        topics2 = []
        get_topics_mock2 = Mock(return_value=topics2)

        execute_mock1 = Mock()
        # Exception shouldn't be thrown because there are no tocpis for plugin
        execute_mock2 = Mock(return_value=Exception)

        self.tracker1.execute = execute_mock1
        self.tracker1.get_topics = get_topics_mock1

        self.tracker2.execute = execute_mock2
        self.tracker2.get_topics = get_topics_mock2

        ids = [1, 2]
        self.trackers_manager.execute(engine, ids)

        self.assertTrue(engine.log.info.called)
        self.assertFalse(engine.log.failed.called)  # Check that exception from tracker2 wasn't raised
        get_topics_mock1.assert_called_with(ids)
        execute_mock1.assert_called_with(topics1, engine)
        get_topics_mock2.assert_called_with(ids)
        execute_mock2.assert_not_called()
Example #3
0
    def test_command_has_no_sub___action_from_command_is_called(
        self, action_res, other_action_res, sub_parser_names, command_name
    ):
        selected = choice(sub_parser_names)

        action_mock = Mock(return_value=action_res)
        other_action_mock = Mock(return_value=other_action_res)

        class SubCmd(cmd.Base):
            def action(self, args):
                return action_mock(args)

        class OtherSubCmd(cmd.Base):
            def action(self, args):
                return other_action_mock(args)

        class Cmd(cmd.Base):
            sub_commands = dict((n, (SubCmd if n == selected else OtherSubCmd)) for n in sub_parser_names)

        sys.argv = ["foo", selected]

        command = Cmd(command_name)
        res = command.run()

        self.assertEqual(res, action_res)
        action_mock.assert_called_once_with(command.parse_args())
        other_action_mock.assert_not_called()
    def test_update(self, include_prerelease, is_started, start_interval, enabled, interval, start_called, stop_called):
        checker = NewVersionChecker(False)

        def start_side_effect(i):
            checker.interval = i

        start_mock = Mock(side_effect=start_side_effect)
        stop_mock = Mock()
        is_started_mock = Mock(return_value=is_started)

        checker.interval = start_interval
        checker.start = start_mock
        checker.stop = stop_mock
        checker.is_started = is_started_mock

        checker.update(include_prerelease, enabled, interval)

        self.assertEqual(checker.interval, interval)
        self.assertEqual(checker.include_prereleases, include_prerelease)
        if start_called:
            start_mock.assert_called_once_with(interval)
        else:
            start_mock.assert_not_called()

        if stop_called:
            stop_mock.assert_called_once()
        else:
            stop_mock.assert_not_called()
Example #5
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)
Example #6
0
def test_lazylist_copy_lazy():
    mock_func = Mock()
    mock_func.return_value = 1
    ll = LazyList([mock_func] * 10)
    copied_ll = ll.copy()
    assert len(copied_ll) == 10
    assert id(ll._callables) != id(copied_ll._callables)
    mock_func.assert_not_called()
Example #7
0
    def test_only_call_actions(self):
        self.options["-invoke"] = True

        invoke = Mock()
        self.dispatcher._invoke = invoke

        dispatch(self.options, self.dispatcher)

        invoke.assert_not_called()
Example #8
0
    def test_bad_request_missed_required_field_set_pause_state(self):
        set_topic_paused_mock = Mock(side_effect=KeyError)
        self.tracker_manager.set_topic_paused = set_topic_paused_mock

        topic_parse = TopicPauseState(self.tracker_manager)
        self.api.add_route("/api/topic/{id}/pause", topic_parse)

        self.simulate_request("/api/topic/{0}/pause".format(1), method="POST", body=json.dumps({"wrong": "value"}))
        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
        set_topic_paused_mock.assert_not_called()
Example #9
0
    def test_format_magic_method_without_regex_simple(self):
        m = Mock()
        s = XFormatUnicode(u"thiago fraz\xe3o")
        s._do_formatting = m
        s._do_formatting.return_value = ""

        ret = u"bla {0}".format(s)

        m.assert_not_called()
        self.assertEquals(ret, "bla " + s)
Example #10
0
    def test_format_magic_method_without_regex_complex(self):
        m = Mock()
        s = XFormatUnicode(u"bla")
        s._do_formatting = m
        s._do_formatting.return_value = ""

        ret = u"{0:^10}".format(s)

        m.assert_not_called()
        self.assertEquals(ret, "   bla    ")
Example #11
0
    def test_areyousure_no(self):
        yes = Mock()
        no = Mock()

        yes_func, no_func = self.sut.areyousure(yes, no)
        no_func()

        no.assert_called_once()
        self.widget.escape.assert_called_once()
        yes.assert_not_called()
Example #12
0
    def test_start_editing_backspace_empty_text(self):
        self.sut.submit_command = Mock()
        self.widget.command_line_text = "not empty command"
        callback = Mock()

        complete, enter, backspace = self.sut.start_editing(callback, ())
        backspace()

        self.widget.stop_editing.assert_not_called()
        self.sut.submit_command.assert_not_called()
        callback.assert_not_called()
    def test_is_started(self):
        checker = NewVersionChecker(False)

        execute_mock = Mock(return_value=True)
        checker.execute = execute_mock

        checker.start(10)
        self.assertTrue(checker.is_started())
        checker.stop()
        self.assertFalse(checker.is_started())

        execute_mock.assert_not_called()
    def test_start_twice_should_raise(self):
        checker = NewVersionChecker(False)

        execute_mock = Mock(return_value=True)
        checker.execute = execute_mock

        checker.start(10)
        with self.assertRaises(Exception):
            checker.start(10)
        checker.stop()

        execute_mock.assert_not_called()
    def test_timer_stop_dont_call_execute(self):
        checker = NewVersionChecker(False)

        execute_mock = Mock(return_value=True)
        checker.execute = execute_mock

        checker.start(1)
        checker.stop()

        execute_mock.assert_not_called()

        self.assertLess(execute_mock.call_count, 4)
Example #16
0
    def test_revert_before_run(self):
        # Reverting without running is not valid
        _run_mock = Mock()

        class RunlessTask(Task):
            @classmethod
            def _run(cls, state, children, abort, term):
                return _run_mock(cls, state, children, abort, term)

        task = RunlessTask(self.rollout_id)
        self.assertRaises(Exception, task.revert)

        _run_mock.assert_not_called()
Example #17
0
    def test_fetch_requests_uses_exiting_token(self, request, sleep):
        post_response_mock = Mock()
        post_response_mock.raise_for_status = Mock(return_value=False)
        post_response_mock.json = Mock(return_value={"token": "token1", "expires": "123"})
        request.post = Mock(return_value=post_response_mock)

        request_token_mock = Mock()
        request.post = post_response_mock

        return_false_for_status_mock = Mock(return_value=(True, None))
        self.patient._request_token = request_token_mock
        self.patient.token_expire_milliseconds = (time() * 1000) + 10000
        self.patient._return_false_for_status = return_false_for_status_mock

        self.patient._fetch("url")

        request_token_mock.assert_not_called()
    def test_execute(self, value):
        execute_mock = Mock()
        plugin_type2 = type("ExecuteMixin", (TrackerPluginMixinBase,), {"execute": execute_mock})
        plugin_type3 = type(
            "MockPlugin4",
            (WithCredentialsMixin, plugin_type2, TrackerPluginBase),
            {
                "_prepare_request": self.empty_lambda,
                "parse_url": self.empty_lambda,
                "can_parse_url": self.empty_lambda,
                "verify": lambda s: value,
                "login": lambda s: LoginResult.IncorrentLoginPassword,
            },
        )
        plugin = plugin_type3()

        engine = Mock()
        plugin.execute(None, engine)
        if value:
            execute_mock.assert_called_with(None, engine)
        else:
            execute_mock.assert_not_called()
Example #19
0
    def test_request_context_caching(self):
        """
        Test that the RequestContext is cached in the RequestCache.
        """
        with patch("edxmako.request_context.get_current_request", return_value=None):
            # requestcontext should be None, because the cache isn't filled
            self.assertIsNone(get_template_request_context())

        with patch("edxmako.request_context.get_current_request", return_value=self.request):
            # requestcontext should not be None, and should fill the cache
            self.assertIsNotNone(get_template_request_context())

        mock_get_current_request = Mock()
        with patch("edxmako.request_context.get_current_request", mock_get_current_request):
            # requestcontext should not be None, because the cache is filled
            self.assertIsNotNone(get_template_request_context())
        mock_get_current_request.assert_not_called()

        RequestCache.clear_request_cache()

        with patch("edxmako.request_context.get_current_request", return_value=None):
            # requestcontext should be None, because the cache isn't filled
            self.assertIsNone(get_template_request_context())
class Testget_rate_limited_function(TestCase):
    def setUp(self):
        self.mock_func, self.mock_limit = Mock(name="func"), Mock(name="limit")
        self.rate_limited_func = funcutils.get_rate_limited_function(self.mock_func, self.mock_limit)

    def _assert_initialized_correctly_with_mocks(self, rate_limited_func_arg):
        """
        Assert the rate_limited_func argument was correctly initialized with
        the mocks created in setUp as its func and limit.
        """
        self.assertIs(rate_limited_func_arg.func, self.mock_func)
        self.assertIs(rate_limited_func_arg.limit, self.mock_limit)
        self.assertEqual(rate_limited_func_arg.last_called, False)

    def test_init_with_positional_args(self):
        """
        Rate-limited functions can be initialized with the function and limit in that order.
        """
        self._assert_initialized_correctly_with_mocks(
            funcutils.get_rate_limited_function(self.mock_func, self.mock_limit)
        )

    def test_init_with_keyword_args(self):
        """
        Rate-limited functions can be initialized with limit and func keyword arguments.
        """
        self._assert_initialized_correctly_with_mocks(
            funcutils.get_rate_limited_function(limit=self.mock_limit, func=self.mock_func)
        )

    def test_repr(self):
        """
        A rate-limited function's repr is what we expect.
        """
        self.rate_limited_func.last_called = mock_last_called = Mock()
        self.assertEqual(
            repr(self.rate_limited_func),
            (
                "get_rate_limited_function("
                "func=" + repr(self.mock_func) + ", "
                "limit=" + repr(self.mock_limit) + ", "
                "last_called=" + repr(mock_last_called)
            )
            + ")",
        )

    def test_calling_rate_limited_func_delegates_to_wrapped_func(self):
        """
        Calling a rate-limited function delegates to the wrapped function.
        """
        self.rate_limited_func.limit = 1
        arg, kwarg = Mock(name="arg"), Mock(name="kwarg")
        self.rate_limited_func(arg, kwarg=kwarg)
        self.mock_func.assert_called_once_with(arg, kwarg=kwarg)

    def test_calling_func_attribute_calls_wrapped_function(self):
        """
        Calling a rate-limited function's func attribute calls the wrapped function.
        """
        arg, kwarg = Mock(name="arg"), Mock(name="kwarg")
        self.rate_limited_func.func(arg, kwarg=kwarg)
        self.mock_func.assert_called_once_with(arg, kwarg=kwarg)

    def test_calling_func_attribute_not_rate_limited(self):
        """
        Calling a rate-limited function's func attribute is not affected by rate limiting.
        """
        self.rate_limited_func.limit = 5
        arg0, kwarg0, arg1, kwarg1 = (Mock(name="arg0"), Mock(name="kwarg0"), Mock(name="arg1"), Mock(name="kwarg1"))
        self.rate_limited_func.func(arg0, kwarg=kwarg0)
        self.rate_limited_func.func(arg1, kwarg=kwarg1)

        self.mock_func.assert_has_calls([call(arg0, kwarg=kwarg0), call(arg1, kwarg=kwarg1)])

    def test_rate_limit_respected(self):
        """
        If you call a rate-limited function before the time limit is up, it is called not called.

        This tests behavior with respect to last_called, rather than actually sleeping.
        """
        self.rate_limited_func.limit = 1
        self.rate_limited_func.last_called = time() - 0.5
        self.rate_limited_func()
        self.mock_func.assert_not_called()

    def test_can_call_again_if_last_called_older_than_limit(self):
        """
        If you call a rate-limited function a second time after the time limit is up, it is called twice.

        This tests behavior with respect to last_called, rather than actually sleeping.
        """
        self.rate_limited_func.limit = 100
        self.rate_limited_func.last_called = time() - 100
        self.rate_limited_func()
        self.mock_func.assert_has_calls([call()])

    def test_last_called_set_when_called(self):
        """
        If you call a rate-limited function, last_called is set to a new value.
        """
        self.rate_limited_func.limit = 1
        self.assertEqual(self.rate_limited_func.last_called, False)
        self.rate_limited_func()
        self.assertAlmostEqual(self.rate_limited_func.last_called, time(), places=2)

    def test_last_called_not_set_when_called_within_time_limit(self):
        """
        If you call a rate-limited function during the time limit, last_called is not set to a new value.
        """
        self.rate_limited_func.limit = 1
        self.assertEqual(self.rate_limited_func.last_called, False)
        self.rate_limited_func()
        last_called = self.rate_limited_func.last_called
        self.rate_limited_func()
        self.assertIs(last_called, self.rate_limited_func.last_called)

    def test_end_to_end(self):
        """
        A rate-limited function works as expected.

        A rate-limited function delegates to the wrapped function, then
        prevents calls until the time limit has passed, then allows calls
        again.
        """
        self.rate_limited_func.limit = 0.5
        self.rate_limited_func()
        self.mock_func.assert_called_once()

        # If called before limit has elapsed, the wrapped function won't be
        # called again.
        self.rate_limited_func()
        self.mock_func.assert_called_once()

        # After limit has elapsed, the wrapped function can be called again.
        sleep(0.5)
        self.rate_limited_func()
        self.mock_func.assert_has_calls([call(), call()])
Example #21
0
class BaseDealerTest(BankMockerTest):
    # pylint: disable=too-few-public-methods
    """A container for utility classes common when testing the Dealer class."""
    FEATURES = {
        BANK_PATH_1: (FEATURE_PATH_1, "", FEATURE_1 + "\n"),
        BANK_PATH_2: (FEATURE_PATH_2, "", FEATURE_2 + "\n"),
    }

    def __init__(self):
        super(BaseDealerTest, self).__init__()
        self.dealer = None
        self.mocked_open = MockOpen()
        self.mocked_popen = create_autospec(Popen)
        self.mocked_mkdir = Mock()

    def teardown(self):
        super(BaseDealerTest, self).teardown()
        patch.stopall()

        # Reset dealer instance.
        self.dealer = None

    def _mock_dealer_functions(self):
        """Mock out standard library functions used by the dealer module."""
        self._reset_mocks()

        patcher = patch.multiple(
            "bddbot.dealer",
            open=self.mocked_open,
            Bank=self.mock_bank_class,
            RemoteBank=self.mock_bank_class,
            Popen=self.mocked_popen,
            mkdir=self.mocked_mkdir,
        )

        patcher.start()

    def _create_dealer(self, banks, tests, name=""):
        """Create a new dealer instance without loading state."""
        if tests is None:
            tests = DEFAULT_TEST_COMMANDS

        self.mocked_open[STATE_PATH].side_effect = IOError()
        self.dealer = Dealer(banks, tests, name=name)

        self.mocked_open.assert_called_once_with(STATE_PATH, "rb")

        self._reset_mocks()

    def _load_dealer(self, banks=None, tests=None, name=""):
        """Simulate a call to load() and verify success."""
        if banks is None:
            banks = [BANK_PATH_1]
        if not tests:
            tests = DEFAULT_TEST_COMMANDS

        if self.dealer is None:
            self._create_dealer(banks, tests, name=name)

        # pylint: disable=bad-continuation
        with patch.multiple("bddbot.dealer", Bank=self.mock_bank_class, RemoteBank=self.mock_bank_class):
            self.dealer.load()

        # Verify calls to mocks.
        self.mocked_open.assert_not_called()
        self.mocked_popen.assert_not_called()

        for path in banks:
            if not path.startswith("@"):
                self.mock_bank_class.assert_any_call(path)
            else:
                (host, port) = path[1:].split(":")
                self.mock_bank_class.assert_called_with(name, host, int(port))

        self._reset_mocks()

    def _deal(self, expected_feature, expected_scenario, bank_path=None, feature_path=None):
        # pylint: disable=too-many-arguments
        """Simulate dealing a scenario and verify success.

        If `expected_feature` is specified, simulate the first time a scenario is dealt from
        the features bank. Otherwise, simulate a consecutive deal from a previous bank.

        Return the commands passed to `Popen()` to verify outside of this function.
        """
        if not bank_path:
            bank_path = BANK_PATH_1

        if not feature_path:
            feature_path = bank_path.replace("bank", "feature")

        self.mocked_popen.return_value.returncode = 0
        self.mocked_popen.return_value.communicate.return_value = ("", "")

        self.dealer.deal()

        # If feature is specified, simulate the first deal from the features bank.
        if expected_feature is not None:
            self.mocked_open.assert_called_once_with(feature_path, "w")

            self._assert_writes(["", expected_feature + "\n", expected_scenario], path=feature_path)

            self.mocked_mkdir.assert_called_once_with(dirname(feature_path))

        # If feature isn't specified, simulate a consecutive deal.
        # Note that calls to Popen should be verified outside of this function in this case.
        else:
            self.mocked_open.assert_called_once_with(feature_path, "ab")
            self.mocked_open[feature_path].write.assert_called_once_with(expected_scenario)
            self.mocked_popen.return_value.communicate.assert_called_with()
            self.mocked_mkdir.assert_not_called()

        self.mock_banks[bank_path].is_fresh.assert_called_with()
        self.mock_banks[bank_path].is_done.assert_called_with()
        self.mock_banks[bank_path].get_next_scenario.assert_called_once_with()

        # We return the commands because we reset the mocks at the end of the function.
        # The stdout/stderr values aren't important, we only care about the commands.
        popen_calls = [command for ((command,), _) in self.mocked_popen.call_args_list]

        # Reset mocks.
        self._reset_mocks()

        return popen_calls

    def _assert_writes(self, chunks, path=FEATURE_PATH_1):
        """Verify all calls to write()."""
        assert_equal([call(chunk) for chunk in chunks], self.mocked_open[path].write.mock_calls)

    def _reset_mocks(self):
        """Reset all mocks."""
        self.mocked_open.reset_mock()
        self.mocked_popen.reset_mock()
        self.mock_bank_class.reset_mock()
        self.mocked_mkdir.reset_mock()

        for mock_bank in self.mock_banks.itervalues():
            mock_bank.reset_mock()
Example #22
0
class TestScript(TestCase):
    def run_it(self, args):
        parser = parser_with_standard_args("test", "test it")
        parser.add_argument("--test", action="store_true")
        self.logging_config = Mock()
        self.output = OutputCapture()
        with Replacer() as r:
            r.replace("logging.basicConfig", self.logging_config)
            r.replace("sys.argv", ("x " + args).split())
            with self.output:
                self.args, self.session = script_setup(parser)

    def test_default(self):
        self.run_it("")
        compare(self.args.test, False)
        self.assertTrue(isinstance(self.session, Session))
        compare(self.session.url, default_url)
        compare(self.session.ssl_context, None)
        self.logging_config.assert_called_once_with(level=logging.WARNING)

    def test_extra_option(self):
        self.run_it("--test")
        compare(self.args.test, True)
        self.assertTrue(isinstance(self.session, Session))
        compare(self.session.url, default_url)
        compare(self.session.ssl_context, None)
        self.logging_config.assert_called_once_with(level=logging.WARNING)

    def test_unsafe_certs(self):
        self.run_it("--unsafe-certs")
        compare(self.args.test, False)
        self.assertTrue(isinstance(self.session, Session))
        compare(self.session.url, default_url)
        self.assertTrue(self.session.ssl_context)
        self.logging_config.assert_called_once_with(level=logging.WARNING)

    def test_full_url(self):
        self.run_it("--url ftp://foo")
        compare(self.args.test, False)
        self.assertTrue(isinstance(self.session, Session))
        compare(self.session.url, "ftp://foo")
        compare(self.session.ssl_context, None)
        self.logging_config.assert_called_once_with(level=logging.WARNING)

    def test_protocol_domain_version(self):
        self.run_it("--protocol http --domain foo --version bar")
        compare(self.args.test, False)
        self.assertTrue(isinstance(self.session, Session))
        compare(self.session.url, "http://foo.attask-ondemand.com/attask/api/bar")
        compare(self.session.ssl_context, None)
        self.logging_config.assert_called_once_with(level=logging.WARNING)

    def test_url_and_others(self):
        with ShouldRaise(SystemExit(2)):
            self.run_it("--url foo --domain bar")
        self.logging_config.assert_not_called()

    def test_log_level(self):
        self.run_it("--log-level 0")
        compare(self.args.test, False)
        self.assertTrue(isinstance(self.session, Session))
        compare(self.session.url, default_url)
        compare(self.session.ssl_context, None)
        self.logging_config.assert_called_once_with(level=0)