Example #1
0
    def test_same_mode_no_callback(self):
        """Create a Controller object, call on_new_mode_online method and
        check that the callback fires, but does not fire when
        set_composite_mode is called multiple times with the same format
        """
        self.setup_server()
        self.setup_controller()

        self.log.info("setting callback")
        test_cb = Mock(side_effect=self.quit_mainloop)
        self.controller.on_new_mode_online(test_cb)

        self.log.info("starting test-sources")
        self.setup_video_sources(count=2)

        self.log.info("waiting for initial callback with" "default-mode COMPOSITE_DUAL_EQUAL")
        self.run_mainloop(timeout=5)
        test_cb.assert_called_once_with(Controller.COMPOSITE_DUAL_EQUAL)
        test_cb.reset_mock()

        self.log.info("setting the same composite mode" "(COMPOSITE_DUAL_EQUAL) again")
        assert not self.controller.set_composite_mode(Controller.COMPOSITE_DUAL_EQUAL)

        self.log.info("setting a new composite-mode COMPOSITE_PIP")
        assert self.controller.set_composite_mode(Controller.COMPOSITE_PIP)
        self.run_mainloop(timeout=5)

        # just waiting for the timeout to verify no incoming call
        # would slow down the tests remarebly, so we send another
        # mode-change, knowing that when it arrives without an
        # intermediate call, there was no duplicate callback

        self.log.info("waiting for callback with new mode COMPOSITE_PIP")
        test_cb.assert_called_once_with(Controller.COMPOSITE_PIP)
Example #2
0
    def test_entry_init(self, mock_entry_init):
        eset = self.get_obj()
        eset.entries = dict()
        evt = Mock()
        evt.filename = "test.txt"
        handler = Mock()
        handler.__basenames__ = []
        handler.__extensions__ = []
        handler.deprecated = False
        handler.experimental = False
        handler.__specific__ = True

        # test handling an event with the parent entry_init
        eset.entry_init(evt, handler)
        mock_entry_init.assert_called_with(eset, evt, entry_type=handler, specific=handler.get_regex.return_value)
        self.assertItemsEqual(eset.entries, dict())

        # test handling the event with a Cfg handler
        handler.__specific__ = False
        eset.entry_init(evt, handler)
        handler.assert_called_with(os.path.join(eset.path, evt.filename))
        self.assertItemsEqual(eset.entries, {evt.filename: handler.return_value})
        handler.return_value.handle_event.assert_called_with(evt)

        # test handling an event for an entry that already exists with
        # a Cfg handler
        handler.reset_mock()
        eset.entry_init(evt, handler)
        self.assertFalse(handler.called)
        self.assertItemsEqual(eset.entries, {evt.filename: handler.return_value})
        eset.entries[evt.filename].handle_event.assert_called_with(evt)
    def test_maps(self):
        mock_client = Mock(spec=Client, name="client")
        mock_cmd = Mock(spec=Command)

        # None
        self.console.getMaps = Mock(return_value=None)
        self.p.cmd_maps(data=None, client=mock_client, cmd=mock_cmd)
        mock_client.message.assert_called_once_with("^7Error: could not get map list")

        # no map
        self.console.getMaps = Mock(return_value=[])
        self.p.cmd_maps(data=None, client=mock_client, cmd=mock_cmd)
        mock_cmd.sayLoudOrPM.assert_called_once_with(mock_client, "^7Map Rotation list is empty")

        # one map
        mock_cmd.reset_mock()
        self.console.getMaps = Mock(return_value=["foo"])
        self.p.cmd_maps(data=None, client=mock_client, cmd=mock_cmd)
        mock_cmd.sayLoudOrPM.assert_called_once_with(mock_client, "^7Map Rotation: ^2foo")

        # many maps
        mock_cmd.reset_mock()
        self.console.getMaps = Mock(return_value=["foo1", "foo2", "foo3"])
        self.p.cmd_maps(data=None, client=mock_client, cmd=mock_cmd)
        mock_cmd.sayLoudOrPM.assert_called_once_with(mock_client, "^7Map Rotation: ^2foo1^7, ^2foo2^7, ^2foo3")
def test_main(monkeypatch):
    # Check that questions are asked and a config file generated
    mock_cli_wrapper = Mock(return_value={"dimensions": (2, 2), "ip_address": "127.0.0.1"})
    monkeypatch.setattr(wizard, "cli_wrapper", mock_cli_wrapper)

    # Temporarily any existing project config file out of the way
    config = nengo_spinnaker_rc["project"]
    if os.path.isfile(config):  # pragma: no cover
        _, temp = tempfile.mkstemp()
        print(config, temp)
        shutil.move(config, temp)
    else:
        temp = None

    # Create a project config file in the test runner's directory (which
    # shouldn't exist yet).
    assert main("-p".split()) == 0
    assert mock_cli_wrapper.called
    mock_cli_wrapper.reset_mock()
    assert os.path.isfile(config)

    # Should fail to create a config file when one already exists
    assert main("-p".split()) != 0
    assert not mock_cli_wrapper.called

    # ...unless forced
    assert main("-p --force".split()) == 0
    assert mock_cli_wrapper.called
    mock_cli_wrapper.reset_mock()

    # Restore the old config file
    if temp is not None:  # pragma: no cover
        shutil.move(temp, config)
    else:
        os.remove(config)
Example #5
0
    def test_create_subscription(self):
        pubsub = Mock()
        pubsub.topic.return_value = Mock()
        q = BroadcastQueue(pubsub)

        sub = Mock()
        sub.exists.return_value = False

        # Test to make sure it creates a unique (non-shared) subscription.
        with patch("gcloud.pubsub.Subscription") as SubscriptionMock:
            SubscriptionMock.return_value = sub
            rsub = q._get_or_create_subscription()

            assert rsub == sub
            assert "worker" in SubscriptionMock.call_args[0][0]
            assert "broadcast" in SubscriptionMock.call_args[0][0]
            assert sub.exists.called
            assert sub.create.called

        # Test reusing existing
        with patch("gcloud.pubsub.Subscription") as SubscriptionMock:
            sub.reset_mock()
            SubscriptionMock.return_value = sub
            sub.exists.return_value = True
            rsub = q._get_or_create_subscription()

            assert rsub == sub
            assert not sub.create.called
Example #6
0
    def test_save(self, mock_dump, mock_open):
        core = Mock()
        ts = self.get_obj(core)
        queue = Mock()
        queue.empty = Mock(side_effect=Empty)
        ts.work_queue = queue

        mock_open.side_effect = IOError
        # test that save does _not_ raise an exception even when
        # everything goes pear-shaped
        ts._save()
        queue.empty.assert_any_call()
        mock_open.assert_called_with(ts.pending_file, "w")

        queue.reset_mock()
        mock_open.reset_mock()

        queue.data = []
        for hostname, xml in self.data:
            md = Mock()
            md.hostname = hostname
            queue.data.append((md, lxml.etree.XML(xml)))
        queue.empty.side_effect = lambda: len(queue.data) == 0
        queue.get_nowait = Mock(side_effect=lambda: queue.data.pop())
        mock_open.side_effect = None

        ts._save()
        queue.empty.assert_any_call()
        queue.get_nowait.assert_any_call()
        mock_open.assert_called_with(ts.pending_file, "w")
        mock_open.return_value.close.assert_any_call()
        # the order of the queue data gets changed, so we have to
        # verify this call in an ugly way
        self.assertItemsEqual(mock_dump.call_args[0][0], self.data)
        self.assertEqual(mock_dump.call_args[0][1], mock_open.return_value)
Example #7
0
    def test_invalidate_function_with_args(self):
        def my_func(name):  # pragma: nocover
            return "Hello %s" % name

        my_func._region = "short_term"
        my_func._namespace = "retools:a_key decarg"

        mock_redis = Mock(spec=redis.client.Redis)
        mock_redis.smembers.return_value = {"1"}

        invalidate_function = self._makeOne()
        with patch("retools.global_connection._redis", mock_redis):
            CR = self._makeCR()
            CR.add_region("short_term", expires=600)

            invalidate_function(my_func, "fred")
            calls = mock_redis.method_calls
            eq_(calls[0][1][0], "retools:short_term:retools:a_key decarg:fred")
            eq_(calls[0][0], "hset")
            eq_(len(calls), 1)

            # And a unicode key
            mock_redis.reset_mock()
            invalidate_function(my_func, "\u03b5\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac")
            calls = mock_redis.method_calls
            eq_(
                calls[0][1][0],
                "retools:short_term:retools:a_key" " decarg:\u03b5\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac",
            )
            eq_(calls[0][0], "hset")
            eq_(len(calls), 1)
Example #8
0
    def test_reconnect_listener(self):
        # configure fewer retries/wait period to make tests faster
        self.command.max_reconnect_retries = 3
        self.command.retry_reconnect_wait = 1

        mocklistener = Mock(Stomp)
        # raise an error every time - no reconnection
        mocklistener.connect.side_effect = StompConnectTimeout
        # simulate what happens when fedora becomes unavailable
        mocklistener.canRead.return_value = True
        mocklistener.receiveFrame.side_effect = StompFrameError

        with patch("eulindexer.indexer.management.commands.indexer.Stomp", new=Mock(return_value=mocklistener)):
            self.assertRaises(CommandError, self.command.reconnect_listener)
            # listener.connect should be called the configured # of retries
            self.assertEqual(self.command.max_reconnect_retries, mocklistener.connect.call_count)

        mocklistener.reset_mock()  # reset method call count
        mocklistener.raised_error = False
        # error the first time but then connect, to simulate fedora recovery
        def err_then_connect(*args, **kwargs):
            if not mocklistener.raised_error:
                mocklistener.raised_error = True
                raise StompConnectTimeout
            else:
                return DEFAULT

        mocklistener.connect.side_effect = err_then_connect

        with patch("eulindexer.indexer.management.commands.indexer.Stomp", new=Mock(return_value=mocklistener)):
            # should return without raising an exception
            self.command.reconnect_listener()
            # listener.connect should be called twice - failure, then success
            self.assertEqual(2, mocklistener.connect.call_count)
Example #9
0
    def test01_send_mailing(self):
        # Mock the SMTP connection
        mock_smtp = Mock()

        def mock_get_connection(*args, **kargs):
            return mock_smtp

        send.get_connection = mock_get_connection

        # Capture sent emails
        self.msg_list = None

        def send_messages(msg_list):
            self.msg_list = msg_list

        mock_smtp.send_messages.side_effect = send_messages

        send.send_mailing()
        mock_smtp.open.assert_called_once()
        mock_smtp.close.assert_called_once()
        mock_smtp.reset_mock()

        self.assertEqual(len(self.msg_list), 1)
        msg_formatted = str(self.msg_list[0].message())
        self.assertTrue("From: Card Stories <feedback@farsides.com>" in msg_formatted)
        self.assertTrue("Content-Type: multipart/mixed" in msg_formatted)
        self.assertTrue("Content-Type: text/plain" in msg_formatted)
        self.assertTrue("Content-Type: text/html" in msg_formatted)
        self.assertTrue("Content-Type: image/jpeg" in msg_formatted)
    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])])
 def test_when_base_returns_function_value_when_passed_a_function(self):
     mocked = Mock(return_value=8)
     self.assertEqual(_when_base(None, mocked), 8)
     mocked.assert_called_once_with(None)
     mocked.reset_mock()
     self.assertEqual(_when_base("abc", mocked), 8)
     mocked.assert_called_once_with("abc")
Example #12
0
    def test_abort(self):
        self.x = None

        abort_if_not_none = self.abort_if_not_none
        assign = self.assign

        m = Mock()

        # test unaborted workflow
        w = Workflow(steps=[abort_if_not_none, m])
        w(DefaultContext())
        assert m.called

        # test simple aborted workflow
        m.reset_mock()
        self.x = 1
        w = Workflow(steps=[abort_if_not_none, m])
        w(DefaultContext())
        assert not m.called

        # test mid workflow abort
        m.reset_mock()
        self.x = None
        w = Workflow(steps=[abort_if_not_none, lambda context: assign(True), abort_if_not_none, m])
        w(DefaultContext())
        assert self.x is True
        assert not m.called
Example #13
0
    def test_timestamp_prevents_export_run(self):
        from recensio.policy.browser.export import MetadataExport
        _issues_and_volumes = MetadataExport.issues_and_volumes
        mock_issues = Mock(return_value=[])
        MetadataExport.issues_and_volumes = mock_issues

        annotations = IAnnotations(self.portal)
        # fake running export
        annotations[EXPORT_TIMESTAMP_KEY] = time()
        self._clear_export_files()
        output = self.xml_export()
        self.assertFalse(mock_issues.called)
        self.assertIn('abort', output)

        mock_issues.reset_mock()
        # fake running export has finished
        del annotations[EXPORT_TIMESTAMP_KEY]
        self._clear_export_files()
        output = self.xml_export()
        self.assertTrue(mock_issues.called)
        self.assertNotIn('abort', output)

        if EXPORT_TIMESTAMP_KEY in annotations:
            del annotations[EXPORT_TIMESTAMP_KEY]
        MetadataExport.issues_and_volumes = _issues_and_volumes
Example #14
0
class BankMockerTest(object):
    # pylint: disable=too-few-public-methods
    """A base test case class to mock out Bank creation."""

    def __init__(self):
        self.mock_banks = defaultdict(Mock)
        self.mock_bank_class = Mock(side_effect=self.__create_bank)

    def teardown(self):
        self.mock_bank_class.reset_mock()
        self.mock_banks.clear()

    def _setup_bank(self, bank, is_fresh, is_done, scenario):
        """Setup a mock bank."""
        # pylint: disable=no-member
        (output_path, header, feature) = self.FEATURES[bank]

        self.mock_banks[bank].is_fresh.return_value = is_fresh
        self.mock_banks[bank].is_done.return_value = is_done
        self.mock_banks[bank].output_path = output_path
        self.mock_banks[bank].header = header
        self.mock_banks[bank].feature = feature
        self.mock_banks[bank].get_next_scenario.return_value = scenario

    def __create_bank(self, *args):
        """Return a mock Bank instance, or creates a new one and adds it to the map."""
        if 1 == len(args):
            is_remote = False
            (key,) = args
        else:
            is_remote = True
            (_, host, port) = args
            key = "@{host}:{port:d}".format(host=host, port=port)

        return self.mock_banks.setdefault(key, Mock(is_remote=is_remote))
Example #15
0
    def test15_poll_notification(self):
        args = {
            "type": ["tabs"],
            "action": ["poll"],
            "player_id": [13],
            "game_id": [20],
            "modified": [10000000000000000],
        }

        # Fake poll controlled from the test
        poll = defer.Deferred()
        mock_poll_tabs = Mock()
        mock_poll_tabs.return_value = poll
        orig_service_poll_tabs = self.service.poll_tabs
        self.service.poll_tabs = mock_poll_tabs

        mock_listener = Mock()
        self.service.listen().addCallback(mock_listener)
        self.service.poll(args)
        mock_listener.assert_called_once_with({"player_id": 13, "type": "poll_start"})

        mock_listener.reset_mock()
        self.service.listen().addCallback(mock_listener)
        poll.callback(args)
        mock_listener.assert_called_once_with({"player_id": 13, "type": "poll_end"})

        self.service.poll_tabs = orig_service_poll_tabs
Example #16
0
class TestChatOutput(unittest.TestCase):
    def setUp(self):
        self.exampl = irc_async.IRCMessage("TEST 1 2 :trail\r\n")
        self.outfunc = Mock()
        self.do = simplebot.ChatOutput(self.outfunc)

    def tearDown(self):
        self.outfunc.reset_mock()

    def test_send_implicit_trail(self):
        self.do.raw("TEST", "1", "2", "trail")
        self.outfunc.assert_called_with(self.exampl)

    def test_send_explicit_trail(self):
        self.do.raw_trail("TEST", "1", "2", trail="trail")
        self.outfunc.assert_called_with(self.exampl)

    def test_send_nick(self):
        pass

    def test_send_custom(self):
        self.do.test("1", "2", "trail")
        self.outfunc.assert_called_with(self.exampl)

    def test_error_on_send(self):
        pass

    def test_send_privmsg(self):
        pass

    def test_send_multiline(self):
        pass

    def test_send_ml_block(self):
        pass
Example #17
0
    def test_clone(self):
        m = Mock()

        class T1(object):
            pass

        class T2(object):
            pass

        def f1():
            m.f1()

        def n1():
            m.n1()
            return T1(), T2()

        def l1():
            m.l1()

        def t1(obj):
            m.t1()

        def t2(obj):
            m.t2()

        # original
        runner1 = Runner()
        runner1.add(f1, first())
        runner1.add(n1)
        runner1.add(l1, last())
        runner1.add(t1, T1)
        runner1.add(t2, T2)
        # now clone and add bits
        def f2():
            m.f2()

        def n2():
            m.n2()

        def l2():
            m.l2()

        def tn(obj):
            m.tn()

        runner2 = runner1.clone()
        runner2.add(f2, first())
        runner2.add(n2)
        runner2.add(l2, last())
        # make sure types stay in order
        runner2.add(tn, T2)
        # now run both, and make sure we only get what we should
        runner1()
        compare([call.f1(), call.n1(), call.l1(), call.t1(), call.t2()], m.mock_calls)
        m.reset_mock()
        runner2()
        compare(
            [call.f1(), call.f2(), call.n1(), call.n2(), call.l1(), call.l2(), call.t1(), call.t2(), call.tn()],
            m.mock_calls,
        )
Example #18
0
    def testReset(self):
        parent = Mock()
        spec = ["something"]
        mock = Mock(name="child", parent=parent, spec=spec)
        mock(sentinel.Something, something=sentinel.SomethingElse)
        something = mock.something
        mock.something()
        mock.side_effect = sentinel.SideEffect
        return_value = mock.return_value
        return_value()

        mock.reset_mock()

        self.assertEqual(mock._name, "child", "name incorrectly reset")
        self.assertEqual(mock._parent, parent, "parent incorrectly reset")
        self.assertEqual(mock._methods, spec, "methods incorrectly reset")

        self.assertFalse(mock.called, "called not reset")
        self.assertEqual(mock.call_count, 0, "call_count not reset")
        self.assertEqual(mock.call_args, None, "call_args not reset")
        self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
        self.assertEqual(
            mock.method_calls, [], "method_calls not initialised correctly: %r != %r" % (mock.method_calls, [])
        )

        self.assertEqual(mock.side_effect, sentinel.SideEffect, "side_effect incorrectly reset")
        self.assertEqual(mock.return_value, return_value, "return_value incorrectly reset")
        self.assertFalse(return_value.called, "return value mock not reset")
        self.assertEqual(mock._children, {"something": something}, "children reset incorrectly")
        self.assertEqual(mock.something, something, "children incorrectly cleared")
        self.assertFalse(mock.something.called, "child not reset")
Example #19
0
    def test_refund_transaction(self, one):
        bid = Mock()
        bid.pay_id = 111
        transaction_id = 123
        campaign_id = 99
        amount = 100

        one.return_value = bid

        # Scenario: transaction_id < 0
        return_value = refund_transaction(self.user, -transaction_id, campaign_id, amount)
        bid.refund.assert_called_once_with(amount)
        self.assertEqual(return_value, (True, None))

        with patch("r2.lib.authorize.interaction.api.refund_transaction") as refund:
            # Scenario: refund_transaction is successful
            bid.reset_mock()
            return_value = refund_transaction(self.user, transaction_id, campaign_id, amount)
            bid.refund.assert_called_once_with(amount)
            self.assertEqual(return_value, (True, None))

            # Scenario: refund_transaction raises TransactionError
            bid.reset_mock()
            refund.side_effect = TransactionError("")
            return_value = refund_transaction(self.user, transaction_id, campaign_id, amount)
            self.assertEqual(return_value[0], False)
Example #20
0
    def testCall(self):
        mock = Mock()
        self.assertTrue(isinstance(mock.return_value, Mock), "Default return_value should be a Mock")

        result = mock()
        self.assertEqual(mock(), result, "different result from consecutive calls")
        mock.reset_mock()

        ret_val = mock(sentinel.Arg)
        self.assertTrue(mock.called, "called not set")
        self.assertEqual(mock.call_count, 1, "call_count incoreect")
        self.assertEqual(mock.call_args, ((sentinel.Arg,), {}), "call_args not set")
        self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})], "call_args_list not initialised correctly")

        mock.return_value = sentinel.ReturnValue
        ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
        self.assertEqual(ret_val, sentinel.ReturnValue, "incorrect return value")

        self.assertEqual(mock.call_count, 2, "call_count incorrect")
        self.assertEqual(mock.call_args, ((sentinel.Arg,), {"key": sentinel.KeyArg}), "call_args not set")
        self.assertEqual(
            mock.call_args_list,
            [((sentinel.Arg,), {}), ((sentinel.Arg,), {"key": sentinel.KeyArg})],
            "call_args_list not set",
        )
Example #21
0
    def test_canInstall(self, mock_canInstall):
        posix = self.get_obj()
        entry = lxml.etree.Element("Path", name="test", type="file")

        # first, test superclass canInstall failure
        mock_canInstall.return_value = False
        self.assertFalse(posix.canInstall(entry))
        mock_canInstall.assert_called_with(posix, entry)

        # next, test fully_specified failure
        posix.logger.error.reset_mock()
        mock_canInstall.reset_mock()
        mock_canInstall.return_value = True
        mock_fully_spec = Mock()
        mock_fully_spec.return_value = False
        posix._handlers[entry.get("type")].fully_specified = mock_fully_spec
        self.assertFalse(posix.canInstall(entry))
        mock_canInstall.assert_called_with(posix, entry)
        mock_fully_spec.assert_called_with(entry)
        self.assertTrue(posix.logger.error.called)

        # finally, test success
        posix.logger.error.reset_mock()
        mock_canInstall.reset_mock()
        mock_fully_spec.reset_mock()
        mock_fully_spec.return_value = True
        self.assertTrue(posix.canInstall(entry))
        mock_canInstall.assert_called_with(posix, entry)
        mock_fully_spec.assert_called_with(entry)
        self.assertFalse(posix.logger.error.called)
Example #22
0
    def test_passphrase(self, mock_get_passphrases):
        pkc = self.get_obj()
        cfp = Mock()
        cfp.has_section.return_value = False
        cfp.has_option.return_value = False
        Bcfg2.Server.Plugins.Cfg.CfgPrivateKeyCreator.SETUP = Mock()
        Bcfg2.Server.Plugins.Cfg.CfgPrivateKeyCreator.SETUP.cfp = cfp

        self.assertIsNone(pkc.passphrase)
        cfp.has_section.assert_called_with("sshkeys")

        cfp.reset_mock()
        cfp.has_section.return_value = True
        self.assertIsNone(pkc.passphrase)
        cfp.has_section.assert_called_with("sshkeys")
        cfp.has_option.assert_called_with("sshkeys", "passphrase")

        cfp.reset_mock()
        cfp.get.return_value = "test"
        mock_get_passphrases.return_value = dict(test="foo", test2="bar")
        cfp.has_option.return_value = True
        self.assertEqual(pkc.passphrase, "foo")
        cfp.has_section.assert_called_with("sshkeys")
        cfp.has_option.assert_called_with("sshkeys", "passphrase")
        cfp.get.assert_called_with("sshkeys", "passphrase")
        mock_get_passphrases.assert_called_with(Bcfg2.Server.Plugins.Cfg.CfgPrivateKeyCreator.SETUP)
Example #23
0
    def test_diff(self, mock_time):
        ptool = self.get_obj()
        content1 = "line1\nline2"
        content2 = "line3"

        self.now = 1345640723

        def time_rv():
            self.now += 1
            return self.now

        mock_time.side_effect = time_rv

        rv = ["line1", "line2", "line3"]
        func = Mock()
        func.return_value = rv
        self.assertItemsEqual(ptool._diff(content1, content2, func), rv)
        func.assert_called_with(["line1", "line2"], ["line3"])

        func.reset_mock()
        mock_time.reset_mock()

        def time_rv():
            self.now += 5
            return self.now

        mock_time.side_effect = time_rv

        def slow_diff(content1, content2):
            for i in range(1, 10):
                yield "line%s" % i

        func.side_effect = slow_diff
        self.assertFalse(ptool._diff(content1, content2, func), rv)
        func.assert_called_with(["line1", "line2"], ["line3"])
Example #24
0
    def test_any_mock_calls_comparison_order(self):
        mock = Mock()
        d = datetime.now()

        class Foo(object):
            def __eq__(self, other):
                return False

            def __ne__(self, other):
                return True

        for d in datetime.now(), Foo():
            mock.reset_mock()

            mock(d, foo=d, bar=d)
            mock.method(d, zinga=d, alpha=d)
            mock().method(a1=d, z99=d)

            expected = [
                call(ANY, foo=ANY, bar=ANY),
                call.method(ANY, zinga=ANY, alpha=ANY),
                call(),
                call().method(a1=ANY, z99=ANY),
            ]
            self.assertEqual(expected, mock.mock_calls)
            self.assertEqual(mock.mock_calls, expected)
Example #25
0
    def test_creation(self):
        # Test the case where queue needs to create the topic.
        pubsub = Mock()
        topic = Mock()
        topic.exists.return_value = False
        pubsub.topic.return_value = topic

        q = Queue(pubsub)

        assert pubsub.topic.called
        assert topic.exists.called
        assert q.topic == topic

        sub = Mock()
        sub.exists.return_value = False

        # Test the case where it needs to create the subcription.
        with patch("gcloud.pubsub.Subscription") as SubscriptionMock:
            SubscriptionMock.return_value = sub
            rsub = q._get_or_create_subscription()

            assert rsub == sub
            assert SubscriptionMock.called_with("psq-default-shared", topic)
            assert sub.exists.called
            assert sub.create.called

        # Test case where subscription exists and it should re-use it.
        with patch("gcloud.pubsub.Subscription") as SubscriptionMock:
            sub.reset_mock()
            SubscriptionMock.return_value = sub
            sub.exists.return_value = True
            rsub = q._get_or_create_subscription()

            assert rsub == sub
            assert not sub.create.called
Example #26
0
def test_check_projects_skips_checks():
    project = Mock()
    check_project(project, skip_checks=["ignore_unpushed_commits"], ignore_unpushed_if_no_remotes=False)

    assert not project.check_unpushed_commits.called
    assert project.check_remotes.called
    assert project.check_uncommitted_changes.called
    assert project.check_git_stash.called
    assert call("LICENSE") in project.check_for_nonempty_file.call_args_list
    assert call("README") in project.check_for_nonempty_file.call_args_list

    project.reset_mock()
    check_project(project, skip_checks=["ignore_remotes"], ignore_unpushed_if_no_remotes=False)

    assert project.check_unpushed_commits.called
    assert not project.check_remotes.called
    assert project.check_uncommitted_changes.called
    assert project.check_git_stash.called
    assert call("LICENSE") in project.check_for_nonempty_file.call_args_list
    assert call("README") in project.check_for_nonempty_file.call_args_list

    project.reset_mock()
    check_project(project, skip_checks=["ignore_uncommitted_changes"], ignore_unpushed_if_no_remotes=False)

    assert project.check_unpushed_commits.called
    assert project.check_remotes.called
    assert not project.check_uncommitted_changes.called
    assert project.check_git_stash.called
    assert call("LICENSE") in project.check_for_nonempty_file.call_args_list
    assert call("README") in project.check_for_nonempty_file.call_args_list

    project.reset_mock()
    check_project(project, skip_checks=["ignore_stash"], ignore_unpushed_if_no_remotes=False)

    assert project.check_unpushed_commits.called
    assert project.check_remotes.called
    assert project.check_uncommitted_changes.called
    assert not project.check_git_stash.called
    assert call("LICENSE") in project.check_for_nonempty_file.call_args_list
    assert call("README") in project.check_for_nonempty_file.call_args_list

    project.reset_mock()
    check_project(project, skip_checks=["ignore_missing_license"], ignore_unpushed_if_no_remotes=False)

    assert project.check_unpushed_commits.called
    assert project.check_remotes.called
    assert project.check_uncommitted_changes.called
    assert project.check_git_stash.called
    assert call("LICENSE") not in project.check_for_nonempty_file.call_args_list
    assert call("README") in project.check_for_nonempty_file.call_args_list

    project.reset_mock()
    check_project(project, skip_checks=["ignore_missing_readme"], ignore_unpushed_if_no_remotes=False)

    assert project.check_unpushed_commits.called
    assert project.check_remotes.called
    assert project.check_uncommitted_changes.called
    assert project.check_git_stash.called
    assert call("LICENSE") in project.check_for_nonempty_file.call_args_list
    assert call("README") not in project.check_for_nonempty_file.call_args_list
Example #27
0
    def test_handles(self, mock_get_regex):
        match = Mock()
        mock_get_regex.return_value = Mock()
        mock_get_regex.return_value.match = match

        evt = Mock()
        evt.filename = "event.txt"

        if self.test_obj.__basenames__:
            match.return_value = False
            self.assertFalse(self.test_obj.handles(evt))
            mock_get_regex.assert_called_with([b for b in self.test_obj.__basenames__])
            print("match calls: %s" % match.call_args_list)
            print("expected: %s" % [call(evt.filename) for b in self.test_obj.__basenames__])
            match.assert_called_with(evt.filename)

            mock_get_regex.reset_mock()
            match.reset_mock()
            match.return_value = True
            self.assertTrue(self.test_obj.handles(evt))
            match.assert_called_with(evt.filename)
        else:
            match.return_value = False
            self.assertFalse(self.test_obj.handles(evt, basename=os.path.basename(self.path)))
            mock_get_regex.assert_called_with([os.path.basename(self.path)])
            match.assert_called_with(evt.filename)

            mock_get_regex.reset_mock()
            match.reset_mock()
            match.return_value = True
            self.assertTrue(self.test_obj.handles(evt, basename=os.path.basename(self.path)))
            mock_get_regex.assert_called_with([os.path.basename(self.path)])
            match.assert_called_with(evt.filename)
Example #28
0
def test_cached_parent():
    class HasParent(XBlock):
        pass

    runtime = Mock()
    block = HasParent(runtime, DictFieldData({}), Mock())

    # block has no parent yet, and we don't need to call the runtime to find
    # that out.
    assert_equals(block.get_parent(), None)
    assert not runtime.get_block.called

    # Set a parent id for the block.  Get the parent.  Now we have one, and we
    # used runtime.get_block to get it.
    block.parent = "some_parent_id"
    parent = block.get_parent()
    assert_not_equals(parent, None)
    assert runtime.get_block.called_with("some_parent_id")

    # Get the parent again.  It will be the same parent, and we didn't call the
    # runtime.
    runtime.reset_mock()
    parent2 = block.get_parent()
    assert parent2 is parent
    assert not runtime.get_block.called
Example #29
0
    def test_pool_restart_relaod_modules(self):
        consumer = Consumer()
        consumer.controller = _WC(app=current_app)
        consumer.controller.pool.restart = Mock()
        panel = self.create_panel(consumer=consumer)
        panel.app = self.app
        _import = panel.app.loader.import_from_cwd = Mock()
        _reload = Mock()

        current_app.conf.CELERYD_POOL_RESTARTS = True
        try:
            with patch.dict(sys.modules, {"foo": None}):
                panel.handle("pool_restart", {"modules": ["foo"], "reload": False, "reloader": _reload})

                self.assertTrue(consumer.controller.pool.restart.called)
                self.assertFalse(_reload.called)
                self.assertFalse(_import.called)

                _import.reset_mock()
                _reload.reset_mock()
                consumer.controller.pool.restart.reset_mock()

                panel.handle("pool_restart", {"modules": ["foo"], "reload": True, "reloader": _reload})

                self.assertTrue(consumer.controller.pool.restart.called)
                self.assertTrue(_reload.called)
                self.assertFalse(_import.called)
        finally:
            current_app.conf.CELERYD_POOL_RESTARTS = False
Example #30
0
    def test_new_mode_callback(self):
        """Create a Controller object, call on_new_mode_online method and
        check that the callback fires when set_composite_mode is called
        """
        self.setup_server()
        self.setup_controller()

        self.log.info("setting callback")
        test_cb = Mock(side_effect=self.quit_mainloop)
        self.controller.on_new_mode_online(test_cb)

        self.log.info("starting test-sources")
        self.setup_video_sources(count=2)

        self.log.info("waiting for initial callback with default-mode" "COMPOSITE_DUAL_EQUAL")
        self.run_mainloop(timeout=5)
        test_cb.assert_called_once_with(Controller.COMPOSITE_DUAL_EQUAL)
        test_cb.reset_mock()

        self.log.info("setting new composite mode COMPOSITE_NONE")
        assert self.controller.set_composite_mode(Controller.COMPOSITE_NONE)
        self.run_mainloop(timeout=5)

        self.log.info("waiting for callback with new mode COMPOSITE_NONE")
        test_cb.assert_called_once_with(Controller.COMPOSITE_NONE)