SlideShare une entreprise Scribd logo
1  sur  38
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Lohika_Odessa_TechTalks
 
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
Barbara Jones
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
varuntaliyan
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentation
nicobn
 

Tendances (20)

Py.test
Py.testPy.test
Py.test
 
Pytest - testing tips and useful plugins
Pytest - testing tips and useful pluginsPytest - testing tips and useful plugins
Pytest - testing tips and useful plugins
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
PHPUnit
PHPUnitPHPUnit
PHPUnit
 
Python Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit TestingPython Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit Testing
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
 
Phpunit testing
Phpunit testingPhpunit testing
Phpunit testing
 
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
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
 
Test your code like a pro - PHPUnit in practice
Test your code like a pro - PHPUnit in practiceTest your code like a pro - PHPUnit in practice
Test your code like a pro - PHPUnit in practice
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentation
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
Keep your repo clean
Keep your repo cleanKeep your repo clean
Keep your repo clean
 
Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit Testing
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to hero
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 

En vedette

[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics
[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics
[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics
Ho Chi Minh City Software Testing Club
 
Test Design with Action-based Testing Methodology - Ngo Hoang Minh
Test Design with Action-based Testing Methodology - Ngo Hoang MinhTest Design with Action-based Testing Methodology - Ngo Hoang Minh
Test Design with Action-based Testing Methodology - Ngo Hoang Minh
Ho Chi Minh City Software Testing Club
 
Analytical Risk-based and Specification-based Testing - Bui Duy Tam
Analytical Risk-based and Specification-based Testing - Bui Duy TamAnalytical Risk-based and Specification-based Testing - Bui Duy Tam
Analytical Risk-based and Specification-based Testing - Bui Duy Tam
Ho Chi Minh City Software Testing Club
 

En vedette (20)

Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with Python
 
Funcargs & other fun with pytest
Funcargs & other fun with pytestFuncargs & other fun with pytest
Funcargs & other fun with pytest
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit Testing
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With Pytest
 
2014/07/07 Software Testing - Truong Anh Hoang
2014/07/07 Software Testing - Truong Anh Hoang 2014/07/07 Software Testing - Truong Anh Hoang
2014/07/07 Software Testing - Truong Anh Hoang
 
Common Web UI Problems Transforming Manual to Automation
Common Web UI Problems Transforming Manual to Automation Common Web UI Problems Transforming Manual to Automation
Common Web UI Problems Transforming Manual to Automation
 
Web API Test Automation Using Frisby & Node.js
Web API Test Automation Using Frisby  & Node.jsWeb API Test Automation Using Frisby  & Node.js
Web API Test Automation Using Frisby & Node.js
 
Security testing-What can we do - Trinh Minh Hien
Security testing-What can we do - Trinh Minh HienSecurity testing-What can we do - Trinh Minh Hien
Security testing-What can we do - Trinh Minh Hien
 
[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics
[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics
[HCMC STC Jan 2015] Making IT Count – Agile Test Metrics
 
[HCMC STC Jan 2015] Practical Experiences In Test Automation
[HCMC STC Jan 2015] Practical Experiences In Test Automation[HCMC STC Jan 2015] Practical Experiences In Test Automation
[HCMC STC Jan 2015] Practical Experiences In Test Automation
 
A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...
A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...
A Novel Approach of Automation Test for Software Monitoring Solution - Tran S...
 
Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...
Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...
Deliver Fast, Break Nothing Via Effective Building Developer and Tester Colla...
 
[HCMC STC Jan 2015] FATS: A Framework For Automated Testing Scenarios
[HCMC STC Jan 2015] FATS: A Framework For Automated Testing Scenarios[HCMC STC Jan 2015] FATS: A Framework For Automated Testing Scenarios
[HCMC STC Jan 2015] FATS: A Framework For Automated Testing Scenarios
 
Agile Testing - Not Just Tester’s Story _ Dang Thanh Long
Agile Testing - Not Just Tester’s Story _ Dang Thanh LongAgile Testing - Not Just Tester’s Story _ Dang Thanh Long
Agile Testing - Not Just Tester’s Story _ Dang Thanh Long
 
Building an effective mobile testing strategy
Building an effective mobile testing strategyBuilding an effective mobile testing strategy
Building an effective mobile testing strategy
 
The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...
The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...
The New Agile Testing Quadrants: Bringing Skilled Testers and Developers Toge...
 
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
 
Test Design with Action-based Testing Methodology - Ngo Hoang Minh
Test Design with Action-based Testing Methodology - Ngo Hoang MinhTest Design with Action-based Testing Methodology - Ngo Hoang Minh
Test Design with Action-based Testing Methodology - Ngo Hoang Minh
 
Analytical Risk-based and Specification-based Testing - Bui Duy Tam
Analytical Risk-based and Specification-based Testing - Bui Duy TamAnalytical Risk-based and Specification-based Testing - Bui Duy Tam
Analytical Risk-based and Specification-based Testing - Bui Duy Tam
 
[HCMC STC Jan 2015] Risk-Based Software Testing Approaches
[HCMC STC Jan 2015] Risk-Based Software Testing Approaches[HCMC STC Jan 2015] Risk-Based Software Testing Approaches
[HCMC STC Jan 2015] Risk-Based Software Testing Approaches
 

Similaire à Python Unit Test

用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用
Felinx Lee
 
2011 py con
2011 py con2011 py con
2011 py con
Eing Ong
 
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
Graham Dumpleton
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
New Relic
 
Python concurrency: libraries overview
Python concurrency: libraries overviewPython concurrency: libraries overview
Python concurrency: libraries overview
Andrii Mishkovskyi
 

Similaire à Python Unit Test (20)

Unit test
Unit testUnit test
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
 
用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用
 
svm classification
svm classificationsvm classification
svm classification
 
2011 py con
2011 py con2011 py con
2011 py con
 
Intro to Testing in Zope, Plone
Intro to Testing in Zope, PloneIntro to Testing in Zope, Plone
Intro to Testing in Zope, Plone
 
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
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
 
Batch processing Demo
Batch processing DemoBatch processing Demo
Batch processing Demo
 
Python concurrency: libraries overview
Python concurrency: libraries overviewPython concurrency: libraries overview
Python concurrency: libraries overview
 
Detect Negative and Positive sentiment in user reviews using python word2vec ...
Detect Negative and Positive sentiment in user reviews using python word2vec ...Detect Negative and Positive sentiment in user reviews using python word2vec ...
Detect Negative and Positive sentiment in user reviews using python word2vec ...
 
Practical Celery
Practical CeleryPractical Celery
Practical Celery
 

Plus de David Xie (7)

走上It之路
走上It之路走上It之路
走上It之路
 
Shell奇技淫巧
Shell奇技淫巧Shell奇技淫巧
Shell奇技淫巧
 
Git version control
Git version controlGit version control
Git version control
 
云计算
云计算云计算
云计算
 
Hadoop
HadoopHadoop
Hadoop
 
沙龙升级
沙龙升级沙龙升级
沙龙升级
 
Git使用
Git使用Git使用
Git使用
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

Python 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. ,
  • 13. ,
  • 17. GUI
  • 19. python module unittest
  • 20. (unittest.TestCase) setUp, tearDown suite ( , )
  • 21. setUp , ,
  • 23.
  • 24.
  • 25. #!/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()
  • 26.
  • 27. #!/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()
  • 28.
  • 29.
  • 30.
  • 31.
  • 33. 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))
  • 34.
  • 35. tdd -