python之测试

unittest

 

Test outcomes

Tests have 3 possible outcomes:

ok
The test passes.

FAIL
The test does not pass, and raises an AssertionError exception.

ERROR
The test raises an exception other than AssertionError.

 

 

Asserting Truth

class TruthTest(unittest.TestCase):

    def test_fail_unless(self):
        self.failUnless(True)

    def test_assert_true(self):
        self.assertTrue(True)

    def test_fail_if(self):
        self.failIf(False)

    def test_assert_fail(self):
        self.assertFalse(False)

 

Testing Equality

class EqualityTest(unittest.TestCase):

    def test_equal(self):
        self.failUnlessEqual(1, 3-2)

    def test_not_equal(self):
        self.failIfEqual(2, 3-2)

 

Almost Equal

class AlmostEqualTest(unittest.TestCase):

    def test_almost_equal(self):
        self.failUnlessAlmostEqual(1.1, 1.2, places=0)

    def test_not_almost_equal(self):
        self.failIfAlmostEqual(1.1, 1.2, places=1)

 

Testing for Exceptions

def raises_error(*args, **kwargs):
    print args, kwargs
    raise ValueError('Invalid value:' + str(args) + str(kwargs))

class ExceptionTest(unittest.TestCase):

    def test_fail_unless_raises(self):
        self.failUnlessRaises(ValueError, raises_error, 'a', b='c')

 

Test Fixtures

Fixtures are resources needed by a test.
For example, if you are writing several tests for the same class, those tests all need an instance of that class to use for testing.
Other test fixtures include database connections and temporary files.
TestCase includes a special hook to configure and clean up any fixtures needed by your tests.
To configure the fixtures, override setUp(). To clean up, override tearDown().

class FixturesTest(unittest.TestCase):

    def setUp(self):
        print 'In setUp'
        self.fixture = range(1, 10)

    def tearDown(self):
        print 'in tearDown'
        del self.fixture

    def test_fixtures(self):
        print 'in test'
        self.failUnlessEqual(self.fixture, range(1, 10))

 

 

 

 

Mocks

Mocking is primarily used in unit testing.

An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want to test you replace the other objects by mocks that simulate the behavior of the real objects. This is useful if the the real objects are impractical to incorporate into the unit test.

In short, mocking is creating objects that simulate the behavior of real objects.

 

Google    PyCon US 2014 Montreal  Ned Batchelder - Getting Started Testing

 

 

 

 2015-06-02

转载于:https://www.cnblogs.com/whuyt/p/4547604.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值