2

I'm automating testing on iOS & Android devices with pytest and Appium. Consider the following:

some_locator: 
       {
        'iOS': ('MobileBy.ACCESSIBILITY_ID', 'some_id'),
        'Android': ('MobileBy.ID', 'another_id')
        }

def foo():
    bar = driver.find_element(some_locator)
    return bar.text

I want to run the script with either 'ios' or 'android' parameter from the command line to make function find_element use the corresponding tuple values. Also I know that I can do like this:

# conftest.py
def pytest_addoption(parser):
    parser.addoption("--platform", default="ios")

@pytest.fixture
def cmdopt(request):
    return request.config.getoption("--platform")

# some_file.py

some_locator: 
       {
        'iOS': ('MobileBy.ACCESSIBILITY_ID', 'some_id'),
        'Android': ('MobileBy.ID', 'another_id')
        }

def foo(platform):
    if platform == 'ios':
        bar = find_element(*some_locator['ios'])
    elif platform == 'android':
        bar = find_element(*some_locator['android'])
    return bar.text

but frankly speaking, I don't like it that way, because I'll have to add these if blocks in every method. Is there any convenient way to do it? My python is bad so I can't figure out the solution, please advice.

bvrch
  • 53
  • 5
  • You can write your code like this e.g.: def foo(platform): bar = find_element(*some_locator[platform]) return bar.text. Make sure you handle the KeyError exception wisely . – vikas0713 Jun 20 '18 at 14:02

2 Answers2

1

Use the platform variable directly

def foo(platform):
    bar = find_element(*some_locator[platform])
    return bar.text
mike.k
  • 3,277
  • 1
  • 12
  • 18
  • So obviuos! Thanks, don't know why I didn't figure it out myself – bvrch Jun 20 '18 at 14:12
  • @NikBarch because once you stare at your own code for too long, obvious things are missed, happens to me all the time. Take a break, come back to it, and you'll see much more. – mike.k Jun 20 '18 at 14:14
1

Can't you just use the platform variable to index some_locator directly? i.e.

def foo(platform):
    return find_element(*some_locator[platform]).text

Effectively the some_locator dictionary does the same job as the if-elif chain.

Joe Weston
  • 106
  • 5