Example #1
0
class TestPlugin(unittest.TestCase):
    def setUp(self):
        self.mock = Mock()

    def test__pytest_adoption__gets_general_group(self):
        pytest_addoption(self.mock)
        self.mock.assert_has_calls(call.getgroup("general"))

    def test__pytest_adoption__adds_spec_option(self):
        pytest_addoption(self.mock)
        self.mock.assert_has_calls(
            call.getgroup().addoption(
                "--spec", action="store_true", dest="spec", help="Print test result in specification format"
            )
        )

    @patch("imp.reload")
    def test__pytest_configure__should_not_reload_configuration(self, imp_mock):
        pytest_configure(FakeConfig(spec=False))
        self.assertEqual(len(imp_mock.mock_calls), 0)

    @patch("imp.reload")
    def test__pytest_configure__reloads_pytest_after_patching(self, imp_mock):
        pytest_configure(FakeConfig(spec=True))
        self.assertEqual(len(imp_mock.mock_calls), 1)
Example #2
0
    def test_get_cuts(self):
        gps_station = (datetime_to_gps(datetime(2014, 1, 1, 10, 3)), datetime_to_gps(datetime(2014, 3, 1, 11, 32)))
        gps_ref_station = (
            datetime_to_gps(datetime(2014, 1, 5, 0, 1, 1)),
            datetime_to_gps(datetime(2014, 3, 5, 3, 34, 4)),
        )
        elec_station = (
            datetime_to_gps(datetime(2014, 1, 3, 3, 34, 3)),
            datetime_to_gps(datetime(2014, 3, 5, 23, 59, 59)),
        )
        elec_ref_station = (
            datetime_to_gps(datetime(2014, 1, 9, 0, 0, 0)),
            datetime_to_gps(datetime(2014, 3, 15, 1, 2, 3)),
        )
        gps_mock = Mock()
        elec_mock = Mock()

        gps_mock.side_effect = [array(gps_station), array(gps_ref_station)]
        elec_mock.side_effect = [array(elec_station), array(elec_ref_station)]

        self.off._get_electronics_timestamps = elec_mock
        self.off._get_gps_timestamps = gps_mock

        cuts = self.off._get_cuts(sentinel.station, sentinel.ref_station)

        elec_mock.assert_has_calls([call(sentinel.ref_station), call(sentinel.station)], any_order=True)
        gps_mock.assert_has_calls([call(sentinel.ref_station), call(sentinel.station)], any_order=True)

        self.assertEqual(len(cuts), 8)
        six.assertCountEqual(self, sorted(cuts), cuts)
        self.assertEqual(cuts[0], datetime(2014, 1, 1))
        today = datetime.now()
        self.assertEqual(cuts[-1], datetime(today.year, today.month, today.day))
Example #3
0
def test_display():
    # Given

    matrix = Mock()
    color = Mock()
    font = Mock()
    draw = Mock()
    sleep = Mock()

    canvas = Mock()
    canvas.width = 2
    matrix.CreateFrameCanvas.return_value = canvas
    matrix.SwapOnVSync.return_value = canvas
    draw.side_effect = [1, 0, 0]
    text = "Hi"

    tape = Tape(matrix, color, font, draw, sleep)

    # When
    tape.display(text)

    # Then
    draw1 = call(canvas, font, 2, 12, color, text)
    draw2 = call(canvas, font, 2, 12, color, text)
    draw3 = call(canvas, font, 1, 12, color, text)
    draw.assert_has_calls([draw1, draw2, draw3], any_order=False)
    sleep.assert_has_calls([call(0.05), call(0.05)])
    assert canvas.Clear.call_count == 2
Example #4
0
def test_run_sphinx():
    t = build_sphinx.build_sphinx(Distribution(attrs={"name": "RunSphinx", "version": sentinel.v}))
    t._make_sphinx_setup = Mock()
    t.all_files = sentinel.all_files
    builder_name = "my_builder"

    sphinx_mock = {"Sphinx": Mock()}
    makedirs_mock = Mock()

    expected_build_dir = os.path.join(t.build_dir, builder_name)
    expected_doc_dir = os.path.join(t.build_dir, "doctrees")

    with ExitStack() as stack:
        stack.enter_context(_mock_modules({"sphinx.application": sphinx_mock}))
        stack.enter_context(patch("os.path.isdir", return_value=False))
        stack.enter_context(patch("os.makedirs", new=makedirs_mock))
        stack.enter_context(patch("os.path.abspath", new=lambda f: "ABS: " + f))
        t.run_sphinx(builder_name)

    # Check directories were created
    calls = [call(t.build_dir), call(expected_doc_dir), call(expected_build_dir)]
    makedirs_mock.assert_has_calls(calls, any_order=True)

    sphinx = sphinx_mock["Sphinx"]
    sphinx.assert_called_once_with(
        srcdir="ABS: " + t.source_dir,
        confdir="ABS: " + t.source_dir,
        outdir="ABS: " + expected_build_dir,
        doctreedir="ABS: " + expected_doc_dir,
        buildername=builder_name,
        confoverrides={"version": sentinel.v, "release": sentinel.v},
        status=sys.stdout,
        freshenv=False,
    )
Example #5
0
 def test_ensure_testing_spec_base_image_build(self):
     mock_docker_client = Mock()
     mock_build = Mock()
     mock_docker_client.build = mock_build
     testing_spec = {"build": "/path/to/docker_file_folder"}
     _ensure_testing_spec_base_image(mock_docker_client, testing_spec)
     mock_build.assert_has_calls([call(path="/path/to/docker_file_folder", tag="dusty_testing_base/image")])
Example #6
0
 def test_ensure_base_image_build(self, fake_docker_client, fake_testing_spec, fake_expanded_libs):
     fake_docker_client.return_value = fake_docker_client
     mock_build = Mock()
     fake_docker_client.build = mock_build
     testing_spec = {"build": "/path/to/docker_file_folder"}
     fake_testing_spec.return_value = testing_spec
     _ensure_base_image(testing_spec)
     mock_build.assert_has_calls([call(path="/path/to/docker_file_folder", tag="dusty_testing_base/image")])
    def test_delete_loops_through_all_resources(self):
        instance = StaticGenerator("/some_path", "/some_path_2")
        remove = Mock()
        with nested(patch("os.path.exists", Mock(return_value=True)), patch("os.remove", remove)):

            instance.delete()

        remove.assert_has_calls([call("test_web_root/fresh/some_path"), call("test_web_root/fresh/some_path_2")])
    def test_delete_from_path_deletes_current_file(self):
        instance = StaticGenerator()
        remove = Mock()
        with nested(patch("os.path.exists", Mock(return_value=True)), patch("os.remove", remove)):

            instance.delete_from_path("/some_path")

        remove.assert_has_calls([call("test_web_root/fresh/some_path"), call("test_web_root/fresh/some_path.gz")])
Example #9
0
def test_call_id_stack(rabbit_config, predictable_call_ids, runner_factory):
    child_do_called = Mock()

    stack_request = Mock()
    LoggingWorkerContext = get_logging_worker_context(stack_request)

    class Child(object):
        name = "child"

        @rpc
        def child_do(self):
            child_do_called()
            return 1

    class Parent(object):
        name = "parent"

        child_service = RpcProxy("child")

        @rpc
        def parent_do(self):
            return self.child_service.child_do()

    class Grandparent(object):
        name = "grandparent"

        parent_service = RpcProxy("parent")

        @rpc
        def grandparent_do(self):
            return self.parent_service.parent_do()

    runner = runner_factory(rabbit_config)
    runner.add_service(Child, LoggingWorkerContext)
    runner.add_service(Parent, LoggingWorkerContext)
    runner.add_service(Grandparent, LoggingWorkerContext)
    runner.start()

    container = get_container(runner, Grandparent)
    with entrypoint_hook(container, "grandparent_do") as grandparent_do:
        assert grandparent_do() == 1

    # Check child is called
    child_do_called.assert_called_with()
    assert child_do_called.call_count == 1

    # Check IDs were requested
    assert predictable_call_ids.call_count == 3

    # Check call ID stack persisted over RPC
    stack_request.assert_has_calls(
        [
            call(None),
            call(["grandparent.grandparent_do.0"]),
            call(["grandparent.grandparent_do.0", "parent.parent_do.1"]),
        ]
    )
Example #10
0
 def deduping_treats_different_calls_to_same_task_differently(self):
     body = Mock()
     t1 = Task(body)
     pre = [call(t1, 5), call(t1, 7), call(t1, 5)]
     t2 = Task(Mock(), pre=pre)
     c = Collection(t1=t1, t2=t2)
     e = Executor(collection=c)
     e.execute("t2")
     # Does not call the second t1(5)
     body.assert_has_calls([mock_call(5), mock_call(7)])
 def test_validate_dict_passes_undefined_if_a_value_isnt_in_data(self):
     mocked = Mock(return_value={})
     with patch.object(Schema, "_validate", mocked):
         data = {"a": 1, "c": 2}
         schema = {"a": int, "b": int, "c": int, "d": int}
         Schema._validate_dict(schema, data, [])
         mocked.assert_has_calls(
             [call(int, 1, ["a"]), call(int, Undefined, ["b"]), call(int, 2, ["c"]), call(int, Undefined, ["d"])],
             any_order=True,
         )
 def test_validate_dict_calls_validate_once_for_each_key(self):
     # TODO: Should we be checking this, or just checking the output?
     mocked = Mock(return_value={})
     with patch.object(Schema, "_validate", mocked):
         schema = {"a": unicode, "c": int, "e": unicode, "g": bool}
         data = {"a": "b", "c": 4, "e": "f", "g": True}
         Schema._validate_dict(schema, data, [])
         mocked.assert_has_calls(
             [call(unicode, "b", ["a"]), call(int, 4, ["c"]), call(unicode, "f", ["e"]), call(bool, True, ["g"])],
             any_order=True,
         )
Example #13
0
    def test_hostport_or_instance_config(self, publish_mock):

        testcases = {
            "default": {"config": {}, "calls": [call("6379", "localhost", 6379)]},  # test default settings
            "host_set": {"config": {"host": "myhost"}, "calls": [call("6379", "myhost", 6379)]},
            "port_set": {"config": {"port": 5005}, "calls": [call("5005", "localhost", 5005)]},
            "hostport_set": {"config": {"host": "megahost", "port": 5005}, "calls": [call("5005", "megahost", 5005)]},
            "instance_1_host": {"config": {"instances": ["nick@myhost"]}, "calls": [call("nick", "myhost", 6379)]},
            "instance_1_port": {"config": {"instances": ["nick@:9191"]}, "calls": [call("nick", "localhost", 9191)]},
            "instance_1_hostport": {
                "config": {"instances": ["nick@host1:8765"]},
                "calls": [call("nick", "host1", 8765)],
            },
            "instance_2": {
                "config": {"instances": ["foo@hostX", "bar@:1000"]},
                "calls": [call("foo", "hostX", 6379), call("bar", "localhost", 1000)],
            },
            "old_and_new": {
                "config": {
                    "host": "myhost",
                    "port": 1234,
                    "instances": ["foo@hostX", "bar@:1000", "hostonly", ":1234"],
                },
                "calls": [
                    call("foo", "hostX", 6379),
                    call("bar", "localhost", 1000),
                    call("6379", "hostonly", 6379),
                    call("1234", "localhost", 1234),
                ],
            },
        }

        for testname, data in testcases.items():
            config = get_collector_config("RedisCollector", data["config"])

            collector = RedisCollector(config, None)

            mock = Mock(return_value={}, name=testname)
            patch_c = patch.object(RedisCollector, "collect_instance", mock)

            patch_c.start()
            collector.collect()
            patch_c.stop()

            expected_call_count = len(data["calls"])
            self.assertEqual(
                mock.call_count,
                expected_call_count,
                msg="[%s] mock.calls=%d != expected_calls=%d" % (testname, mock.call_count, expected_call_count),
            )
            for exp_call in data["calls"]:
                # Test expected calls 1 by 1,
                # because self.instances is a dict (=random order)
                mock.assert_has_calls(exp_call)
 def test_validate_list_calls_validate_for_each_data_entry(self):
     mocked = Mock(return_value=1)
     with patch.object(Schema, "_validate", mocked):
         Schema._validate_list([int], [], [])
         self.assertFalse(mocked.called)
         mocked.reset_mock()
         Schema._validate_list([int], [1], [])
         mocked.assert_called_once_with(int, 1, [0])
         mocked.reset_mock()
         Schema._validate_list([int], [1, 2, 3], [])
         mocked.assert_has_calls([call(int, 1, [0]), call(int, 2, [1]), call(int, 3, [2])])
 def test_begin_initializes_lcd(self):
     gpio = Mock()
     spi = Mock()
     lcd = LCD.PCD8544(1, 2, gpio=gpio, spi=spi)
     lcd.begin(40)
     # Verify RST is set low then high.
     gpio.assert_has_calls([call.set_low(2), call.set_high(2)])
     # Verify SPI calls.
     spi.assert_has_calls(
         [call.write([0x21]), call.write([0x14]), call.write([0xA8]), call.write([0x20]), call.write([0x0C])]
     )
    def test_upper_level(self, logger_obj, handler_cls):
        handler = Mock()
        handler.configure_mock(level=logging.INFO)
        handler_cls.return_value = handler

        with log_helpers.QuietLogger(logging.WARNING):
            log_helpers.logger.warning("Test")

        handler.assert_has_calls((call.setLevel(logging.WARNING + 1), call.setLevel(logging.INFO)))

        logger_obj.assert_has_calls((call.warning("Test"),))
    def test_publish_loops_through_all_resources(self):
        instance = StaticGenerator("/some_path_1", "/some_path_2")
        rename = Mock(wraps=os.rename)
        with nested(
            patch("os.rename", rename),
            patch.object(instance, "get_content_from_path", Mock(return_value="some_content")),
        ):

            instance.publish()

        rename.assert_has_calls(
            [call(ANY, "test_web_root/fresh/some_path_1"), call(ANY, "test_web_root/fresh/some_path_2")]
        )
Example #18
0
    def test_it_invokes_the_callback_for_two_entities(self):
        # Given
        callback = Mock()
        fake_class = fake("Class_")
        fake_function = fake("Function")
        async_publisher = AsyncPublisher(callback)
        async_publisher.start()

        # When
        async_publisher.on_entity(fake_class)
        async_publisher.on_entity(fake_function)
        async_publisher.stop()

        # Then
        callback.assert_has_calls([call(fake_class), call(fake_function)])
    def test_lower_level(self, logger_obj, handler_cls):
        handler = Mock()
        handler.configure_mock(level=logging.INFO)
        handler_cls.return_value = handler

        with log_helpers.QuietLogger(logging.DEBUG):
            log_helpers.logger.warning("Test")

        handler.assert_has_calls((call.setLevel(logging.INFO),))

        logger_obj.assert_has_calls(
            (
                call.debug("QuietLogger requested lower level, than is already set. " "Not changing level"),
                call.warning("Test"),
            )
        )
Example #20
0
def test_call_id_over_events(rabbit_config, predictable_call_ids, runner_factory):
    one_called = Mock()
    two_called = Mock()

    stack_request = Mock()
    LoggingWorkerContext = get_logging_worker_context(stack_request)

    class EventListeningServiceOne(object):
        name = "listener_one"

        @event_handler("event_raiser", "hello")
        def hello(self, name):
            one_called()

    class EventListeningServiceTwo(object):
        name = "listener_two"

        @event_handler("event_raiser", "hello")
        def hello(self, name):
            two_called()

    class EventRaisingService(object):
        name = "event_raiser"
        dispatch = EventDispatcher()

        @rpc
        def say_hello(self):
            self.dispatch("hello", self.name)

    runner = runner_factory(rabbit_config)
    runner.add_service(EventListeningServiceOne, LoggingWorkerContext)
    runner.add_service(EventListeningServiceTwo, LoggingWorkerContext)
    runner.add_service(EventRaisingService, LoggingWorkerContext)
    runner.start()

    container = get_container(runner, EventRaisingService)
    listener1 = get_container(runner, EventListeningServiceOne)
    listener2 = get_container(runner, EventListeningServiceTwo)
    with entrypoint_hook(container, "say_hello") as say_hello:
        waiter1 = entrypoint_waiter(listener1, "hello")
        waiter2 = entrypoint_waiter(listener2, "hello")
        with waiter1, waiter2:
            say_hello()

    assert predictable_call_ids.call_count == 3
    stack_request.assert_has_calls([call(None), call(["event_raiser.say_hello.0"]), call(["event_raiser.say_hello.0"])])
Example #21
0
class DevelopersWriterTest(unittest.TestCase):
    def setUp(self):
        self.developer = Mock()
        self.developer.login.return_value = "realsugar"
        self.developer.password.return_value = "A1aaaaa"

    def test_htpasswd_update_command(self):
        command = DevelopersWriter.htpasswd_update_command(self.developer)
        expected = "htpasswd -b " + settings.PASSWORDS_PATH + " realsugar A1aaaaa"
        self.developer.assert_has_calls([("login",), ("password",)], any_order=True)
        self.assertEqual(expected, command)

    def test_htpasswd_delete_command(self):
        command = DevelopersWriter.htpasswd_delete_command(self.developer)
        expected = "htpasswd -D " + settings.PASSWORDS_PATH + " realsugar"
        self.developer.assert_has_calls([("login",)])
        self.assertEqual(expected, command)
def test_merge_method_calls_provided_function_for_merging_identical_items():
    package1 = get_package_tree()
    package2 = get_package_tree()

    package_1_classes_list = package1.findall(CLASSES_LIST)
    package_2_classes_list = package2.findall(CLASSES_LIST)

    mock_merge_function = Mock()

    expected_calls = [
        call(package_1_classes_list[0], package_2_classes_list[0]),
        call(package_1_classes_list[1], package_2_classes_list[1]),
    ]

    merge([], package_1_classes_list, package_2_classes_list, ["filename", "name"], mock_merge_function)

    mock_merge_function.assert_has_calls(expected_calls)
 def test_delete_loops_through_all_resources(self):
     instance = StaticGenerator("/path_one", "/path/two")
     remove = Mock()
     with nested(patch("os.path.exists", Mock(return_value=True)), patch("os.remove", remove)):
         instance.delete()
     # default language cache path contains no language code
     remove.assert_has_calls(
         [
             call("test_web_root/fresh/path_one"),
             call("test_web_root/fresh/path_one.gz"),
             call("test_web_root/fresh/fr.path_one"),
             call("test_web_root/fresh/fr.path_one.gz"),
             call("test_web_root/fresh/path/two"),
             call("test_web_root/fresh/path/two.gz"),
             call("test_web_root/fresh/path/fr.two"),
             call("test_web_root/fresh/path/fr.two.gz"),
         ]
     )
Example #24
0
def test_call_id_over_events(rabbit_config, predictable_call_ids, runner_factory):
    one_called = Mock()
    two_called = Mock()

    stack_request = Mock()
    LoggingWorkerContext = get_logging_worker_context(stack_request)

    class HelloEvent(NamekoEvent):
        type = "hello"

    class EventListeningServiceOne(object):
        @event_handler("event_raiser", "hello")
        def hello(self, name):
            one_called()

    class EventListeningServiceTwo(object):
        @event_handler("event_raiser", "hello")
        def hello(self, name):
            two_called()

    class EventRaisingService(object):
        name = "event_raiser"
        dispatch = event_dispatcher()

        @rpc
        def say_hello(self):
            self.dispatch(HelloEvent(self.name))

    runner = runner_factory(rabbit_config)
    runner.add_service(EventListeningServiceOne, LoggingWorkerContext)
    runner.add_service(EventListeningServiceTwo, LoggingWorkerContext)
    runner.add_service(EventRaisingService, LoggingWorkerContext)
    runner.start()

    container = get_container(runner, EventRaisingService)
    with entrypoint_hook(container, "say_hello") as say_hello:
        say_hello()

    with wait_for_call(5, one_called), wait_for_call(5, two_called):

        assert predictable_call_ids.call_count == 3
        stack_request.assert_has_calls(
            [call(None), call(["event_raiser.say_hello.0"]), call(["event_raiser.say_hello.0"])]
        )
    def test_validate_list_calls_validate_for_schema_values_as_necessary(self):
        def mock_return(schema, data, path):
            if not isinstance(data, schema):
                raise Invalid("")
            return data

        mocked = Mock(side_effect=mock_return)
        with patch.object(Schema, "_validate", mocked):
            Schema._validate_list([int, unicode], [], [])
            self.assertFalse(mocked.called)
            mocked.reset_mock()
            Schema._validate_list([int, unicode], ["a"], [])
            mocked.assert_has_calls([call(int, "a", [0]), call(unicode, "a", [0])])
            mocked.reset_mock()
            Schema._validate_list([int, unicode], [1], [])
            mocked.assert_called_once_with(int, 1, [0])
            mocked.reset_mock()
            with self.assertRaises(InvalidGroup):
                Schema._validate_list([int, unicode], [None], [])
            mocked.assert_has_calls([call(int, None, [0]), call(unicode, None, [0])])
    def test_validate_list_calls_validate_for_each_schema_data_combo(self):
        def mock_return(schema, data, path):
            if not isinstance(data, schema):
                raise Invalid("")
            return data

        mocked = Mock(side_effect=mock_return)
        with patch.object(Schema, "_validate", mocked):
            Schema._validate_list([int, unicode], ["a", "b"], [])
            mocked.assert_has_calls(
                [call(int, "a", [0]), call(unicode, "a", [0]), call(int, "b", [1]), call(unicode, "b", [1])]
            )
            mocked.reset_mock()
            with self.assertRaises(InvalidGroup):
                Schema._validate_list([int, unicode], ["a", 1, None], [])
            mocked.assert_has_calls(
                [
                    call(int, "a", [0]),
                    call(unicode, "a", [0]),
                    call(int, 1, [1]),
                    call(int, None, [2]),
                    call(unicode, None, [2]),
                ]
            )
            mocked.reset_mock()
            Schema._validate_list([int, unicode], [1, 2], [])
            mocked.assert_has_calls([call(int, 1, [0]), call(int, 2, [1])])
Example #27
0
class test_Message_DECODER_ENCODER:
    def setup(self):
        self.tgt = Mock()
        self._push = MESSAGE_DECODER(self.tgt)

    def test_simple(self):
        x = MESSAGE_ENCODER(self._push)("hello", hello_world)
        assert_equal(x, 1)
        self.tgt.assert_called_with(hello_world)

    def test_multi_push(self):
        x = MESSAGE_ENCODER(self._push)("hello", [hello_world, hello_other])
        assert_equal(x, 2)
        self.tgt.assert_has_calls([call(hello_world), call(hello_other)])

    def test_empty_push(self):
        MESSAGE_DECODER(self.tgt)(b"")
        self.tgt.assert_has_calls([])

    def test_buffering(self):
        buf = StringIO()
        MESSAGE_ENCODER(buf.write)("hello", hello_world)

        msg = buf.getvalue()
        split = len(msg) / 2
        buf1 = msg[:split]
        buf2 = msg[split:]

        decoder = MESSAGE_DECODER(self.tgt)

        decoder(buf1)
        self.tgt.assert_has_calls([])

        decoder(buf2)
        self.tgt.assert_called_with(hello_world)
Example #28
0
    def test_register_multiple_schemas(self):
        self.getLumberjackObject()

        expected_templates = {
            "type_a": self.build_expected_template("type_a", SCHEMA_A),
            "type_b": self.build_expected_template("type_b", SCHEMA_B),
        }

        if MOCK:
            mock_put_template_f = Mock(return_value=None)
            self.elasticsearch.indices.put_template = mock_put_template_f

            mock_put_mapping_f = Mock(return_value=None)
            self.elasticsearch.indices.put_mapping = mock_put_mapping_f

        self.lj.register_schema("type_a", SCHEMA_A)
        self.lj.register_schema("type_b", SCHEMA_B)

        if MOCK:
            self.assertEqual(mock_put_template_f.call_count, 2)
            mock_put_template_f.assert_has_calls(
                [
                    call(
                        name="lumberjack-" + self.config["index_prefix"] + "type_a", body=expected_templates["type_a"]
                    ),
                    call(
                        name="lumberjack-" + self.config["index_prefix"] + "type_b", body=expected_templates["type_b"]
                    ),
                ]
            )

        if not MOCK:
            res = self.elasticsearch.indices.get_template(name="lumberjack-" + self.config["index_prefix"] + "*")

            self.assertDictContainsSubset(
                expected_templates["type_a"], res["lumberjack-" + self.config["index_prefix"] + "type_a"]
            )
            self.assertDictContainsSubset(
                expected_templates["type_b"], res["lumberjack-" + self.config["index_prefix"] + "type_b"]
            )
Example #29
0
    def test_no_wait_after_get(self):
        log_manager = ExecuteLogManager()
        get_current_execute_log_details_mock = Mock(return_value=[{}])
        log_manager.get_current_execute_log_details = get_current_execute_log_details_mock
        log_manager.is_running = Mock(return_value=True)

        time = TimeMock()

        with patch("monitorrent.rest.execute.time", time):
            execute_log_current = ExecuteLogCurrent(log_manager)

            self.api.add_route(self.test_route, execute_log_current)

            body = self.simulate_request(self.test_route, query_string="after=17", decode="utf-8")

            self.assertEqual(self.srmock.status, falcon.HTTP_OK)

            result = json.loads(body)

            self.assertEqual(result, {"is_running": True, "logs": [{}]})

        get_current_execute_log_details_mock.assert_has_calls([call(17)])
Example #30
0
class URLTestCase(ConnectionTestMixin, TestCase):
    def setUp(self):
        super(URLTestCase, self).setUp()
        self.plugin = self.connection.settings.enable(Default.name, [])
        self.fetch_title = Mock(return_value=succeed("title"))
        self.plugin.fetcher.fetch_title = self.fetch_title
        self.outgoing = self.connection.settings.enable(OutgoingPlugin.name, [])

    def test_simple(self):
        self.receive("PRIVMSG {} :http://www.example.com/".format(self.connection.nickname))
        self.fetch_title.assert_called_with(u"http://www.example.com/", hostname_tag=True, friendly_errors=True)
        self.assertEqual(self.outgoing.last_seen.content, "title")

    def test_multiple_iris(self):
        self.receive("PRIVMSG {} :http://foo.test/ http://bar.test/".format(self.connection.nickname))
        self.fetch_title.assert_has_calls(
            [
                call(u"http://foo.test/", hostname_tag=True, friendly_errors=True),
                call(u"http://bar.test/", hostname_tag=True, friendly_errors=True),
            ]
        )
        self.assertEqual(self.outgoing.last_seen.content, "title")