際際滷

際際滷Share a Scribd company logo
Python UnitTest
覓伎 ろ 伎 讌? == 覓伎 襷れ伎 讌 覈襴
Test passes 
ろ碁ゼ 糾骸   蟆 豕 
 襦蠏碁覦 
Test fails Refactor 
ろ ろ碁ゼ  
貊 譟伎 蟇 覦 讌 レ
Basic Example 
import random 
import unittest 
class PizzaTest(unittest.TestCase): 
def setUp(self): 
self.seq = list(range(10)) 
def test_shuffle(self): 
unittest.TestCase襯 覦  
random.shuffle(self.seq) 
self.seq.sort() 
self.assertEqual(self.seq, list(range(10))) 
#襴ろ碁ゼ 覲蟆渚伎狩  覲蟆曙  TypeError 覦 
self.assertRaises(TypeError, random.shuffle, (1,2,3)) 
def test_choice(self): 
element = random.choice(self.seq) 
self.assertTrue(element in self.seq) 
def test_sample(self): 
with self.assertRaises(ValueError): 
#豌覯讌 朱誤郁 螳讌 襴ろ 螳 覲企 襷 襯 ロ ValueError螳 覦 
random.sample(self.seq, 20) 
for element in random.sample(self.seq, 5): 
self.assertTrue(element in self.seq) 
ろ  ろ 襷 襾殊 ろ 譴觜  
ろ   企 
test襦 伎  
$ python3 -m unittest tests.py
Test Discovery 
ろ碁ゼ 谿城 伎 貉れろ磯伎   . 
python -m unittest discover -s project_directory -p '*_test.py' 
-v, --verbose 
Verbose output 
-s, --start-directory directory 
Directory to start discovery (. default) 
-p, --pattern pattern 
Pattern to match test files (test*.py default) 
-t, --top-level-directory directory
Test Suite 
願  襦 ろ 蟲 蠍 
def suite(): 
suite = unittest.TestSuite() 
suite.addTest(PizzaTest('test_choice')) 
# suite.addTest(PizzaTest('test_sample')) 
return suite 
if __name__ == '__main__': 
unittest.TextTestRunner().run(suite())
Test Skip 
@unittest.skip("demonstrating skipping") 
def test_nothing(self): 
self.fail("shouldn't happen") 
@unittest.skipIf(mylib.__version__ < (1, 3), 
"not supported in this library version") 
def test_format(self): 
# Tests that work for only a certain version of the library. 
pass 
@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") 
def test_windows_support(self): 
# windows specific testing code 
pass
Python3.4 Assertions
assertEqual(a, b) 
a b螳 螳朱 ろ 炎概 蠏碁讌 朱 ろ
assertNotEqual(a, b) 
a b螳 螳讌 朱 ろ 炎概
assertTrue(x), assertFalse(x) 
 覩語 狩蟆 True願碓 False企 炎概
assertIs(a, b), assertIsNot(a, b) 
a b螳 螳 る 企 炎概蟇磯 覃 炎概
assertIsNone(x), assertIsNotNone(x) 
x螳 None 企 炎概願碓 None 覃 炎概
assertIn(a, b), assertNotIn(a, b) 
a螳 b  朱 炎概, a螳 b 讌 炎概
assertIsInstance(a, b), assertNotIsInstance(a, b) 
a = object 
b= class 
a螳 b 語ろ伎れ企 炎概, 覃 炎概
れ Exception ろ    
assertRaises(exc, fun, *args, **kwds) 
def order(): 
raise Exception 
def test_order(self): 
with self.assertRaises(Exception): 
order()
Exception 覃語 蠏 襷れ螳 覃 炎概 
assertRaisesRegex(exc, r, fun, *args, **kwds) 
def test_exception_message_regex(self): 
self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$", int, 'XYZ')
 讌襷  
https://docs.python.org/3.4/library/unittest.html#unittest.TestCase.assertAlmostEqual
Django assertion   
https://docs.djangoproject.com/en/dev/topics/testing/tools/#assertions
Mock 
れ 危襴貅伎 螳豌企ゼ 轟 覦朱  企 螳豌
3 襴危 覈 螳豌 襷れ 覲願鍵 
from unittest.mock import MagicMock 
class A(object): 
def test(self): 
pass 
class AuthTest(TestCase): 
def setUp(self): 
pass 
3 襴危襦 覈 螳豌  
def test_mock(self): 
inst = A() 
inst.method = MagicMock(return_value=3) 
self.assertEqual(inst.method(1), 3) 
inst.method.assert_called_with(1) 
襷 3 襴危讌 
ろ 
mock 螳豌願 語 讌
Raising an exception when a mock is called 
def test_side_effect(self): 
mock = Mock(side_effect=KeyError('Foo')) 
self.assertRaises(KeyError, mock)
patch 
mock.patch襯 覃 碁 殊企襴 襯 覦蠖  .
Fake client 
from django.test import Client 
from unittest.mock import MagicMock, Mock, patch 
def get_fake_request(status_code, content): 
m = Mock() 
m.status_code = status_code 
m.content = content 
def fake_get(url, *args, **kwargs): 
return m 
return fake_get 
class MockTest(TestCase): 
@patch('django.test.Client.get', get_fake_request(200, 'Fake')) 
def test_request(self): 
res = Client.get('http://fake.com') 
self.assertEqual(res.status_code, 200)
Django UnitTest
Request test 
def test_test_view(self): 
c = Client() 
res = c.get('/test_view/', {}) 
e = {'result': 1} 
self.assertJSONEqual(res.content.decode('utf-8'), json.dumps(e)) 
post, head, put, patch, delete, trace
login_required view 朱? 
@login_required 
def auth_view(request): 
return HttpResponse(status=200) 
def test_login_required_view(self): 
client = Client() 
res = client.login(username='debug', password='debug') 
res = client.get('/auth_view/') 
self.assertEqual(res.status_code, 200) 
Client.login  語 襦蠏語語 覃
Rainist, For Making Better Decision 
http://www.rainist.com 
豕覈蠏

More Related Content

Python Unittest

  • 2. 覓伎 ろ 伎 讌? == 覓伎 襷れ伎 讌 覈襴
  • 3. Test passes ろ碁ゼ 糾骸 蟆 豕 襦蠏碁覦 Test fails Refactor ろ ろ碁ゼ 貊 譟伎 蟇 覦 讌 レ
  • 4. Basic Example import random import unittest class PizzaTest(unittest.TestCase): def setUp(self): self.seq = list(range(10)) def test_shuffle(self): unittest.TestCase襯 覦 random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, list(range(10))) #襴ろ碁ゼ 覲蟆渚伎狩 覲蟆曙 TypeError 覦 self.assertRaises(TypeError, random.shuffle, (1,2,3)) def test_choice(self): element = random.choice(self.seq) self.assertTrue(element in self.seq) def test_sample(self): with self.assertRaises(ValueError): #豌覯讌 朱誤郁 螳讌 襴ろ 螳 覲企 襷 襯 ロ ValueError螳 覦 random.sample(self.seq, 20) for element in random.sample(self.seq, 5): self.assertTrue(element in self.seq) ろ ろ 襷 襾殊 ろ 譴觜 ろ 企 test襦 伎 $ python3 -m unittest tests.py
  • 5. Test Discovery ろ碁ゼ 谿城 伎 貉れろ磯伎 . python -m unittest discover -s project_directory -p '*_test.py' -v, --verbose Verbose output -s, --start-directory directory Directory to start discovery (. default) -p, --pattern pattern Pattern to match test files (test*.py default) -t, --top-level-directory directory
  • 6. Test Suite 願 襦 ろ 蟲 蠍 def suite(): suite = unittest.TestSuite() suite.addTest(PizzaTest('test_choice')) # suite.addTest(PizzaTest('test_sample')) return suite if __name__ == '__main__': unittest.TextTestRunner().run(suite())
  • 7. Test Skip @unittest.skip("demonstrating skipping") def test_nothing(self): self.fail("shouldn't happen") @unittest.skipIf(mylib.__version__ < (1, 3), "not supported in this library version") def test_format(self): # Tests that work for only a certain version of the library. pass @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") def test_windows_support(self): # windows specific testing code pass
  • 9. assertEqual(a, b) a b螳 螳朱 ろ 炎概 蠏碁讌 朱 ろ
  • 10. assertNotEqual(a, b) a b螳 螳讌 朱 ろ 炎概
  • 11. assertTrue(x), assertFalse(x) 覩語 狩蟆 True願碓 False企 炎概
  • 12. assertIs(a, b), assertIsNot(a, b) a b螳 螳 る 企 炎概蟇磯 覃 炎概
  • 13. assertIsNone(x), assertIsNotNone(x) x螳 None 企 炎概願碓 None 覃 炎概
  • 14. assertIn(a, b), assertNotIn(a, b) a螳 b 朱 炎概, a螳 b 讌 炎概
  • 15. assertIsInstance(a, b), assertNotIsInstance(a, b) a = object b= class a螳 b 語ろ伎れ企 炎概, 覃 炎概
  • 16. れ Exception ろ assertRaises(exc, fun, *args, **kwds) def order(): raise Exception def test_order(self): with self.assertRaises(Exception): order()
  • 17. Exception 覃語 蠏 襷れ螳 覃 炎概 assertRaisesRegex(exc, r, fun, *args, **kwds) def test_exception_message_regex(self): self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$", int, 'XYZ')
  • 18. 讌襷 https://docs.python.org/3.4/library/unittest.html#unittest.TestCase.assertAlmostEqual
  • 19. Django assertion https://docs.djangoproject.com/en/dev/topics/testing/tools/#assertions
  • 20. Mock れ 危襴貅伎 螳豌企ゼ 轟 覦朱 企 螳豌
  • 21. 3 襴危 覈 螳豌 襷れ 覲願鍵 from unittest.mock import MagicMock class A(object): def test(self): pass class AuthTest(TestCase): def setUp(self): pass 3 襴危襦 覈 螳豌 def test_mock(self): inst = A() inst.method = MagicMock(return_value=3) self.assertEqual(inst.method(1), 3) inst.method.assert_called_with(1) 襷 3 襴危讌 ろ mock 螳豌願 語 讌
  • 22. Raising an exception when a mock is called def test_side_effect(self): mock = Mock(side_effect=KeyError('Foo')) self.assertRaises(KeyError, mock)
  • 23. patch mock.patch襯 覃 碁 殊企襴 襯 覦蠖 .
  • 24. Fake client from django.test import Client from unittest.mock import MagicMock, Mock, patch def get_fake_request(status_code, content): m = Mock() m.status_code = status_code m.content = content def fake_get(url, *args, **kwargs): return m return fake_get class MockTest(TestCase): @patch('django.test.Client.get', get_fake_request(200, 'Fake')) def test_request(self): res = Client.get('http://fake.com') self.assertEqual(res.status_code, 200)
  • 26. Request test def test_test_view(self): c = Client() res = c.get('/test_view/', {}) e = {'result': 1} self.assertJSONEqual(res.content.decode('utf-8'), json.dumps(e)) post, head, put, patch, delete, trace
  • 27. login_required view 朱? @login_required def auth_view(request): return HttpResponse(status=200) def test_login_required_view(self): client = Client() res = client.login(username='debug', password='debug') res = client.get('/auth_view/') self.assertEqual(res.status_code, 200) Client.login 語 襦蠏語語 覃
  • 28. Rainist, For Making Better Decision http://www.rainist.com 豕覈蠏