SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler offline
UNIT TEST
davidx <mykingheaven@gmail.com>
import random
import unittest

class TestSequenceFunctions(unittest.TestCase):
    def setUp(self):
        self.seq = range(10)

    def test_shuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, range(10))

        # should raise an exception for an immutable sequence
        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):
            random.sample(self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assertTrue(element in self.seq)

if __name__ == '__main__':
    unittest.main()
:“
     ”
Test Fixture

Test Case

Test Suite

Test Runner
Test Fixture
Test Case
,       ,




    ,
,
,
Test Suite
Test Case
Test Runner
GUI
Python
python     module

unittest
(unittest.TestCase)

                setUp, tearDown



    suite        (
,           )
setUp


,   ,
tearDown
#!/usr/bin/python
#-*-coding:utf-8-*-
import httplib
import simplejson as json
from socket import socket
import struct, ssl, binascii
class APN(object):
   _conn = None
   def __init__(self, server='gateway.sandbox.push.apple.com', port=2195):
     self._server = server
     self._port = port
     self._conn = self._get_connection()
  def _get_connection(self):
    if not self._conn:
       s = socket()
       c = ssl.wrap_socket(s, ssl_version = ssl.PROTOCOL_SSLv3, certfile ='apn_mallsales.pem')
       c.connect((self._server, self._port))
       self._conn = c
    return self._conn
  def send_message(self, udid, message, badge=9):
    body = { 'aps': { 'alert': message, 'badge': badge } }
    payload = json.dumps(body)
    fmt = "!cH32sH%ds" % len(payload)
    command = 'x00'
    msg = struct.pack(fmt, command, 32, binascii.unhexlify(udid.replace(' ','')), len(payload), payload)
    self._get_connection().write(msg)
  def close(self):
    if self.__conn:
       self.__conn.close()
#!/usr/bin/python
#-*-coding:utf-8-*-
import unittest
from linkapn import APN
class TestApn(unittest.TestCase):
   def setUp(self):
     self.apn = APN()
     self.udid = '4d5479aa 5509cc3f 43ea363d 55406e98 13252481 063c3089 9c317478 736fa722'
  def test_one(self):
    message = 'test from david'
    badge = 9
    self.apn.send_message(self.udid, message, badge)
  def test_two(self):
    message = 'another test from david'
    badge = 9
    self.apn.send_message(self.udid, message, badge)
  def tearDown(self):
    print "closing connection"
if __name__ == '__main__':
   unittest.main()
Test Suite
def suite():
	

 suite = unittest.TestSuite()
	

 suite.addTest(TestApn('first_test'))
	

 suite.addTest(TestApn('second_test'))
	

 return suite

or:

def suite():
	

 tests = ['first_test', 'second_test']
	

 return unittest.TestSuite(map(TestApn, tests))
tdd -
Agile -
Questions?
http://www.hudong.com/wiki/%E5%8D
%95%E5%85%83%E6%B5%8B%E8%AF
%95

http://www.ibm.com/developerworks/cn/
linux/l-pyunit/index.html

Mais conteúdo relacionado

Mais procurados (20)

Hidden Gems of Ruby 1.9
Hidden Gems of Ruby 1.9Hidden Gems of Ruby 1.9
Hidden Gems of Ruby 1.9
 
Ssaw08 0624
Ssaw08 0624Ssaw08 0624
Ssaw08 0624
 
Php arduino
Php arduinoPhp arduino
Php arduino
 
MUST CS101 Lab11
MUST CS101 Lab11 MUST CS101 Lab11
MUST CS101 Lab11
 
Php 5.6
Php 5.6Php 5.6
Php 5.6
 
Android taipei 20160225 淺談closure
Android taipei 20160225   淺談closureAndroid taipei 20160225   淺談closure
Android taipei 20160225 淺談closure
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using Scala
 
Controlling Arduino With PHP
Controlling Arduino With PHPControlling Arduino With PHP
Controlling Arduino With PHP
 
Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinos
 
Namespaces
NamespacesNamespaces
Namespaces
 
Ext oo
Ext ooExt oo
Ext oo
 
14 - Exceptions
14 - Exceptions14 - Exceptions
14 - Exceptions
 
Mirage For Beginners
Mirage For BeginnersMirage For Beginners
Mirage For Beginners
 
ekb.py - Python VS ...
ekb.py - Python VS ...ekb.py - Python VS ...
ekb.py - Python VS ...
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
 
Advanced modulinos trial
Advanced modulinos trialAdvanced modulinos trial
Advanced modulinos trial
 
Promise is a Promise
Promise is a PromisePromise is a Promise
Promise is a Promise
 
ScalaFlavor4J
ScalaFlavor4JScalaFlavor4J
ScalaFlavor4J
 
Functuon
FunctuonFunctuon
Functuon
 
FSE 2008
FSE 2008FSE 2008
FSE 2008
 

Destaque

Destaque (6)

Desfalques contra o Santos.
Desfalques contra o Santos.Desfalques contra o Santos.
Desfalques contra o Santos.
 
Ahmed+Abd+Elfatah+
Ahmed+Abd+Elfatah+Ahmed+Abd+Elfatah+
Ahmed+Abd+Elfatah+
 
走上It之路
走上It之路走上It之路
走上It之路
 
Shell奇技淫巧
Shell奇技淫巧Shell奇技淫巧
Shell奇技淫巧
 
Guide project in uk
Guide project in ukGuide project in uk
Guide project in uk
 
Publications
PublicationsPublications
Publications
 

Semelhante a Unit test

Python Unit Test
Python Unit TestPython Unit Test
Python Unit TestDavid Xie
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My PatienceAdam Lowry
 
Qualidade levada a sério em Python - Emilio Simoni
Qualidade levada a sério em Python - Emilio SimoniQualidade levada a sério em Python - Emilio Simoni
Qualidade levada a sério em Python - Emilio SimoniGrupo de Testes Carioca
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и DjangoMoscowDjango
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con djangoTomás Henríquez
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
Isolated development in python
Isolated development in pythonIsolated development in python
Isolated development in pythonAndrés J. Díaz
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
2011 py con
2011 py con2011 py con
2011 py conEing Ong
 
用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用Felinx Lee
 
Automated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and ValidationAutomated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and ValidationBarbara Jones
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicGraham Dumpleton
 
Intro to Testing in Zope, Plone
Intro to Testing in Zope, PloneIntro to Testing in Zope, Plone
Intro to Testing in Zope, PloneQuintagroup
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockRobot Media
 
Unit tests and mocks
Unit tests and mocksUnit tests and mocks
Unit tests and mocksAyla Khan
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeLaurence Svekis ✔
 

Semelhante a Unit test (20)

Python Unit Test
Python Unit TestPython Unit Test
Python Unit Test
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
 
Qualidade levada a sério em Python - Emilio Simoni
Qualidade levada a sério em Python - Emilio SimoniQualidade levada a sério em Python - Emilio Simoni
Qualidade levada a sério em Python - Emilio Simoni
 
Django (Web Konferencia 2009)
Django (Web Konferencia 2009)Django (Web Konferencia 2009)
Django (Web Konferencia 2009)
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con django
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
Isolated development in python
Isolated development in pythonIsolated development in python
Isolated development in python
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
2011 py con
2011 py con2011 py con
2011 py con
 
用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用
 
Automated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and ValidationAutomated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and Validation
 
Batch processing Demo
Batch processing DemoBatch processing Demo
Batch processing Demo
 
svm classification
svm classificationsvm classification
svm classification
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
 
Intro to Testing in Zope, Plone
Intro to Testing in Zope, PloneIntro to Testing in Zope, Plone
Intro to Testing in Zope, Plone
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
Unit tests and mocks
Unit tests and mocksUnit tests and mocks
Unit tests and mocks
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
 

Último

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 

Último (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 

Unit test

  • 2. import random import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) def test_shuffle(self): # make sure the shuffled sequence does not lose any elements random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, range(10)) # should raise an exception for an immutable sequence 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): random.sample(self.seq, 20) for element in random.sample(self.seq, 5): self.assertTrue(element in self.seq) if __name__ == '__main__': unittest.main()
  • 3. :“
  • 4.
  • 5.
  • 6. Test Fixture Test Case Test Suite Test Runner
  • 8.
  • 10. , , ,
  • 11. ,
  • 12. ,
  • 16. GUI
  • 18. python module unittest
  • 19. (unittest.TestCase) setUp, tearDown suite ( , )
  • 20. setUp , ,
  • 22.
  • 23.
  • 24. #!/usr/bin/python #-*-coding:utf-8-*- import httplib import simplejson as json from socket import socket import struct, ssl, binascii class APN(object): _conn = None def __init__(self, server='gateway.sandbox.push.apple.com', port=2195): self._server = server self._port = port self._conn = self._get_connection() def _get_connection(self): if not self._conn: s = socket() c = ssl.wrap_socket(s, ssl_version = ssl.PROTOCOL_SSLv3, certfile ='apn_mallsales.pem') c.connect((self._server, self._port)) self._conn = c return self._conn def send_message(self, udid, message, badge=9): body = { 'aps': { 'alert': message, 'badge': badge } } payload = json.dumps(body) fmt = "!cH32sH%ds" % len(payload) command = 'x00' msg = struct.pack(fmt, command, 32, binascii.unhexlify(udid.replace(' ','')), len(payload), payload) self._get_connection().write(msg) def close(self): if self.__conn: self.__conn.close()
  • 25.
  • 26. #!/usr/bin/python #-*-coding:utf-8-*- import unittest from linkapn import APN class TestApn(unittest.TestCase): def setUp(self): self.apn = APN() self.udid = '4d5479aa 5509cc3f 43ea363d 55406e98 13252481 063c3089 9c317478 736fa722' def test_one(self): message = 'test from david' badge = 9 self.apn.send_message(self.udid, message, badge) def test_two(self): message = 'another test from david' badge = 9 self.apn.send_message(self.udid, message, badge) def tearDown(self): print "closing connection" if __name__ == '__main__': unittest.main()
  • 27.
  • 28.
  • 29.
  • 30.
  • 32. def suite(): suite = unittest.TestSuite() suite.addTest(TestApn('first_test')) suite.addTest(TestApn('second_test')) return suite or: def suite(): tests = ['first_test', 'second_test'] return unittest.TestSuite(map(TestApn, tests))
  • 33.
  • 34. tdd -

Notas do Editor