简体   繁体   中英

Unit test Attribute error when importing a module and using it

The following is my directory for automation which contains three files, I am trying to run the unittest file test_page.py by importing Base.py. Base.py contains browser setup and tear down, it accepts user arguments ( browser, username and password) and logs in to the site. But when I run the test_page.py I get some errors. The problem is I need to get the browser instance from Base.py which I am unable to. I tried assigning the Browser().browser to a variable but that opens a new instance. I need to use the same instance of browser that Base.py is using.

    Automation
       __init__.py
         Base.py
         test_page.py

Base.py

        import sys
        import argparse
        from selenium import webdriver
        import datetime

        parser = argparse.ArgumentParser()
        parser.add_argument('browser', default='chrome', help='Types of browser:chrome, firefox, ie')
        parser.add_argument('username', help='This is the  username')
        parser.add_argument('password', help='This is the  password')
        args = parser.parse_args()

        setup_parameters = sys.argv[1:]


        class Browser(object):

            url = 'https:someurl'
            start_time = datetime.datetime.today()


            def __init__(self):
                self.username = setup_parameters[1]
                self.password = setup_parameters[2]
                if setup_parameters[0] == 'chrome':
                    self.browser = webdriver.Chrome('C:\Python37\chromedriver.exe')
                    print("Running tests on Chrome browser on %s" % self.start_time)


                elif setup_parameters[0] == 'ie':
                    self.browser = webdriver.Ie()
                    print("Running tests on Internet Explorer browser on %s" % self.start_time)


                elif setup_parameters[0] == 'firefox':
                    self.browser = webdriver.Firefox()
                    print("Running tests on Firefox browser on %s" % self.start_time)


                elif setup_parameters[0] == 'None':
                    print('No browser type specified.... continuing with the default browser')
                    self.browser = webdriver.Chrome()

            def login(self):
                # Method used to log in to the site
                self.browser.get(self.url)
                self.browser.implicitly_wait(10)
                self.browser.maximize_window()
                self.browser.find_element_by_id("Username").send_keys(self.username)
                self.browser.find_element_by_id("Password").send_keys(self.password)
                self.browser.find_element_by_id("btnLogin").click()

            def close(self):
                # Closing the browser window and terminating the test
                self.browser.close()
                print("Test(s) ended on {} at {}".format(setup_parameters[0], datetime.datetime.today()))


        if __name__ == '__main__':
            Browser().login()
            Browser().close()

test_page.py

    from unittest import TestSuite
    from unittest import TestCase
    from selenium import webdriver
    import time
    import sys
    import Base
    from Base import Browser

    class TestHomePage(unittest.TestCase):

        def setUp(self):
            self.driver = Browser().browser
            self.login = Browser().login()

        def test_links(self):
            self.driver.find_elements_by_link_text('click this link').click()

        def tearDown(self):
            self.close = Browser().close()


    if __name__ == '__main__':
        unittest.main()

    When I run test_page.py, I get the following error

    C:\Users\Projects\PortalAutomation>python test_page.py chrome username password

    EEE
    ======================================================================
    ERROR: chrome (unittest.loader._FailedTest)
    ----------------------------------------------------------------------
    AttributeError: module '__main__' has no attribute 'chrome'

    ======================================================================
    ERROR: 1EADMIN (unittest.loader._FailedTest)
    ----------------------------------------------------------------------
    AttributeError: module '__main__' has no attribute 'username'

    ======================================================================
    ERROR: password1 (unittest.loader._FailedTest)
    ----------------------------------------------------------------------
    AttributeError: module '__main__' has no attribute 'password'

    ----------------------------------------------------------------------
    Ran 3 tests in 0.000s

    FAILED (errors=3)

You're calling argparse in your Base.py file. Don't do that. Move these lines to another file, or wrap them in if __name__ == __main__ :

if __name__ == __main__
    parser = argparse.ArgumentParser()
    parser.add_argument('browser', default='chrome', help='Types of browser:chrome, firefox, ie')
    parser.add_argument('username', help='This is the  username')
    parser.add_argument('password', help='This is the  password')
    args = parser.parse_args()

If you don't put these lines in another file or inside of if __name__ == "__main__" , that section of code will be run upon import , not when calling test_page.py from the command line.

You also don't want to be using argparse in conjunction with unittest . Test Base.py using unittest , and setup the arguments you might need for the class in setUp . I recommend you pass in username and password into the constructor of your Browser object so you can easily write a test that uses a canned username/pw. You can do that like so:

class Browser(object):

    url = 'https:someurl'
    start_time = datetime.datetime.today()

    def __init__(self, driver, username, password):
        self.driver = driver
        self.username = username
        self.password = password
        if self.driver == 'chrome':
        ...

then you can write a test like this:

def setUp(self):
    browser_obj = Browser('chrome', 'some_username', 'some_password')
    self.driver = browser_obj.browser
    self.login = browser_obj.login()

def test_links(self):
    self.driver.find_elements_by_link_text('click this link').click()

def tearDown(self):
    browser_obj.close()

and then invoke your unit test with a simple python test_page.py (no arguments necessary).

When you run in prod, you can call Base.py with arguments, like Base.py chrome username password . Usually people don't test their argparse logic too thoroughly if at all: as it's not exactly quantum physics to pass in arguments to existing classes/function.

Note that your original test is making several browser objects instead of using the same one. You probably don't want this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM