我在硒Web测试套件中使用python gflags模块时遇到问题。
我基本上遵循gflags github repo中的示例的方式。我通过DEFINE_string定义的新标志正在工作。但是默认的--help无效。

这是我的代码:

#!/usr/bin/env python
import datetime
import gflags
import sys
import time
import os
import glob
import unittest
from selenium import webdriver
from pageobject.contact_us_page import ContactUsPage
from pageobject.utility import SendEmailNotification
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

FLAGS = gflags.FLAGS
gflags.DEFINE_string('sender_addr', '', 'The Sender of email notification')
gflags.DEFINE_list('receivers_addr', '', 'The list of receivers')
gflags.DEFINE_string('sender_password', '', 'The password of sender email box')


class TestContactUsPage(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.driver = webdriver.Chrome('../chromedriver')
        cls.cu_page = ContactUsPage(cls.driver)

    @classmethod
    def tearDownClass(cls):
        cls.driver.close()

    def tally(self):
        return len(self._resultForDoCleanups.errors) + len(self._resultForDoCleanups.failures)

    def setUp(self):
        self.errors_and_failures = self.tally()

    def tearDown(self):

        # if sys.exc_info()[0]:
        #     message = 'Test fails with expection: %s' % sys.exc_info()[1]
        #     subject = 'Test fails'
        #     utilityLib.SendEmailResult('[email protected]', '[email protected]',)
        if self.tally() > self.errors_and_failures:
            now = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
            self.cu_page.TakeScreenShot('error_' + now)

    def testStep01(self):
        self.cu_page.Open()
        time.sleep(3)
        title = self.driver.title
        self.assertEqual(title, 'Parkside Lending LLC')

    def testStep02(self):
        self.cu_page.GotoPage()
        title_element = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((
            By.XPATH, '//h1[contains(.,"Contact Us")]')))
        self.cu_page.TakeScreenShot('cupage')
        self.assertEqual(title_element.text, 'Contact Us')

    def testStep03(self):
        self.cu_page.FillContactForm()
        submit_button = self.driver.find_element_by_name('submit')
        submit_button.click()
        self.assertTrue(self.cu_page.SubmitVerification(), 'Contact Form submission Fails, Please check out the '
                                                           'output and screen shot.')

if __name__ == '__main__':
    FLAGS(sys.argv)
    suite = unittest.TestLoader().loadTestsFromTestCase(TestContactUsPage)
    testResult = unittest.TextTestRunner(verbosity=2).run(suite)
    now = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
    error_file = max((glob.glob('error_*.png')), key=os.path.getmtime)
    sender = FLAGS.sender_addr
    receipts = FLAGS.receivers_addr
    password = FLAGS.sender_password
    with open('test.out', 'w') as f:

        if testResult.wasSuccessful():
            f.write('%s --- All %s test steps are passed, %s failures and %s errors' % (now, testResult.testsRun,
                    testResult.failures, testResult.errors))
        else:
            f.write('%s --- Test steps are failed.\n' % now)
            if len(testResult.failures):
                for failure in testResult.failures:
                    f.write('Test is failing at: %s\n' % failure[0])
                    f.write(failure[1])
            if len(testResult.errors):
                for error in testResult.errors:
                    f.write('Test has error at: %s\n' % error[0])
                    f.write(error[1])
    with open('test.out', 'r') as f:
        message = f.read()
        if testResult.wasSuccessful():
            subject = 'All Contact Us Page test steps are passed'
        else:
            subject = 'Contact Us Page Test steps are failed.'
            SendEmailNotification().SendEmailResult(
            sender, receipts, message, subject,
            ['cupage.png', error_file]
            , password)


如果我使用python contact_us_page_test.py --help来尝试获取帮助文本,则为以下输出。

python contact_us_page_test.py --help

Traceback (most recent call last):
  File "contact_us_page_test.py", line 70, in <module>
    FLAGS(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/gflags/flagvalues.py", line 708, in __call__
    name, value, suggestions=suggestions)
gflags.exceptions.UnrecognizedFlagError: Unknown command line flag 'help'

最佳答案

Python gflags不提供--help标志。但是,gflags.FLAGS对象将字符串化为完整的帮助。像这样使用它:

try:
  argv = FLAGS(sys.argv)
except gflags.FlagsError as e:
  print "%s\nUsage: %s ARGS\n%s" % (e, sys.argv[0], FLAGS)
  sys.exit(1)

10-08 12:47