How to skip a method call during pytest - pytest-mock

Is there a way to skip calling inner method during pytests ? I am in need to skip validate() method when invoked from test_handle()
# module.py
def handle(request):
try:
token_validator = TokenValidator()
token_validator.**validate**(request['headers'].get("auth_token"))
except Exception:
return response(status=400)
try:
firstname = request['body'].get("first_nm")
except Exception:
return response(status=400)
return firstname
# pytest.py
def test_handle():
mock_event = dict(
headers={},
body={}
)
expected = "Somename"
result = module.handle(mock_event)
TestCase().assertEqual(expected, result)

Related

How to raise multiple ValidationError on Django Rest API?

Suppose I have three serializers in function and I want to check the validation. If any errors occur in the condition it Response error message at a time
My function:
def employ_create(request):
if request.method == 'POST':
employ_basic_info = data['basic_info']
employ_academic_info = data['academic_info']
employ_address = data['address']
employ_basic_info_serializer = EmployBasicInfoSerializers(data=employ_basic_info)
employ_academic_info_serializer = EmployAcademicInfoSerializers(data=employ_academic_info)
employ_address_serializer = EmployAddressInfoSerializers(data=employ_address)
if employ_basic_info_serializer.is_valid() and employ_academic_info_serializer.is_valid() and employ_address_serializer.is_valid():
employ_basic_info_serializer.save(employ_id=user_obj)
employ_academic_info_serializer.save(employ_id=user_obj)
employ_address_serializer.save(employ_id=user_obj)
return Response(status=rest_framework.status.HTTP_200_OK)
status_errors = {
'employ_basic_info_error':employ_basic_info_serializer.errors,
'employ_academic_info_error':employ_academic_info_serializer.errors,
'employ_address_error':employ_address_serializer.errors,
}
return Response({'stutase':status_errors}, status=rest_framework.status.HTTP_400_BAD_REQUEST)
I want to return employ_basic_info_serializer, employ_academic_info_serializer, employ_address_serializer errors if any errors occur. How can I do it? pls, help me...
Make sure to call the is_valid() method of each serializer object as,
def employ_create(request):
if request.method == 'POST':
employ_basic_info = data['basic_info']
employ_academic_info = data['academic_info']
employ_address = data['address']
employ_basic_info_serializer = EmployBasicInfoSerializers(
data=employ_basic_info)
employ_academic_info_serializer = EmployAcademicInfoSerializers(
data=employ_academic_info)
employ_address_serializer = EmployAddressInfoSerializers(data=employ_address)
is_valid_employ_basic_info_serializer = employ_basic_info_serializer.is_valid()
is_valid_employ_academic_info_serializer = employ_academic_info_serializer.is_valid()
is_valid_employ_address_serializer = employ_address_serializer.is_valid()
if (
is_valid_employ_academic_info_serializer and
is_valid_employ_basic_info_serializer and
is_valid_employ_address_serializer
):
employ_basic_info_serializer.save(employ_id=user_obj)
employ_academic_info_serializer.save(employ_id=user_obj)
employ_address_serializer.save(employ_id=user_obj)
return Response(status=rest_framework.status.HTTP_200_OK)
status_errors = {
'employ_basic_info_error': employ_basic_info_serializer.errors,
'employ_academic_info_error': employ_academic_info_serializer.errors,
'employ_address_error': employ_address_serializer.errors,
}
return Response(
{'stutase': status_errors},
status=rest_framework.status.HTTP_400_BAD_REQUEST
)

Django - passing a dict to form constructor and having it available globally in the class

I'm making a big mess trying to access the object that I passed from the view to the form.
class PrenotaForm(forms.ModelForm):
ORARI_CHOICES = ()
def __init__(self, *args, **kwargs):
DICT_ORARI_CHOICES = kwargs.pop('ORARI_CHOICES_NEW', {})
ORARI_CHOICES_NEW = []
for key, value in DICT_ORARI_CHOICES.items():
temp = [key,value]
ORARI_CHOICES_NEW.append(temp)
super(PrenotaForm, self).__init__(*args, **kwargs)
self.ORARI_CHOICES = ORARI_CHOICES_NEW
print("EEEEEEEEEEEEEEE" + str(self.ORARI_CHOICES))
print(ORARI_CHOICES)
I don't understand why inside the init the ORARI_CHOICES is populated as shown in console output:
EEEEEEEEEEEEEEE[['è uguale', 'Indifferente'], ['845', '08:45'], ['900', '09:00'], ['915', {'label': '09:15', 'disabled': 'disabled'}], ['930', {'label': '09:30', 'disabled': 'disabled'}], ['945', '09:45'], ['1000', '10:00'], ['1015', '10:15'], ['1030', '10:30'], ['1045', '10:45'], ['1100', '11:00'], ['1115', '11:15'], ['1130', '11:30'], ['1145', '11:45']]
but outside the init the ORARI_CHOICE is still empty:
print(ORARI_CHOICES)
since the print does not output nothing.
How can I override the ORARI_CHOICES = () and make it avalable globally in the class after every GET request performed in the view?
if request.method == 'GET':
size_gruppi = 30
print("gruppi size is : " + str(size_gruppi))
ORARI_CHOICES = (
('è uguale', "Indifferente"),
('845', "08:45"),
('900', "09:00"),
('915', "09:15"),
('930', "09:30"),
('945', "09:45"),
('1000', "10:00"),
('1015', "10:15"),
('1030', "10:30"),
('1045', "10:45"),
('1100', "11:00"),
('1115', "11:15"),
('1130', "11:30"),
('1145', "11:45"),
)
orari_map = map(list,ORARI_CHOICES)
orari_dict = dict(ORARI_CHOICES)
print(orari_dict)
counter = 0
for key in orari_map:
if key[0] != 'è uguale':
tot_in_fascia = sum(filter(None, Iscritto.objects.filter(fasce_orarie=key[0]).aggregate(Sum('size_adulti'), Sum('size_giovani')).values()))
print(tot_in_fascia)
if tot_in_fascia >= size_gruppi:
print("fascia " + key[0] + " è al completo ")
orari_dict.update({key[0]: {'label': key[1], 'disabled': 'disabled'}})
form = PrenotaForm(ORARI_CHOICES_NEW = orari_dict)
return render(request, "prenota.html", {'form': form, 'posti_liberi': posti_disponibili, 'giovani_iscritti': giovani_iscritti})
You should set ORARI_CHOICES as a class/static attribute.
class PrenotaForm(forms.ModelForm):
ORARI_CHOICES = []
def __init__(self, *args, **kwargs):
DICT_ORARI_CHOICES = kwargs.pop('ORARI_CHOICES_NEW', {})
# ORARI_CHOICES_NEW = []
for key, value in DICT_ORARI_CHOICES.items():
temp = [key,value]
self.__class__.ORARI_CHOICES.append(temp)
super(PrenotaForm, self).__init__(*args, **kwargs)
print("EEEEEEEEEEEEEEE" + str(self.ORARI_CHOICES))
Now, PrenotaForm.ORARI_CHOICES is already accessible. PrenotaForm.ORARI_CHOICES will always be accessible, but it returns empty list, untill you do not create instance of PrenotaForm. After instance creation of PrenotaForm, __init__ method will be called and data will be added inside ORARI_CHOICES.

Django Viewflow - Return Handler Response

Following is my flow:-
class APLWorkflow(Flow):
start = (
flow.StartFunction(function1)
.Next(this.request_quotes)
)
request_quotes = (
flow.Handler(function2)
.Next(this.move_package)
)
move_package = (
flow.Handler(function3)
.Next(this.shipment_create)
)
shipment_create = (
flow.Function(function4)
.Next(this.end)
)
end = flow.End()
Following are my util functions:-
def function1():
return 1
def function2():
return 2
def function3():
return 3
def function4():
return 4
The problem is when I start the flow, it runs perfectly well. However, the response returned is that of start node, not the last executed node.
Following is my code:-
activation.prepare()
response = APLWorkFLow.start.run(**some_kwargs)
activation.done() # stops the flow at `move_package`.
print(response) # prints 1, not 3.
How do I return the response of the last executed node, in this Handler (move_package)?

flask + wtforms nameerror

flask + wtforms
Hello, I have some problems with the transfer of data into a form
def edit_comment(n):
idlist = str(n)
if (r.exists('entries:%s' %idlist) != True):
return abort(404)
if 'user_id' not in session:
return abort(401)
if (g.user['group_access'] == '1'):
return abort(403)
form = EditForm(idlist)
return render_template('edit_comment.html',idlist = idlist, r = r, form = form)
...
class EditForm(Form):
edit_title = TextField("Title",validators = [Required()] ,default =r.hget('entries:%s' %idlist, 'title'))
edit_text = TextAreaField("Text",validators = [Required()],default =r.hget('entries:%s' %idlist, 'text'))
...
Traceback (most recent call last):
File "run.py", line 129, in <module>
class EditForm(Form):
File "run.py", line 130, in EditForm
edit_title = TextField("Title",validators = [Required()] ,default =r.hget('entries:%s' %idlist, 'title'))
NameError: name 'idlist' is not defined
here there are clear problems with data transmission. tried to pass through the constructor, but so far No results
You need to set the default value on the EditForm instance. Right now it' set at import time - clearly not what you want, even if the variable was defined. Actually, you don't even need the default field for it - just set it directly:
form = EditForm()
form.edit_title.data = r.hget('entries:%s' % idlist, 'title')
form.edit_text.data = r.hget('entries:%s' % idlist, 'text')
return render_template('edit_comment.html', idlist=idlist, r=r, form=form)
Note: Usually it's a good idea to have your view function to have a structure similar to this:
form = EditForm()
if form.validate_on_submit():
# do whatever should be done on submit, then redirect somewhere
return redirect(...)
elif request.method == 'GET':
# Populate the form with initial values
form.edit_title.data = ...
form.edit_text.data = ...
return render_template(..., form=form)
That way whatever the user entered is preserved in case the validation fails, but if he opens the form for the first time it's populated with whatever default data (e.g. the current values from your db) you want.

coercing to Unicode: need string or buffer, NoneType found

I am making an Ajax request into views as follows:
def all_json_models(request):
data = {}
try:
isp = request.GET['status']
present_isp = Priority.objects.filter(ispname = isp)
isp_count = MultiWAN.objects.all()
# data['latest_no_rules'] = latest_no_rules
#data['present_isp'] = present_isp
data['isp_count'] = isp_count
return HttpResponse(simplejson.dumps(data))
my models.py is like
class MultiWAN(models.Model):
isp_name = models.CharField(max_length=10)
description = models.TextField(null=True)
ip_address = models.IPAddressField(null=True)
subnet = models.IPAddressField(null=True)
gateway = models.IPAddressField(null=True)
nameserver = models.ForeignKey('NameServer')
weight = models.IntegerField(null=False)
interface = models.CharField(max_length=5)
def __unicode__(self):
"""
This function is to return the values we required.
Arguments:
- `self`:
"""
# return u'%s ' % (self.isp_name)
class NameServer(models.Model):
""" A Isp can have more than one nameserver so far we are declearing a seperate table
"""
name = models.IPAddressField(null=False)
class Priority(models.Model):
priority = models.IntegerField(null = True)
ispname = models.ForeignKey('MultiWAN')
rule = models.CharField(max_length=5,null=False)
From = models.IPAddressField(null=True)
To = models.IPAddressField(null=True)
def __unicode__(self):
return u'%s ' % (self.priority)
while making request i am getting the error:
"coercing to Unicode: need string or buffer, NoneType found"
What i am doing wrong here?
It's hard to tell without the full traceback (because it gives information about where in you code the exception is thrown).
The error message "coercing to Unicode: need string or buffer, NoneType found" means that, at some point, django tried to convert something to unicode and expected a string, but received None. This means that either you call a function passing None instead of a string, or one of you methods returns None instead of a string.
In the code you showed us, MultiWAN.__unicode__ seems ill-defined. Maybe the error stems from this ?