Search code examples
djangoseleniumdjango-testing

Test case data stays in Django development database Selenium


I have a simple form for registering new user. I wrote a test case for it. It looks as follows:

class AccountTestCase(LiveServerTestCase):

    def setUp(self):
        self.selenium = webdriver.Firefox()
        super(AccountTestCase, self).setUp()

    def tearDown(self):
        self.selenium.quit()
        super(AccountTestCase, self).tearDown()

    def test_register(self):
        selenium = self.selenium
        #Opening the link we want to test
        selenium.get('http://localhost:8000/register/')
        #find the form element
        first_name = selenium.find_element_by_id('id_first_name')
        last_name = selenium.find_element_by_id('id_last_name')
        username = selenium.find_element_by_id('id_username')
        email = selenium.find_element_by_id('id_email')
        password1 = selenium.find_element_by_id('id_password1')
        password2 = selenium.find_element_by_id('id_password2')

        submit = selenium.find_element_by_id('btn_signup')

        #Fill the form with data
        first_name.send_keys('abc')
        last_name.send_keys('abc')
        username.send_keys('abc')
        email.send_keys('[email protected]')
        password1.send_keys('abcabcabc')
        password2.send_keys('abcabcabc')

        #submitting the form
        submit.send_keys(Keys.RETURN)

        #check the returned result
        self.assertTrue('Success!' in selenium.page_source)

When I ran the test case for the first time it passed with flying colors, but on the second run it failed.

After little investigation I realized a user with credentials from test cases is already created in my database. Thus, when I ran test case for second time it failed to create a new user, as user with these details is already present. (I can see user from Django admin).

I believe this is not the expected behaviour of LiveServerTestCase(or any type of test case). In setup, a temporary database is created, test case is ran on it, and destroyed in tearDown phase.

I want to know if, this is the intended behavior? if not why this is happening ? How can I avoid doing it ?

I have not made any changes in settings.py which are related to selenium or testing (is there a flag or something that needs to be set?). Also, I need to keep the server running for this to work (is this normal?) .


Solution

  • As pointed by @Paulo Almeida :

    I was using a wrong url. The URL that I should be using is self.live_server_url . Since I was using http://localhost:8000/register/ It was expecting server to be running and creating records there.

    Thanks.