Pytest Selenium elem.send_keys() causing TypeError: object of type 'NoneType' has no len() - selenium

I am trying to send data to a login textbox but when I use 'send_keys' I get an error..
def wait_for_element(selenium, selenium_locator, search_pattern, wait_seconds=10):
elem = None
wait = WebDriverWait(selenium, wait_seconds)
try:
if (selenium_locator.upper() == 'ID'):
elem = wait.until(
EC.visibility_of_element_located((By.ID, search_pattern))
)
except TimeoutException:
pass
return elem
userid=os.environ.get('userid')
wait_for_element(selenium, "ID", 'username')
assert elem is not None
elem.click()
time.sleep(3)
elem.send_keys(userid)
tests\util.py:123: in HTML5_login
elem.send_keys(userid)
..\selenium\webdriver\remote\webelement.py:478: in send_keys
{'text': "".join(keys_to_typing(value)),
value = (None,)
def keys_to_typing(value):
"""Processes the values that will be typed in the element."""
typing = []
for val in value:
if isinstance(val, Keys):
typing.append(val)
elif isinstance(val, int):
val = str(val)
for i in range(len(val)):
typing.append(val[i])
else:
for i in range(len(val)):
for i in range(len(val)):
E TypeError: object of type 'NoneType' has no len()
I have no clue why it is saying the element is of "NoneType" when I have it pass an assertion as well as click the element. I can even see it clicking the element when I run the test!

This error message...
elem.send_keys(userid) ..\selenium\webdriver\remote\webelement.py:478: in send_keys {'text': "".join(keys_to_typing(value)), value = (None,)
TypeError: object of type 'NoneType' has no len()
...implies that send_keys() method encountered an error when sending the contents of the variable userid.
Though you have tried to use the variable userid, I don't see the variable userid being declared anywhere within your code block. Hence you see the error:
TypeError: object of type 'NoneType' has no len()
Solution
Initialize the userid variable as:
userid = "Austin"
Now, execute your test.

Related

TypeError: scenario()

_ ERROR collecting tests/step_defs/test_service.py _____________________________________________________________
tests\step_defs\test_service.py:19: in
scenarios('../features/service.feature', example_converters=dict(phrase=str))
C:\Users\User.virtualenvs\tau-pytest-bdd-chapter-6-o7uEFzv0\lib\site-packages\pytest_bdd\scenario.py:327: in scenarios
#scenario(feature.filename, scenario_name, **kwargs)
E TypeError: scenario() got an unexpected keyword argument 'example_converters'
I have this error running a test
here is the code
Shared Variables
DUCKDUCKGO_API = 'https://api.duckduckgo.com/'
Scenarios
scenarios('../features/service.feature', example_converters=dict(phrase=str))
Given Steps
#given('the DuckDuckGo API is queried with ""', target_fixture='ddg_response')
def ddg_response(phrase):
params = {'q': phrase, 'format': 'json'}
response = requests.get(DUCKDUCKGO_API, params=params)
return response
Then Steps
#then('the response contains results for ""')
def ddg_response_contents(ddg_response, phrase):
# A more comprehensive test would check 'RelatedTopics' for matching phrases
assert phrase.lower() == ddg_response.json()['Heading'].lower()
#then(parsers.parse('the response status code is "{code:d}"'))
def ddg_response_code(ddg_response, code):
assert ddg_response.status_code == code

Keycloak. Put RealmRepresentation using Admin API gives "no String-argument constructor/factory method to deserialize from String value"

I want to change settings in my realm using the Admin API. The following GET code works
url = keycloak_url + '/admin/realms/master'
headers=...
requests.get(url, headers=headers)
However, when I try to do a PUT, I get a 500 error.
params = dict(registrationAllowed=True, rememberMe=True)
# both below don't work
x = requests.put(url, headers=headers, json=json.dumps(params))
x = requests.put(url, headers=headers, data=params)
The error in the server logs is:
Uncaught server error: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
construct instance of
org.keycloak.representations.idm.RealmRepresentation (although at
least one Creator exists): no String-argument constructor/factory
method to deserialize from String value ('{"registrationAllowed":
true, "rememberMe": true}') at [Source:
(io.undertow.servlet.spec.ServletInputStreamImpl); line: 1, column: 1]
at
com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
at
com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1342)
at
com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1031)
at
com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:371)
at
com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:323)
at
com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1366)
at
com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:171)
at
com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:161)
at
com.fasterxml.jackson.databind.ObjectReader._bind(ObjectReader.java:1574)
at
com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:965)
at
org.jboss.resteasy.plugins.providers.jackson.ResteasyJackson2Provider.readFrom(ResteasyJackson2Provider.java:135)
at
org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.readFrom(AbstractReaderInterceptorContext.java:66)
at
org.jboss.resteasy.core.interception.ServerReaderInterceptorContext.readFrom(ServerReaderInterceptorContext.java:61)
at
org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:56)
at
org.jboss.resteasy.security.doseta.DigitalVerificationInterceptor.aroundReadFrom(DigitalVerificationInterceptor.java:36)
at
...
Silly mistake on my side, it's
x = requests.put(url, headers=headers, json=params)

"on_server_role_update" TypeError Missing Argument

So... I dont know what to say, im going to be quick obviously
CODE:
#bot.event
async def on_server_role_update(role, before, after):
print("[" + (colored("{}".format(role.server), 'blue')) + "] " + (colored("Role Updated: {0} >> {1}".format(before, after), 'yellow')))
ERROR:
TypeError: on_server_role_update() missing 1 positional argument: 'after'
You see? I have the argument but it shows an error!
on_server_role_update should have exactly two arguments: a Role before and a Role after. Why did you think there was a third role argument?
#bot.event
async def on_server_role_update(before, after):
server_blue = colored(str(before.server), 'blue')
msg = "Role Updated: {0} >> {1}".format(before, after)
color_msg = colored(msg, 'yellow')
print("[{}] {}".format(server_blue, color_msg))

Getting an invalid token on an interpolated string sent from python/jinga2 backend

I'm sending a variable called apiID from a tornado/jinja2 python file to my vuejs template like this:
class SmartAPIUIHandler(BaseHandler):
def get(self, yourApiID):
doc_file = "smartapi-ui.html"
dashboard_template = templateEnv.get_template(doc_file)
dashboard_output = dashboard_template.render(apiID = yourApiID )
self.write(dashboard_output)
then in vuejs I'm interpolating the variable with no problem except it gives me an error
it says: Uncaught SyntaxError: Invalid or unexpected token
I checked on the python handler file and apipID is a string, so I don't see the problem. I'm quite new to python so maybe the answer is more obvious to one of you. I appreciate the help!!
Because of dashboard_output = dashboard_template.render(apiID = yourApiID ), you must have, in your template, something around the code:
this.apiID = {{ apiID }};
Due to the value being not a number but a string, add the 's:
this.apiID = '{{ apiID }}';

python3 - data type of input()

I need to assign a user-provided integer value to an object. My format is as follows:
object = input("Please enter an integer")
The following print tests...
print(type(object))
print(object)
...return <class 'str'> and '1'. Is there a way to set the data type of 'object' to the data type of the user's input value? IOW, such that if object=1, type(object)=int? I know I can set the data type of an input to int using the following:
object = int(input("Please enter an integer"))
In this case, if the user does not provide an int, the console throws a traceback error and the program crashes. I would prefer to test whether the object is in fact an int; if not, use my program to print an error statement and recursively throw the previous prompt.
while True:
try:
object = int(input("Please enter an integer"))
break
except ValueError:
print("Invalid input. Please try again")
print(type(object))
print(object)
You can always catch a "traceback error" and substitute your own error handling.
user_input = input("Please enter an integer")
try:
user_number = int(user_input)
except ValueError:
print("You didn't enter an integer!")