Python Selenium - Trying to fail a test when expected value is not found

Viewed 296

I have an application where users can create lists...once they create a list it will show up in a table on their homepage of the app. Only lists the user creates should display in the "created by" column of the table.

I'm trying to have the test fail and print if the expected name is not found.

 users_names = context.browser.find_elements_by_xpath("//tr//td[7]")

expected_name = "%s" % name

for name in expected_name:
    if name.text != expected_name:
        print("Failed\n", users_names)
1 Answers

If I understand your question correctly, you would like to verify that the only lists shown are in-fact created by the user. There's a few ways of doing this, and the example below can be improved.

  • We have our setUp() that's used to get everything ready before we start our test, profiles, preferences etc etc

  • Then test_show_only_user_created_lists() is the meat of our test, where we hold the functionality of what we're testing (you may have to place your remaining code within this section, if you had to do anything before checking the list)

  • Then we have our tearDown() which we use to finish off our remaining test, in this case we just close down our browser.

We could use our handy unit test library and asserting only after our loop has finished. But we must make sure to populate our 'expected_name' variable.

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class listTest(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_show_only_user_created_lists(self):
        driver = self.driver
        driver.get("http://yoursite.com")
        users_names = driver.find_elements_by_xpath("//tr//td[7]")

        testOutcome = 1

        for name in users_names:
            if name.text != expected_name:
              testOutcome = 0

        ### Assert ####
        self.assertTrue(testOutcome)

    def tearDown(self):
        self.driver.quit()

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

We can then run our test with the following command with indication of passes or failures:

python selenium-python-test.py
Related