# this function clears text from fields.
def clear_text(self, field):
switcher = {
'company': self.company_name_textbox_id,
'email': self.email_textbox_id,
'website': self.website_textbox_id,
'phone': self.phone_textbox_id,
}
switcher.get(self.driver.find_element_by_id(field).clear(), "Invalid field provided")
def test03_existing_company_validation(self):
company = CompanyPage(self.driver)
company.clear_text('company')
clear_text is not working. Am I doing it right? How to fix it?
Seems like your logic is going in the wrong order. You should probably be passing field to your switcher dictionary and then passing the value from that to find_element_by_id.
self.driver.find_element_by_id(switcher[field]).clear()
Related
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
Output:
{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}
I dont understand why the key and value first_name and last_name was placed at the last? aren't they supposed to be placed before location and field? because of positional arguments??
please help.
In case you'd want the positional arguments passed in to the function to come before the **kwargs passed in, you could use the dict(..., **kwargs) approach to build a new dict object:
def build_profile(first, last, **addl_info):
"""Build a dictionary containing everything we know about a user."""
user_info = {'first_name': first, 'last_name': last, **addl_info}
return user_info
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
Out:
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
I am pulling from a dictionary in Python. I have it setup like this:
entries = [
{'website': 'yahoo','username': 'jblumberg','password': 'sdkljfhwe'},
{'website': 'google','username': 'jblumberg1','password': 'CoIushujSetu'}
]
I am asking the user to give me a website so I can return the password as so:
def lookup_password(website):
if website in entries.keys():
encrypted_password = entries[website]
return password_encrypt(encrypted_password, -encryption_key)
pass
However that won't give me what I want. How do I set it up to give me the password value for the provided website?
First let's restructure your dict like this so that it's a dict with each key as a website, like it seems you treat it in your code:
entries = {
'yahoo': {'username': 'jblumberg', 'password': 'sdkljfhwe'},
'google': {'username': 'jblumberg1', 'passwprd': 'CoIushujSetu'}
}
Now a couple of changes to your original code gets us to what should be working:
if website in entries:
encrypted_password = entries[website]['password']
I should note that website in entries and website in entries.keys() do the same thing here.
There are multiples small problems in your conception of your data :
First entries is a list. Therefore you won't be able to call ".keys()"
Also when using
encrypted_password = entries[website]
this will store the whole dictionnary. Meaning that you would then be able to access the password via ['password']
encrypted_password = entries[website]['password']
To resume : if you change you data to look like this
entries = {
'yahoo':{
'username': 'jblumberg','password': 'sdkljfhwe'
},
'google':{
'username': 'jblumberg1','password': 'CoIushujSetu'
},
}
def lookup_password(website):
if website in entries:
encrypted_password = entries[website]['password']
return password_encrypt(encrypted_password, -encryption_key)
pass
But if you keep the same data, it will have to look like this:
def lookup_password(website):
for record in entries:
if record['website'] == website:
encrypted_password = record['website']
return password_encrypt(encrypted_password, -encryption_key)
pass
You could use another dictionary:
entries = [
{'yahoo':{'username': 'jblumberg','password': 'sdkljfhwe'},
{'google':{'username': 'jblumberg1','password': 'CoIushujSetu'}
]
Then the following would happen:
>> website = 'yahoo'
>> entries[website]
>> {'username': 'jblumberg','password': 'sdkljfhwe'}
so if you wanted the password:
>> entires[website]['password']
>> 'sdkljfhwe'
Try:
def lookup_password(website):
for entry in entries:
if entry['website'] == website:
return entry['password']
Output:
In[2]: lookup_password('google')
Out[2]: 'CoIushujSetu'
I have a dictionary for creating insert statements for a test I'm doing. The insert value for the description field needs to have the id of the current row, WHICH I DO NOT HAVE until I run the program. Also, that ID increments by 1 each time I insert, and the description for each insert has to have its corresponding row_num.
I want to load a dictionary of all the fields in the table in advance, so I can use the information in it to create the insert and alter statements for my test. I don't want to hardcode the test_value of a field in the code; I want what's supposed to be in it to be defined in the dictionary, and calculated at runtime. The dictionary is meant to be a template for what I want the value of the field to be.
I am getting the max id from the database, and adding 1 to it. That's the row number. I want the value that's being inserted for the description to be, for example, Row Num: {row_num} - Num Inserts {num_inserts} - Wait Time {wait_time}. I have the num_inserts and the wait_time from a config file. They are defined in advance.
I am getting NameError: name 'row_num' is not defined no matter how I've tried to define row_num in this dictionary. When I import the dictionary, the row_num isn't available yet, hence the error.
Here's a small snippet of my database fields dictionary (users is the table in this example):
all_fields_dict = {
'users':
{
'first_name': {
'db_field' : 'FirstName',
'datatype': 'varchar(50)',
'test_value': {utils.calc_field_value(['zfill', 'FirstName'])}, # another attempt that didn't work
'num_bool': False
},
'username': {
'db_field' : 'username',
'datatype': 'varchar(50)',
'test_value': f"user{utils.get_random_str(5)}", # this works, but it's a diff kind of calculation
'num_bool': False,
},
'description': {
'db_field' : 'description',
'datatype': 'text',
'test_value': f"{utils.get_desc_info(row_num)}", # one of my attempts - fails
'num_bool': False,
},
}
}
Among other things, I have tried:
{row_num}:
test_value: f"{row_num"}
calling a function that returns the row num:
def get_row_num()
return row_num
test_value: f"{utils.get_row_num()}
calling a function that CALLS the get_row_num function:
def get_desc_info():
row_num = get_row_num()
return f"Row Num: {row_num} - Wait Time: {wait_time} - Total Inserts: {num_inserts}"
test_value: f"{utils.get_desc_info()}"
I've even tried creating a function with a switcher that returns the get_row_num function, if 'rnum' is passed in as the test_value
def calc_field_value(type):
switcher = {
'rnum': get_row_num(),
etc
}
return switcher[type]
test_value: f"{utils.calc_field_value('rnum')
I've tried declaring it as global in just about every place I can think of.
I haven't tried eval, because of all the security warnings I've read about it.
Same thing, every single time.
Initialize test_field to some placeholder value, or simply don't set a value at all.
Then, later in the code when you do know the value, update the dict.
I am pretty new to using both SQLALCHEMY and the PYRAMID web framework. I am struggling with what might be a simple fix to some, but I haven't been able to figure it out. I have looked at some posts here on Stacks, but they don't quite answer my issue.
I have a many-to-many relationship in my database table. I am trying to return an object (categories) from the parent table assessment. I am trying at the moment to: return {'name': assessment.name, 'text': assessment.text, 'user': assessment.user_id, 'video':assessment.video_id, 'categories': assessment.categories.assessment_category_link} but this doesn't work --> 'categories': assessment.categories.assessment_category_link
I am able to return all the objects except categories. Below is the relevant error and code.
TRACEBACK:
line 306, in get_assessment
return {'name': assessment.name, 'text': assessment.text, 'user': assessment.user_id, 'video':assessment.video_id, 'categories': assessment.categories.assessment_category_link}
AttributeError: 'InstrumentedList' object has no attribute 'assessment_category_link'
SQLALCHEMY TABLE/RELATIONSHIP:
# MANY-to-MANY
association_table = Table('assessment_category_link', Base.metadata,
Column('assessment_id', Integer, ForeignKey('assessments.assessment_id')),
Column('category_id', Integer, ForeignKey('categories.category_id')))
class Assessment(Base):
# column/entity code
categories = relationship('Category', secondary='assessment_category_link', backref='assessments')
def __init__(self, name, text, user, video, categories):
# CODE
self.categories = categories
The GET() method, specifically the return value that is throwing the error:
#view_config(route_name='assessment', request_method='GET', renderer='json')
def get_assessment(request):
with transaction.manager:
assessment_id = int(request.matchdict['id'])
assessment = api.retrieve_assessment(assessment_id)
if not assessment:
raise HTTPNotFound()
return {'name': assessment.name, 'text': assessment.text, 'user': assessment.user_id, 'video':assessment.video_id, 'categories': assessment.categories.assessment_category_link}
I am not sure what you are trying to achieve since assessment.categories would return a list of Category objects that you need to iterate over. It is logical for such a list not to have an attribute named assessment_category_link (as the exception tells you), and it is not clear to me why you would want to access the association object anyway!
The relationship with the secondary keyword argument is meant to hide this complexity away so that assessment.categories would transparently return the list that you're after.
you can represent the categories list as you like, a suggestion for your case:
{...., 'categories': ', '.join([str(i) for i in assessment.categories])}
The answer above was very close, but the working code is:
{...., 'categories': ','.join([str(i) for i in assessment.categories])}
As suggested by similar Stack question/answer to the same issue: TypeError: sequence item 0: expected string, int found
How do I use Django test client.post to test a form that has a ModelChoiceField? How should the data dictionary passed to the post method be written? The way I am doing does not select any value at all.
I have a form with the following field:
country = forms.ModelChoiceField(
label="PaĆs",
queryset=Country.objects.all().order_by('name'),
required=True,
widget=forms.Select(attrs={
'onchange': "Dajaxice.party.update_country(Dajax.process, {'option':this.value})"
},
)
I also have the following test case:
def test_party_profile_sucessfully_saved(self):
self.client.login(username='Party1', password='BadMotherF')
response = self.client.post(reverse('party'), data={'slx_legal_type': '1', 'city': 'Belo Horizonte', 'country': '32',
'mobile': '+55-31-55555555', 'name': 'Roberto Vasconcelos Novaes',
'phone': '+55-31-55555555', 'slx_cnpj': '', 'slx_cpf': '056846515',
'slx_ie': '', 'slx_im': '', 'slx_rg': 'MG9084545', 'street':
'Rua Palmira, 656 - 502', 'streetbis': 'Serra', 'subdivision': '520',
'zip': '30220110'},
follow=True)
self.assertContains(response, 'Succesfully Saved!')
This form works all right. But when I test it using the aforementioned test case, the choice passed as data for the Model Choice Field (Country) does not get chosen. I have tried to pass the value (32) and the name of the country ('Brasil') or whatever.
I guess you need to pass the ID of the country or the model instance.
If you have a country 'Brazil' with id 32 you can pass in
{....
'country' : 32
....}
or
you can first get the country by using
country = Country.objects.get(id=32)
{....
'country': country
....}
I myself encountered such a problem when solving the problem. When specifying specific attributes, for example, <ModelName>.objects.get(<attr>='<...>').<something> when running django test, no post submit is formed and <ModelName>.objects.count() remains unchanged. In a practical way, I noticed that ChoiceField in the POST works only if you specify the id of the required <ModelName>.objects. But I passed the id as '32'. Therefore, it seems to me that the problem is a little different, not that the wrong value for 'country' is passed.
P.S. I apologize in advance that with a separate answer, there is not enough reputation for commenting