Python unittests in Jenkins?

前端 未结 6 595
长情又很酷
长情又很酷 2020-12-07 07:35

How do you get Jenkins to execute python unittest cases? Is it possible to JUnit style XML output from the builtin unittest package?

6条回答
  •  旧巷少年郎
    2020-12-07 07:59

    sample tests:

    tests.py:

    # tests.py
    
    import random
    try:
        import unittest2 as unittest
    except ImportError:
        import unittest
    
    class SimpleTest(unittest.TestCase):
        @unittest.skip("demonstrating skipping")
        def test_skipped(self):
            self.fail("shouldn't happen")
    
        def test_pass(self):
            self.assertEqual(10, 7 + 3)
    
        def test_fail(self):
            self.assertEqual(11, 7 + 3)
    

    JUnit with pytest

    run the tests with:

    py.test --junitxml results.xml tests.py
    

    results.xml:

    
    
        
            self = <tests.SimpleTest testMethod=test_fail>
    
        def test_fail(self):
    >       self.assertEqual(11, 7 + 3)
    E       AssertionError: 11 != 10
    
    tests.py:16: AssertionError
        
        
        
            /home/damien/test-env/lib/python2.6/site-packages/_pytest/unittest.py:119: Skipped: demonstrating skipping
        
    
    

    JUnit with nose

    run the tests with:

    nosetests --with-xunit
    

    nosetests.xml:

    
    
        
            
                
            
        
        
        
            
                
            
        
    
    

    JUnit with nose2

    You would need to use the nose2.plugins.junitxml plugin. You can configure nose2 with a config file like you would normally do, or with the --plugin command-line option.

    run the tests with:

    nose2 --plugin nose2.plugins.junitxml --junit-xml tests
    

    nose2-junit.xml:

    
      
        Traceback (most recent call last):
      File "/Users/damien/Work/test2/tests.py", line 18, in test_fail
        self.assertEqual(11, 7 + 3)
    AssertionError: 11 != 10
    
      
      
      
        
      
    
    

    JUnit with unittest-xml-reporting

    Append the following to tests.py

    if __name__ == '__main__':
        import xmlrunner
        unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))
    

    run the tests with:

    python tests.py
    

    test-reports/TEST-SimpleTest-20131001140629.xml:

    
    
        
        
            
         
        
        
            
        
        
        
        
        
    
    

提交回复
热议问题