示例#1
0
    def test_should_hijack_setup_and_teardown(self):
        lines = []

        def capture(line):
            lines.append(line)

        backup_setup = mocktest._setup
        backup_teardown = mocktest._teardown

        mocktest.mock._setup = mock_wrapper().with_action(lambda: capture("_setup")).mock
        mocktest.mock._teardown = mock_wrapper().with_action(lambda: capture("_teardown")).mock

        class Foo(mocktest.TestCase):
            def setUp(self):
                print "SETUP"
                capture("setup")

            def tearDown(self):
                capture("teardown")

            def test_main_is_called(self):
                capture("main")

        result = self.run_suite(Foo)
        self.assertTrue(result.wasSuccessful())
        self.assertEqual(lines, ["_setup", "setup", "main", "_teardown", "teardown"])

        mocktest.mock._setup = backup_setup
        mocktest.mock._teardown = backup_teardown
示例#2
0
	def test_frozen(self):
		wrapper = mock_wrapper().frozen().unfrozen()
		wrapper.mock.child_a = 'baz'
		self.assertEqual(wrapper.mock.child_a, 'baz')
		
		wrapper = mock_wrapper().frozen()
		self.assert_mock_is_frozen(wrapper)
示例#3
0
	def test_raising(self):
		# class
		wrapper = mock_wrapper().raising(SystemError)
		self.assertRaises(SystemError, wrapper.mock)
	
		# instance (with random extra args)
		wrapper = mock_wrapper().raising(SystemError("this simply will not do"))
		self.assertRaises(SystemError, lambda: wrapper.mock('a','b',foo='blah'))
示例#4
0
    def test_invalid_usage_after_teardown(self):
        mocktest._teardown()

        e = None
        try:
            mock_wrapper()
        except Exception, e_:
            e = e_
示例#5
0
	def test_default_return_value(self):
		wrapper = mock_wrapper()
		mock = wrapper.mock
		self.assertTrue(wrapper.return_value is mocktest.silentmock.DEFAULT)
		retval = mock()
		self.is_a_mock(retval)
		self.assertEqual(mock_wrapper(retval).name, 'return value for (unnamed mock)')
		self.is_a_mock(wrapper.return_value)
示例#6
0
    def test_should_ignore_with_description(self):
        callback = raw_mock()
        mock_wrapper(callback).is_expected.exactly(0).times

        @ignore("not done yet")
        def test_failure(self):
            callback("a")

        self.assert_(self.run_method(test_failure).wasSuccessful())
        assert_desc(self.output.called.with_("[[[ IGNORED ]]] (not done yet) ... "))
示例#7
0
    def test_ignore(self):
        callback = raw_mock()
        mock_wrapper(callback).is_expected.exactly(0).times

        @ignore
        def test_failure(self):
            callback("a")

        self.assert_(self.run_method(test_failure).wasSuccessful())
        assert_desc(self.output.called.with_("[[[ IGNORED ]]] ... "))
示例#8
0
    def test_pending(self):
        callback = raw_mock()

        @pending
        def test_failure(self):
            callback("a")
            raise RuntimeError, "something went wrong!"

        self.assert_(self.run_method(test_failure).wasSuccessful())
        assert_desc(self.output.called.with_("[[[ PENDING ]]] ... "))

        @pending("reason")
        def test_failure_with_reason(self):
            assert False
            callback("b")

        self.assert_(self.run_method(test_failure_with_reason).wasSuccessful())
        assert_desc(self.output.called.with_("[[[ PENDING ]]] (reason) ... "))

        @pending
        def test_successful_pending_test(self):
            assert True
            callback("c")

        self.assertEqual(self.run_method(test_successful_pending_test).wasSuccessful(), False)
        assert_desc(self.output.called.with_("test_successful_pending_test PASSED unexpectedly "))

        self.assertEqual(mock_wrapper(callback).called.exactly(2).times.get_calls(), [("a",), ("c",)])
示例#9
0
	def test_should_show_where_calls_were_made(self):
		wrapper = mock_wrapper()
		mock = wrapper.mock
		
		mock(1,2,345)
		print str(wrapper.called)
		self.assertTrue(re.search('// mock_test\.py:[0-9]+ +:: mock\(1,2,345\)', str(wrapper.called)))
示例#10
0
	def test_spec_class_in_constructor(self):
		wrapper = mock_wrapper().with_spec(self.SpecClass)
		self.assertEqual(wrapper._children.keys(), ['a','b'])
		self.is_a_mock(wrapper.mock.a())
		self.assert_mock_is_frozen(wrapper)
		
		self.assertRaises(AttributeError, lambda: wrapper.mock.__something__)
示例#11
0
	def setUp(self):
		
		self.actually_called = False
		def called(whoami, *args, **kwargs):
			print "ACTUALLY CALLED"
			whoami.actually_called = True
			return 'real_return'
		
		self.wrapper = mock_wrapper(called).returning('mock_return')
示例#12
0
	def test_with_children_should_set_return_values_and_freeze_mock(self):
		wrapper = mock_wrapper().with_children('blob', foo='bar', x=123)
		mock = wrapper.mock
		
		self.is_a_mock(mock.blob)
		self.assertEqual(mock.foo, 'bar')
		self.assertEqual(mock.x, 123)
		
		self.assertEqual(sorted(wrapper._children.keys()), ['blob', 'foo','x'])
		self.assert_mock_is_frozen(wrapper)
示例#13
0
 def test_expectation_formatting(self):
     self.assertEqual(
         repr(mock_wrapper().called.with_("foo", bar=1).twice()),
         "\n".join(
             [
                 'Mock "unnamed mock" did not match expectations:',
                 " expected exactly 2 calls with arguments equal to: 'foo', bar=1",
                 " received 0 calls",
             ]
         ),
     )
示例#14
0
	def test_constructor(self):
		mock = raw_mock()
		wrapper = mock_wrapper(mock)
		self.assertFalse(wrapper.called, "called not initialised correctly")
		self.assertTrue(wrapper.called.exactly(0), "call_count not initialised correctly")
	
		self.assertEquals(wrapper.call_list, [])
		self.assertEquals(wrapper._children, {})
		self.assertEquals(wrapper.action, None)
		self.assertEquals(wrapper.name, 'unnamed mock')
		wrapper.name = 'lil bobby mock'
示例#15
0
	def test_with_methods_should_set_return_values_and_freeze_mock(self):
		wrapper = mock_wrapper().with_methods('blob', '_blob', foo='bar', x=123, _blobx='underscore!')
		mock = wrapper.mock
		
		self.is_a_mock(mock.blob())
		self.is_a_mock(mock._blob())
		self.assertEqual(mock.foo(), 'bar')
		self.assertEqual(mock.x(), 123)
		self.assertEqual(mock._blobx(), 'underscore!')
		
		self.assertEqual(sorted(wrapper._children.keys()), ['_blob', '_blobx', 'blob', 'foo','x'])
		self.assert_mock_is_frozen(wrapper)
示例#16
0
    def test_should_do_expectations(self):
        f = mock_wrapper()
        f.expects("foo").once()
        f.mock.foo("a")
        f.mock.foo()
        self.assertRaises(
            AssertionError,
            mocktest._teardown,
            matching=re.compile('Mock "foo" .*expected exactly 1 calls.* received 2 calls.*', re.DOTALL),
        )

        # pretend we're in a new test (wipe the expected calls register)
        mocktest.mock.MockWrapper._all_expectations = []
示例#17
0
    def test_expect_should_work_on_a_mock_or_wrapper(self):
        wrapper = mock_wrapper()
        mock = wrapper.mock

        expect(mock.a).once()
        wrapper.expects("b").once()
        wrapper.child("c").is_expected.once()

        self.assertTrue(len(mocktest.mockwrapper.MockWrapper._all_expectations) == 3)

        mock.a()
        mock.b()
        mock.c()
示例#18
0
    def test_reality_formatting(self):
        m = mock_wrapper().named("ze_mock").mock
        m(1, 2, 3)
        m(foo="bar")
        m()
        m(1, foo=2)

        line_agnostic_repr = [
            re.sub("\.py:[0-9 ]{3} ", ".py:LINE ", line) for line in repr(mock_wrapper(m).called.once()).split("\n")
        ]

        expected_lines = [
            'Mock "ze_mock" did not match expectations:',
            " expected exactly 1 calls",
            " received 4 calls with arguments:",
            "  1:   1, 2, 3                  // mocktest_test.py:LINE :: m(1,2,3)",
            "  2:   foo='bar'                // mocktest_test.py:LINE :: m(foo='bar')",
            "  3:   No arguments             // mocktest_test.py:LINE :: m()",
            "  4:   1, foo=2                 // mocktest_test.py:LINE :: m(1, foo=2)",
        ]

        for got, expected in zip(line_agnostic_repr, expected_lines):
            self.assertEqual(got, expected)
示例#19
0
	def test_side_effect_is_called(self):
		wrapper = mock_wrapper()
		def effect():
			raise SystemError('kablooie')
		wrapper.action = effect
		
		self.assertRaises(SystemError, wrapper.mock)
		self.assertEquals(True, wrapper.called)
		
		wrapper = mock_wrapper()
		results = []
		def effect(n):
			results.append('call %s' % (n,))
		wrapper.action = effect
		
		wrapper.mock(1)
		self.assertEquals(results, ['call 1'])
		wrapper.mock(2)
		self.assertEquals(results, ['call 1','call 2'])
	
		sentinel = object()
		wrapper = mock_wrapper().with_action(sentinel)
		self.assertEquals(wrapper.action, sentinel)
示例#20
0
	def test_should_allow_setting_of_magic_methods(self):
		clean_wrapper = mock_wrapper().named('clean')
		modified_wrapper = mock_wrapper().named('modified').with_special(
			__repr__ = mock_wrapper().returning('my repr!').mock,
			__len__ = lambda x: 5)
			
		self.assertNotEqual(clean_wrapper.mock.__class__, modified_wrapper.mock.__class__)
		
		val = repr(modified_wrapper.mock)
		self.assertTrue(modified_wrapper.child('__repr__').called.once())
		self.assertEqual(val, 'my repr!')
	
		# can't override builtin mock magic methods
		self.assertRaises(
			AttributeError, lambda: modified_wrapper.with_special(__str__ = lambda x: 'foop'),
			message="cannot override SilentMock special method '__str__'")
	
		# can't assign non-magic ones
		self.assertRaises(ValueError, lambda: modified_wrapper.with_special(_len = lambda x: 5))
		
		self.assertEqual(len(modified_wrapper.mock), 5)
		self.assertRaises(AttributeError, lambda: clean_wrapper.mock.__len__)
		self.assertRaises(TypeError, lambda: len(clean_wrapper.mock))
		self.assertEqual(str(clean_wrapper.mock), 'clean')
示例#21
0
	def test_call_recording(self):
		wrapper = mock_wrapper()
		mock = wrapper.mock
		
		result = mock()
		self.assertEquals(mock(), result, "different result from consecutive calls")
		self.assertEquals(wrapper.call_list,
			[
				None, # called with nothing
				None, # (twice)
			])
	
		wrapper.reset()
		self.assertEquals(wrapper.call_list, [])
		
		mock('first_call')
		mock('second_call', 'arg2', call_=2)
		self.assertEquals(wrapper.call_list,
			[
				('first_call',),
				(('second_call','arg2'), {'call_':2}),
			])
示例#22
0
	def test_side_effect_return_val_used_even_when_it_is_none(self):
		def return_foo():
			print "i've been called!"
		wrapper = mock_wrapper().with_action(return_foo)
		self.assertEqual(wrapper.mock(), None)
示例#23
0
	def test_children_and_methods_can_coexist(self):
		wrapper = mock_wrapper().with_children(a='a').unfrozen().with_methods(b='b')
		self.assertEqual(wrapper.mock.a, 'a')
		self.assertEqual(wrapper.mock.b(), 'b')
示例#24
0
	def setUp(self):
		self.mock = mock_wrapper().named("bob")
示例#25
0
 def setUp(self):
     mocktest._setup()
     self.stderr = mock_wrapper().named("stderr")
     sys.stderr = self.stderr.mock
     self.output = mock_wrapper(sys.stderr.write)
     print "all expectations is %r" % (mocktest.mock.MockWrapper._all_expectations,)
示例#26
0
	def test_default_accessor_value(self):
		wrapper = mock_wrapper()
		mock = wrapper.mock
		retval = mock.child_a
		self.is_a_mock(retval)
		self.assertEqual(mock_wrapper(retval).name, 'child_a')
示例#27
0
 def test_a(self):
     foo = mocktest.mock_wrapper()
     foo.expects("blah").once()
示例#28
0
	def test_name_as_first_arg_in_constructor(self):
		wrapper = mock_wrapper(raw_mock("li'l mocky"))
		self.assertEqual(wrapper.name, "li'l mocky")
示例#29
0
	def test_return_value(self):
		wrapper = mock_wrapper().returning(None)
		self.assertEquals(None, wrapper.return_value)
		self.assertEquals(None, wrapper.mock())
示例#30
0
	def test_side_effect_return_used(self):
		def return_foo():
			return "foo"
		wrapper = mock_wrapper().with_action(return_foo)
		self.assertEqual(wrapper.mock(), 'foo')