GraphQLTestCase: AttributeError: 'HttpResponse' object has no attribute 'COOKIES' - python-unittest

I would want to test my graphql mutation which should set a HTTP only cookie.
I use graphene-django GraphQTestCase
class CookieTest(GraphQLTestCase):
def test_set_cookie(self):
response = self.query(...) # This should return WSGIRequest
cookie = response.COOKIES.get('myCookie') # This line throws an attrib error
self.assertIsNotNone(cookie)
What is the problem?

For some reason response.cookies works, and returns http.cookies.SimpleCookie object:
So the correct way would be:
myCookie = response.cookies.get('myCookie')
myCookie.key # 'myCookie'
myCookie.value # <cookie-value>

Related

Unittest: How do I get the values that have been passed to a patch decorator?

Is there something (I can get the value of) in patch, test_posting, or mock_post that will tell me what values were passed to the original requests.post (or maybe there's some other way)?
The service function looks like this:
def post_to_api_server():
response = requests.post('{}{}'.format(API_SERVER_URL, SEARCH_PATH),
data=payload, headers=header_json, verify=False)
if response.ok:
return response
else:
return None
The test function looks like this:
#patch('requests.post')
def test_posting(mock_post):
mock_post.return_value = Mock(ok=True)
mock_post.return_value.json.return_value = my_test_json
response = post_to_api_server()
With a hint from #mrbean-bremmen, add something like this after the call to response = post_to_api_server():
args_tuple, kwargs_dict = mock_post.call_args
url = args_tuple[0]
if 'data' in kwargs_dict:
data = kwargs_dict['data']
if 'json' in kwargs_dict:
json = kwargs_dict['json']

Python 3.7: Detect name of property being accesed from class

So I am making a Class Which can dynamically return a property depending on whether or not a property was accessed on it. It also detects the name of the property when accessed by a class. my class code is as follows
class ConfigItem(object):
value: object
key:str
default: object
__name__:str = None
def __init__(self, default=None):
self.default: type(default) = default
self.value = default
self.key = "default_value"
def __get__(self, instance, owner):
if self.key:
self.value = os.environ.get(self.key,self.default)
else:
self.value = self.default
def __set_name__(self, owner, name):
self.__name__ = name
self.key = name
I want the code to have the following behavior:
when created like this:
a_test_key = ConfigItem('default_value')
a_test_key.key == 'a_test_key' #True
without having to pass the key into the constructor
and when accessed as so:
key_value = a_test_key
returns a_test_key.value
but when accessed any other way such as:
a_test_key.default
a_test_key.key
returns the respected values.
I think the solution has to do with the get(self, instance, owner) method, but I am unsure how to detect if a property has been accessed from ConfigItem.
Any takers on how to solve this problem?

Moq: How to ensure Verify() reports on non-matching parameters

I have the following unit test verification using Moq:
var mock = new Mock<IDoSomethingUseful>();
var sut = new Thingy(mock.Object);
sut.CallDoSomethingUseful();
mock.Verify(
somethingUseful => somethingUseful.Move(
It.Is<MyVector>(
myVector => myVector.x == 123)), Times.Once, "This fail message needs to be hard-coded with myVector.x was not equal to 123");
How can I get Verify() to tell me that the predicate match failed? The test runner only reports that the call failed so I need to rely on the hard-coded message.
Using Callback the invocation arguments can be accessed. See section Callbacks here.
In your case you could add an expected value for x to the test and get the actual value in Callback. Finally use an Assert to verify if expected and actual values equal where the message can be formated using both values. HTH
int expected_x_value = 123;
int actual_x_value = 0;
var mock = new Mock<IDoSomethingUseful>();
mock.Setup(m => m.Move(It.IsAny<MyVector>()))
.Callback<MyVector>(
(v) =>
{
actual_x_value = v.x;
}
);
var sut = new Thingy(mock.Object);
sut.CallDoSomethingUseful();
Assert.AreEqual(expected_x_value, actual_x_value,
string.Format("myVector.x was expected to be called with x = '{0}' but was '{1}'",
expected_x_value, actual_x_value));

Flask-WTF: Queries of FormFields in FieldList are none after validate_on_submit

I'm trying to generate dynamic forms using Flask-WTF to create a new product based on some templates. A product will have a list of required key-value pairs based on its type, as well as a list of parts required to build it. The current relevant code looks as follows:
forms.py:
class PartSelectionForm(Form):
selected_part = QuerySelectField('Part', get_label='serial', allow_blank=True)
part_type = StringField('Type')
slot = IntegerField('Slot')
required = BooleanField('Required')
def __init__(self, csrf_enabled=False, *args, **kwargs):
super(PartSelectionForm, self).__init__(csrf_enabled=False, *args, **kwargs)
class NewProductForm(Form):
serial = StringField('Serial', default='', validators=[DataRequired()])
notes = TextAreaField('Notes', default='')
parts = FieldList(FormField(PartSelectionForm))
views.py:
#app.route('/products/new/<prodmodel>', methods=['GET', 'POST'])
#login_required
def new_product(prodmodel):
try:
model = db.session.query(ProdModel).filter(ProdModel.id==prodmodel).one()
except NoResultFound, e:
flash('No products of model type -' + prodmodel + '- found.', 'error')
return redirect(url_for('index'))
keys = db.session.query(ProdTypeTemplate.prod_info_key).filter(ProdTypeTemplate.prod_type_id==model.prod_type_id)\
.order_by(ProdTypeTemplate.prod_info_key).all()
parts_needed = db.session.query(ProdModelTemplate).filter(ProdModelTemplate.prod_model_id==prodmodel)\
.order_by(ProdModelTemplate.part_type_id, ProdModelTemplate.slot).all()
class F(forms.NewProductForm):
pass
for key in keys:
if key.prod_info_key in ['shipped_os','factory_os']:
setattr(F, key.prod_info_key, forms.QuerySelectField(key.prod_info_key, get_label='version'))
else:
setattr(F, key.prod_info_key, forms.StringField(key.prod_info_key, validators=[forms.DataRequired()]))
form = F(request.form)
if request.method == 'GET':
for part in parts_needed:
entry = form.parts.append_entry(forms.PartSelectionForm())
entry.part_type.data=part.part_type_id
entry.slot.data=slot=part.slot
entry.required.data=part.required
entry.selected_part.query = db.session.query(Part).join(PartModel).filter(PartModel.part_type_id==part.part_type_id, Part.status=='inventory')
if form.__contains__('shipped_os'):
form.shipped_os.query = db.session.query(OSVersion).order_by(OSVersion.version)
if form.__contains__('factory_os'):
form.factory_os.query = db.session.query(OSVersion).order_by(OSVersion.version)
if form.validate_on_submit():
...
Everything works as expected on a GET request, but on the validate_on_submit I get errors. The error is that all of the queries and query_factories for the selected_part QuerySelectFields in the list of PartSelectionForms is none, causing either direct errors in WTForms validation code or when Jinja2 attempts to re-render the QuerySelectFields. I'm not sure why this happens on the POST when everything appears to be correct for the GET.
I realized that although I set the required queries on a GET I'm not doing it for any PartSelectionForm selected_part entries on the POST. Since I already intended part_type, slot, and required to be hidden form fields, I added the following immediately before the validate_on_submit and everything works correctly:
for entry in form.parts:
entry.selected_part.query = db.session.query(Part).join(PartModel).\
filter(PartModel.part_type_id==entry.part_type.data, Part.status=='inventory')

NullReferenceException while getting properties from session object

I have created a class with name Examination, in this class I have a method with name Get Question(), in take exam when i am creating object of Examination and Run Application it gives following error.
NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 18: Examination e = (Examination)Session["questions"];
Line 19: // display data
Line 20: lblSubject.Text = e.sname;
Line 21: lblQno.Text = e.curpos + 1 + "/" + e.SIZE;
Line 22: lblCtime.Text = DateTime.Now.ToString();
Most probably Session["questions"] does not contain a value, and returns null. It is perfectly valid to cast null to a reference type, but the exception occurs where you try to access properties of it.
You should test if it's null, for instance:
Examination e = (Examination)Session["questions"];
if (e == null)
{
lblSubject.Text = "Your session has expired";
}
(If I'm wrong, and e actually contains a reference to an Examination object, then it's lblSubject that's null)

Resources