0
votes

I am new to Sellinium/Python and running few practice exercises. I want to run this program with internet Explorer, so at command prompt, I have given below command:

py.test -s -v mainTest.py --browser IE

When I run above command, it is showing error as:

ERROR: usage: py.test [options] [file_or_dir] [file_or_dir] [...] py.test: error: unrecognized arguments: --browser IE inifile: None`` rootdir: C:\Users\Radha.Maravajhala\PycharmProjects\RadhaSelenium\Tests

It is not identifying --browser arguement.

How can i run my program with a specific browser as an arguement in py.test command. Please help.

My Code:

mainTest.py

import os
import pytest
import unittest
from executionEngine.DriverScript import driverScript
from Utilities.Constants import Constants
from selenium import webdriver

class mainTest(driverScript):

def main(self):
    print("Main Test started...")
    print("Selenium webdriver Version: %s" % (webdriver.__version__))
    driver = driverScript('IE')
    driver.getbrowserInstance()

m = mainTest()
m.main()

DriverScript.py

import os
import pytest
import unittest

from pip._internal.configuration import Configuration
from selenium import webdriver
from selenium.webdriver import Ie
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.ie.options import Options
from selenium.webdriver.common.keys import Keys
#import selenium.webdriver
from Utilities import Constants

class driverScript():

def __init__(self,browser=None):

     if browser is None:
         browser = {}
     else:
         self.browser = browser
         print(self.browser)

     self.constants = Constants.Constants()

# Method to invoke browser
def getbrowserInstance(self):
    # create a new IE session
    print("Browser invoke started")

    if (self.browser=='IE'):

       capabilities = DesiredCapabilities.INTERNETEXPLORER
       print(capabilities["platform"])
       print(capabilities["browserName"])

       driver_location = self.constants.path_ie_driver

       os.environ["webdriver.ie.driver"] = driver_location

       ie_options = Options()
       ie_options.ignore_protected_mode_settings = True
      
       driver = webdriver.Ie(driver_location, options=ie_options)

       print("Browser is Invoked")
       driver.get("http://www.amazon.co.uk")
       driver.quit()

    elif (self.browser=='Chrome'):

       capabilities = DesiredCapabilities.CHROME
       print(capabilities["platform"])
       print(capabilities["browserName"])

       driver_location = self.constants.path_chrome_driver

       os.environ["webdriver.chrome.driver"] = driver_location

       driver = webdriver.Chrome(driver_location)

       print("Chrome Browser is Invoked")
       driver.get("http://www.amazon.co.uk")
       driver.quit()

Constants.py:

 class Constants():

 #Driver Locations
 path_ie_driver = "C:\\Selenium\\Drivers\\IEDriverServer.exe"
 path_chrome_driver = "C:\\Selenium\\Drivers\\chromedriver.exe"

confest.py

class Constants():

import pytest
from executionEngine.DriverScript import driverScript

# Send request variable to the fixture
# Browser value will be set from request.config.getoption (from command 
#                                                           prompt)
@pytest.yield_fixture(scope="class")
 def invoke_browser(request,browser):
     wdf = driverScript.getbrowserInstance(browser)
     driver = wdf.getbrowserInstance()

# Set class attribute and assign the variable
    if request.cls is not None:
       request.cls.driver = driver
       yield driver
 
driver.quit()

Create 2 parsers to get value from command prompt

def pytest_addoption(parser):
    parser.addoption("--browser")

Return the argument value

    @pytest.fixture(scope="session")
def browser(request):
    return request.config.getoption("--browser")
1
What you showed here is just a command. What's inside your python script? It is better if you post a sample of your script. It can help us to understand the issue in a better way. If you do not pass the argument then does your script run without issue? Let us know which documentation you are referring to. We will try to check it to find how to implement it correctly. - Deepak-MSFT
Thanks for your response Deepak ji. I have updated the call with my code. Please have a look. - murthymrk
I can see that you are passing the path of the IE driver in your code. After that, you do not need to pass the browser as an argument because of which driver you used in your code. It will launch that specific browser. Did you got any error while executing the python script without any argument? - Deepak-MSFT
Deepak ji, without argument, script is running fine and the site is opened in IE, as expected. However, I am planning to expand the script with Chrome and Edge. When I extend with these two browsers, I may need to choose a specific browser to run from command prompt. Thats why I am trying to pass browser as parameter and see how it works. Script is fine with single browser. But when i extend it with Chrome and Edge, how can I manage it? Thats why I am trying to pass it as argument. Please guide me how handle with multiple browsers where i can choose a specific browser at run time. - murthymrk

1 Answers

0
votes

Looks like you have some misunderstanding about passing the argument for a python script.

If you want to run your script with multiple browsers then you need to use the multiple web drivers in your code. In your above code, I can see that you are only using the IE web driver.

Another thing, I did not see where you check and use the argument that you passed from the command line.

I suggest you use the IF..elif condition and try to check the command line argument in it. Based on the value of the argument you can try to execute the code segment for any specific web browser.

Example:

#!/usr/bin/python

import sys, getopt

def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <inputfile> -o <outputfile>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print 'Input file is "', inputfile
   print 'Output file is "', outputfile

if __name__ == "__main__":
   main(sys.argv[1:])

Reference:

Python - Command Line Arguments