def test_method_wrappers(self):
        class Flask(flask.Flask, FlaskHTTPMethodsMixin):
            pass

        app = Flask(__name__)

        client = app.test_client()

        get_handler = Mock(return_value="", spec={})
        get_handler.__name__ = "get_handler"
        app.get("/foo")(get_handler)

        post_handler = Mock(return_value="", spec={})
        post_handler.__name__ = "post_handler"
        app.post("/foo")(post_handler)

        response = client.get("/foo")
        self.assertEquals(response.status_code, 200)
        get_handler.assert_called_once_with()

        response = client.post("/foo")
        self.assertEquals(response.status_code, 200)
        post_handler.assert_called_once_with()

        response = client.delete("/foo")
        self.assertEquals(response.status_code, 405)

        response = client.open("/foo", method="OPTIONS")
        self.assertItemsEqual(response.allow, ("POST", "HEAD", "OPTIONS", "GET"))
Example #2
0
    def test_function_cache(self, mkdirs, cache_file, is_expired, exists, yaml_load, yaml_dump):
        """ Test when the file doesn't exist, is forced or is expired """
        empty_test = Mock()
        empty_test.__name__ = "empty_test"
        empty_test.return_value = "from empty_test"

        is_expired.return_value = False
        exists.return_value = False
        cache_file.return_value = "test.yaml"
        yaml_load.return_value = "from cache"

        """ File doesn't exist, isn't expired, and isn't forced """
        with patch.object(cache, "open", create=True) as mock_open:
            result = cache.function_cache(empty_test, 5, False)

            mkdirs.assert_called_once_with(cache.BASE_DIR)
            mock_open.assert_called_once_with("test.yaml", "w")
            self.assertEqual(result, "from empty_test")

            exists.return_value = True

            """ Exists, isn't expired, forced """
            result = cache.function_cache(empty_test, 5, True)
            self.assertEqual(result, "from empty_test")

            """ Exists, but expired """
            is_expired.return_value = True

            result = cache.function_cache(empty_test, 5, False)
            self.assertEqual(result, "from empty_test")

            self.assertEqual(yaml_load.call_count, 0)
            self.assertEqual(empty_test.call_count, 3)
Example #3
0
    def test_wrap_memo(self):

        func = Mock(name="func")
        func.return_value = 42
        func.__name__ = "my_func"

        wrapped = memo(func)
        # First call gives a call count of 1
        self.assertEqual(wrapped(3), 42)
        self.assertEqual(func.call_count, 1)

        self.assertEqual(wrapped(3), 42)
        self.assertEqual(func.call_count, 1)

        self.assertEqual(wrapped(x=7, y=1, z=2), 42)
        self.assertEqual(func.call_count, 2)

        self.assertEqual(wrapped(y=1, x=7, z=2), 42)
        self.assertEqual(func.call_count, 2)

        self.assertEqual(wrapped(7, 1, 2), 42)  # doesn't matter, is is args or kwargs one call of function
        self.assertEqual(func.call_count, 2)  # arguments in cache should be the same

        self.assertEqual(wrapped(7, 2, 2), 42)
        self.assertEqual(func.call_count, 3)

        self.assertEqual(wrapped([7]), 42)
        self.assertEqual(func.call_count, 4)

        self.assertEqual(wrapped([7]), 42)  # cause list isn't hashable
        self.assertEqual(func.call_count, 5)
Example #4
0
    def test_apply_interval(self):
        t = timer2.Timer()
        try:
            t.schedule.enter_after = Mock()

            myfun = Mock()
            myfun.__name__ = "myfun"
            t.apply_interval(30, myfun)

            self.assertEqual(t.schedule.enter_after.call_count, 1)
            args1, _ = t.schedule.enter_after.call_args_list[0]
            msec1, tref1, _ = args1
            self.assertEqual(msec1, 30)
            tref1()

            self.assertEqual(t.schedule.enter_after.call_count, 2)
            args2, _ = t.schedule.enter_after.call_args_list[1]
            msec2, tref2, _ = args2
            self.assertEqual(msec2, 30)
            tref2.cancelled = True
            tref2()

            self.assertEqual(t.schedule.enter_after.call_count, 2)
        finally:
            t.stop()
 def setUp(self):
     self.testobject = Mock()
     self.testobject.logger = Mock()
     self.testobject.logger.debug = Mock()
     foobar = Mock()
     foobar.__name__ = "foobar"
     self.testobject.foobar = log_function_call(foobar)
     self.testobject.original_foobar = foobar
 def mock_task(self):
     raw_task = Mock()
     # functools.wraps requires the wrapped thing to have a __name__ attr,
     # which Mock()s don't usually have. Furthermore, Celery seems to do
     # some fancy behind-the-scenes caching on tasks' __name__, such that
     # tests pollute each other if the names aren't unique.
     raw_task.__name__ = str(uuid.uuid4())
     return raw_task
Example #7
0
 def test_multiple_ignored(self):
     cb = Mock()
     cb.__name__ = "something"
     old = len(amo_models._on_change_callbacks[Addon])
     Addon.on_change(cb)
     assert len(amo_models._on_change_callbacks[Addon]) == old + 1
     Addon.on_change(cb)
     assert len(amo_models._on_change_callbacks[Addon]) == old + 1
Example #8
0
 def test_multiple_ignored(self):
     cb = Mock()
     cb.__name__ = "something"
     old = len(models._on_change_callbacks[Webapp])
     Webapp.on_change(cb)
     eq_(len(models._on_change_callbacks[Webapp]), old + 1)
     Webapp.on_change(cb)
     eq_(len(models._on_change_callbacks[Webapp]), old + 1)
Example #9
0
 def test_multiple_ignored(self):
     cb = Mock()
     cb.__name__ = "something"
     old = len(amo.models._on_change_callbacks[Addon])
     Addon.on_change(cb)
     eq_(len(amo.models._on_change_callbacks[Addon]), old + 1)
     Addon.on_change(cb)
     eq_(len(amo.models._on_change_callbacks[Addon]), old + 1)
Example #10
0
 def test_decor_command(self):
     fake = Mock()
     fake.__name__ = "fake"
     tfunc = simplebot.command_for("test")(fake)
     self.assertEqual(tfunc.plug_name, "fake")
     self.assertTrue(hasattr(tfunc, "comm_test"))
     tfunc({}, dict(commands=Mock()), {}).comm_test()
     self.assertTrue(fake.called)
    def test_register_with_validators(self):
        mock_transform = Mock(return_value=None)
        mock_transform.__name__ = "mock_transform"
        mock_validator1 = Mock(return_value=None)
        mock_validator1.__name__ = "mock_validator1"
        mock_validator2 = Mock(return_value=None)
        mock_validator2.__name__ = "mock_validator2"

        validators = [mock_validator1, mock_validator2]

        registry.register("XX", mock_transform, validators)

        transform = registry.get("XX", "mock_transform")
        self.assertEqual(transform.validators, validators)

        transform()
        mock_transform.assert_called_once_with()
Example #12
0
 def test_run_command_check_output_return_tuple(self, mock_subprocess):
     check_output = Mock()
     check_output.__name__ = "check_output"
     check_output.return_value = "command output"
     mock_subprocess.check_output = check_output
     result = run_command(self.command)
     self.assertEqual(result[0], 0)
     self.assertEqual(result[1], check_output.return_value)
Example #13
0
 def test_handle_HTTP_403_Error(self):
     error = cb.praw.requests.HTTPError('403 Forbidden')
     mock = Mock(side_effect=error)
     mock.__name__ = str('mock')
     wrapped = cb.handle_praw_exceptions(max_attempts=2)(mock)
     with patch('__main__.cb.time.sleep') as mock_sleep:
         wrapped()
         assert not mock_sleep.called, ("Should not attempt retry "
                                        "after 403 error")
 def test_panelbusy(self):
     mock_func = Mock()
     mock_func.__name__ = "Mock"
     rightbusy = self.utilities.panelbusy("RightPanel")
     decorated_func = rightbusy(mock_func)
     decorated_func(1, 2, 3)
     self.xbmcgui.Window.return_value.setProperty.assert_called_once_with("RightPanel.IsBusy", "true")
     self.xbmcgui.Window.return_value.clearProperty.assert_called_once_with("RightPanel.IsBusy")
     mock_func.assert_called_with(1, 2, 3)
Example #15
0
 def test_handle_HTTP_403_Error(self):
     error = cb.praw.requests.HTTPError("403 Forbidden")
     mock = Mock(side_effect=error)
     mock.__name__ = str("mock")
     wrapped = cb.handle_praw_exceptions(max_attempts=2)(mock)
     with patch("{}.cb.time.sleep".format(__name__)) as mock_sleep:
         wrapped()
         # Should not attempt retry after 403 error
         self.assertFalse(mock_sleep.called)
Example #16
0
 def test_handle_generic_HTTP_Error(self):
     error = cb.praw.requests.HTTPError('')
     mock = Mock(side_effect=error)
     mock.__name__ = str('mock')
     wrapped = cb.handle_praw_exceptions()(mock)
     with patch('__main__.cb.time.sleep') as mock_sleep:
         try:
             wrapped()
         except cb.praw.requests.HTTPError:
             self.fail("HTTPError not properly handled")
 def test_xbmcbusy(self):
     mock_func = Mock()
     mock_func.__name__ = "Mock"
     self.xbmcgui.getCurrentWindowId = Mock(return_value=self.constants.WEATHER_WINDOW_ID)
     decorated_func = self.utilities.xbmcbusy(mock_func)
     decorated_func(1, 2, 3)
     self.assertEqual(2, len(self.xbmc.executebuiltin.call_args_list))
     self.assertEqual(self.xbmc.executebuiltin.call_args_list[0], (("ActivateWindow(busydialog)",),))
     self.assertEqual(self.xbmc.executebuiltin.call_args_list[1], (("Dialog.Close(busydialog)",),))
     mock_func.assert_called_with(1, 2, 3)
Example #18
0
 def test_handle_generic_HTTP_Error(self):
     error = cb.praw.errors.HTTPException("")
     mock = Mock(side_effect=error)
     mock.__name__ = str("mock")
     wrapped = cb.handle_api_exceptions()(mock)
     with patch("{}.cb.time.sleep".format(__name__)) as mock_sleep:
         try:
             wrapped()
         except cb.praw.errors.HTTPException:
             self.fail("HTTPError not properly handled")
Example #19
0
 def test_handle_API_Exceptions(self):
     error = cb.praw.errors.APIException('', '', {})
     mock = Mock(side_effect=error)
     mock.__name__ = str('mock')
     wrapped = cb.handle_praw_exceptions()(mock)
     with patch('__main__.cb.time.sleep') as mock_sleep:
         wrapped()
         try:
             wrapped()
         except cb.praw.requests.HTTPError:
             self.fail("APIException not properly handled")
Example #20
0
def local_store_keeps_separate_operations_for_different_arguments(pickle_dump, marshal_dump):
    changed_function = Mock(return_value=1)
    note_store = get_note_store()
    local_note_store = LocalNoteStore(note_store, changed_function)
    data_function = Mock()
    data_function.__name__ = "data_function"

    local_note_store.get_if_changed(data_function, 1)
    local_note_store.get_if_changed(data_function, 2)

    assert_equal(data_function.call_count, 2)
Example #21
0
 def test_decor_event(self):
     fake_check = "test"
     fake_func = Mock()
     fake_func.__name__ = "fake_func"
     fake_msg = Mock()
     fake_msg.command = fake_check
     tfunc = simplebot.event_for(fake_check)(fake_func)
     self.assertEqual(tfunc.plug_name, "fake_func")
     self.assertTrue(tfunc(1, 2, 3).evt_check(fake_msg))
     tfunc(1, 2, 3).evt_call(1)
     self.assertTrue(fake_func.called)
 def test_passing_arguments(self):
     self.request.user.is_authenticated = lambda: False
     func = Mock()
     func.__name__ = "Mock"
     func.return_value = 123
     with patch("pdc.apps.changeset.models.Changeset") as changeset:
         ret = self.cm.process_view(self.request, func, [1, 2, 3], {"arg": "val"})
         self.assertTrue(func.called)
         self.assertEqual(ret, 123)
         self.assertEqual(func.call_args, call(self.request, 1, 2, 3, arg="val"))
         self.assertEqual(changeset.mock_calls, [call(author=None), call().commit()])
Example #23
0
 def test_handle_Socket_Error(self):
     error = socket.error("[Errno 104] Connection reset by peer")
     error.errno = errno.ECONNRESET
     mock = Mock(side_effect=error)
     mock.__name__ = str("mock")
     wrapped = cb.handle_api_exceptions()(mock)
     with patch("{}.cb.time.sleep".format(__name__)) as mock_sleep:
         try:
             wrapped()
         except cb.praw.socket.SocketError:
             self.fail("SocketError not properly handled")
Example #24
0
 def test_handle_rate_limit_exceeded(self):
     error = cb.praw.errors.RateLimitExceeded("", "", "", response={"ratelimit": 9})
     mock = Mock(side_effect=error)
     mock.__name__ = str("mock")
     wrapped = cb.handle_api_exceptions()(mock)
     with patch("{}.cb.time.sleep".format(__name__)) as mock_sleep:
         try:
             wrapped()
         except cb.praw.errors.RateLimitExceeded:
             self.fail("RateLimitExceeded not properly handled")
     mock_sleep.assert_called_once_with(9)
Example #25
0
 def test_handle_API_Exceptions(self):
     error = cb.praw.errors.APIException("", "", {})
     mock = Mock(side_effect=error)
     mock.__name__ = str("mock")
     wrapped = cb.handle_praw_exceptions()(mock)
     with patch("{}.cb.time.sleep".format(__name__)) as mock_sleep:
         wrapped()
         try:
             wrapped()
         except cb.praw.requests.HTTPError:
             self.fail("APIException not properly handled")
 def test_no_commit_with_exception(self):
     self.request.user.is_authenticated = lambda: False
     func = Mock()
     func.__name__ = "Mock"
     func.side_effect = Exception("Boom!")
     changeset_logger.error = Mock()
     with patch("pdc.apps.changeset.models.Changeset") as changeset:
         self.assertRaises(Exception, self.cm.process_view, self.request, func, [], {})
         self.assertTrue(func.called)
         self.assertEqual(changeset.mock_calls, [call(author=None)])
         self.assertTrue(changeset_logger.error.called)
Example #27
0
 def test_handle_rate_limit_exceeded(self):
     error = cb.praw.errors.RateLimitExceeded('', '',
                                              response = {'ratelimit': 9})
     mock = Mock(side_effect=error)
     mock.__name__ = str('mock')
     wrapped = cb.handle_praw_exceptions()(mock)
     with patch('__main__.cb.time.sleep') as mock_sleep:
         try:
             wrapped()
         except cb.praw.errors.RateLimitExceeded:
             self.fail("RateLimitExceeded not properly handled")
     mock_sleep.assert_called_once_with(9)
Example #28
0
    def test_register_mutiple_resource_classes(self, mck):
        mockKlass = Mock(relationships=[], links=[])
        mockKlass.endpoint_dictionary = Mock(
            return_value=dict(
                first=[dict(route="/2/first", methods=["GET"])],
                second=[dict(route="/2/second", methods=["GET"], other="something", andanother="skdfmsdkf")],
            )
        )
        mockKlass.__name__ = "mockKlass2"
        self.dispatcher.register_resources(mockKlass, self.mockKlass)

        self.assertEqual(mck.call_count, 5)
 def test_ratelimit_no_method_match(self, mock_count):
     # we're testing to make sure that the method type doesn't match
     # the default POST
     self.request.method = "GET"
     # we dont need any parameters since
     # we're only testing that the rate limited doesn't get called
     wrapper = decorators.ratelimit()
     mock_view = Mock()
     mock_view.__name__ = "my mock view"
     wrapped_mock = wrapper(mock_view)
     wrapped_mock(self.request)
     self.assertFalse(mock_count.called)
Example #30
0
 def test_it_preserves_function_attributes(self):
     m = Mock()
     m.__doc__ = "my fn doc"
     m.__name__ = "my_func"
     m.__module__ = "super.awesome.module"
     m.func_name = "my_fn"
     m.func_code = Mock()
     subject = CallOnce(m)
     self.assertEqual(subject.__doc__, "my fn doc")
     self.assertEqual(subject.__name__, "my_func")
     self.assertEqual(subject.__module__, "super.awesome.module")
     self.assertEqual(subject.func_name, "my_fn")
     self.assertEqual(subject.func_code, m.func_code)