mjuopperi
mjuopperi

Reputation: 971

Python selenium send_keys switches input before finishing first string

I'm writing functional tests against Django's StaticLiveServerTestCase with selenium using the Firefox driver.

For some reason my send_keys is cut off in the middle and the rest sent to another field:

"user" in username field, "namepassword" in password field.
Password field's type set to "text" to show the problem.

Here is my test case that is very close to the example in Django documentation.

from django.contrib.auth import get_user_model
from django.contrib.staticfiles.testing import StaticLiveServerTestCase

from selenium.webdriver.firefox.webdriver import WebDriver

User = get_user_model()

class LoginSpec(StaticLiveServerTestCase):

    @classmethod
    def setUpClass(cls):
        super(LoginSpec, cls).setUpClass()
        cls.selenium = WebDriver()
        User.objects.create_user('username', '[email protected]', 'password')

    @classmethod
    def tearDownClass(cls):
        User.objects.all().delete()
        cls.selenium.quit()
        super(LoginSpec, cls).tearDownClass()

    def test_login_with_valid_credentials(self):
        self.selenium.get('%s%s' % (self.live_server_url,  "/login"))

        username = self.selenium.find_element_by_name("username")
        username.send_keys("username")
        password = self.selenium.find_element_by_name("password")
        password.send_keys("password")
        ...

Upvotes: 2

Views: 569

Answers (2)

J4FFLE
J4FFLE

Reputation: 182

I think the real issue is that selenium continues to the next step in the code before it can finish typing out the send_keys() and it seems unrelated to whether it sees a character as a control character or not. It seems to cut it off before I finish if I have more than one or two characters that I'm trying to send, in my case "HPQ" was being submitted as "HP" or "H". Sending the keys one at a time did the trick for me. Thanks @Daniel for the suggestion.

for c in str_to_send:
    element.send_keys(c)

Upvotes: 1

Daniel
Daniel

Reputation: 2459

It looks like (for some reason) something is interpreting the "r" in "username" as a control character (moving focus to the next field), rather than as a regular character.

Two possible workarounds: you could clear() the element before calling send_keys and/or send the letters in your strings one at a time:

def test_login_with_valid_credentials(self):
    self.selenium.get('%s%s' % (self.live_server_url,  "/login"))

    username = self.selenium.find_element_by_name("username")
    username.clear()
    username.send_keys("username")
    # if clear() alone doesn't solve the problem, you might also try:
    # for x in list("username"):
    #     username.send_keys(x)
    password = self.selenium.find_element_by_name("password")
    password().clear
    password.send_keys("password")
    ...

Upvotes: 1

Related Questions