Search code examples
javascriptpythondatatablegherkinpython-behave

Python: How do I translate testing data tables from Javascript to Python


I'm new to Python. I currently have this code in Javascript (using Cypress) but unfortunately, I had issues with the iframe using Firefox so we switched to Selenium (with Python) to run the test case. I tried to search for the equivalent of this for few hours already but no luck. What is the equivalent of this script to Python? I am writing in BDD as well. Not sure how to handle data tables in Python.

I used match case for Python but I got stuck when handling data tables with hashes() or forEach() in Python. Please help. :(

Javascript:

And (‘step title', (firstInput, dataTable)=>{
    switch (firstInput) {
        case 'First Case':
            dataTable.hashes().forEach(elem =>{
                if(elem.titleOfDataTable == 'First Data'){
                    <someActions>
                }else if(elem.titleOfDataTable == 'Second Data'){
                    <someActions>
                }else if(elem.titleOfDataTable == 'Third Data'){
                    <someActions>
                }else{
                    throw new Error(<someMessage>)
                }
            })
            break;

            default:
                <defaultActions>
        }
})

Solution

  • You could simply use if/elif/else statements and a for loop as such (assuming that elem is a dictionary/JSON):

    def test(first_input, data_table):
        if (first_input == 'First Case'):
            for elem in data_table.hashes():
                if elem['titleOfDataTable]' == 'First Data':
                    <some actions>
                elif elem['titleOfDataTable'] == 'Second Data':
                    <some other actions>
                elif elem['titleOfDataTable'] == 'Third Data':
                    <some more actions>
                else:
                    raise ValueError("Unknown title: " + elem['titleOfDataTable'])
         else:
             <default actions>
    
    And('step title', test)  # <- modify this line according to the Python API of your test application