Pytest-drf unit tests and dict_items assert - pytest

There is a code in a legacy project using pytest-drf and I'm new in Python and tests, I would like to know what an assert checking two dict_items is comparing, but could not find out neither other examples nor explanations about it.
Here's the code:
#pytest.mark.django_db
class TestPhones(Base)
list_url = lambda_fixture(lambda: url_for('phones-list'))
detail_url = lambda_fixture(
lambda old_phone: url_for('phones-detail', old_phone.pk))
class TestCreate(VerbTests.Create):
data = phone_json
def test_returned_json(self, data, json, model):
expected = data.items()
actual = json.items()
assert expected <= actual
What is this assert code doing?
I couldn't understand why it's being used the lower symbol '<' for this assert, I see that it's comparing dict_items content in 'expected' and 'actual' received from the API in json format, but couldn't find what's going on.

assert <condition> is used to check that an expected condition is fulfilled.
For more information on the testing and especially on assert, you can have a look on Pytest documentation
While comparing the dictionaries, dict1<=dict2 returns True if dict1 is contained in dict2.
Here a code which show the different cases:
my_dict = {"test1":"test_val1", "test2":"test_val2", "test3":"test_val3", "test4":"test_val4", "test5":"test_val5"}
for my_tuple in [
(["test1", "test2"], ["test1", "test5"]),
(["test1", "test2"], ["test1", "test2"]),
(["test1", "test2"], ["test1"]),
(["test1"], ["test1", "test5"]),
]:
my_dict1 = {}
my_dict2 = {}
for key in my_tuple[0]:
my_dict1[key] = my_dict[key]
for key in my_tuple[1]:
my_dict2[key] = my_dict[key]
print(my_dict1.items() <= my_dict2.items(), "---", my_dict1, "<=", my_dict2)
The returned output
False --- {'test1': 'test_val1', 'test2': 'test_val2'} <= {'test1': 'test_val1', 'test5': 'test_val5'} # not contained
True --- {'test1': 'test_val1', 'test2': 'test_val2'} <= {'test1': 'test_val1', 'test2': 'test_val2'} # equal
False --- {'test1': 'test_val1', 'test2': 'test_val2'} <= {'test1': 'test_val1'} # not contained
True --- {'test1': 'test_val1'} <= {'test1': 'test_val1', 'test5': 'test_val5'} # contained

Related

Storage values using os.stat(filename)

I'm trying to create an EDUCATIONAL PURPOSES ONLY virus. I do not plan on spreading it. It's purpose is to grow a file to the point your storage is full and slow your computer down. It prints the size of the file every 0.001 seconds. With that, I also want to know how fast it is growing the file. The following code doesn't seem to let it run:
class Vstatus():
def _init_(Status):
Status.countspeed == True
Status.active == True
Status.growingspeed == 0
import time
import os
#Your storage is at risk of over-expansion. Please do not let this file run forever, as your storage will fill continuously.
#This is for educational purposes only.
while Vstatus.Status.countspeed == True:
f = open('file.txt', 'a')
f.write('W')
fsize = os.stat('file.txt')
Key1 = fsize
time.sleep(1)
Key2 = fsize
Vstatus.Status.growingspeed = (Key2 - Key1)
Vstatus.Status.countspeed = False
while Vstatus.Status.active == True:
time.sleep(0.001)
f = open('file.txt', 'a')
f.write('W')
fsize = os.stat('file.txt')
print('size:' + fsize.st_size.__str__() + ' at a speed of ' + Vstatus.Status.growingspeed + 'bytes per second.')
This is for Educational Purposes ONLY
The main error I keep getting when running the file is here:
TypeError: unsupported operand type(s) for -: 'os.stat_result' and 'os.stat_result'
What does this mean? I thought os.stat returned an integer Can I get a fix on this?
Vstatus.Status.growingspeed = (Key2 - Key1)
You can't subtract os.stat objects. Your code also has some other problems. Your loops will run sequentially, meaning that your first loop will try to estimate how quickly the file is being written to without writing anything to the file.
import time # Imports at the top
import os
class VStatus:
def __init__(self): # double underscores around __init__
self.countspeed = True # Assignment, not equality test
self.active = True
self.growingspeed = 0
status = VStatus() # Make a VStatus instance
# You need to do the speed estimation and file appending in the same loop
with open('file.txt', 'a+') as f: # Only open the file once
start = time.time() # Get the current time
starting_size = os.fstat(f.fileno()).st_size
while status.active: # Access the attribute of the VStatus instance
size = os.fstat(f.fileno()).st_size # Send file desciptor to stat
f.write('W') # Writing more than one character at a time will be your biggest speed up
f.flush() # make sure the byte is written
if status.countspeed:
diff = time.time() - start
if diff >= 1: # More than a second has gone by
status.countspeed = False
status.growingspeed = (os.fstat(f.fileno()).st_size - starting_size)/diff # get rate of growth
else:
print(f"size: {size} at a speed of {status.growingspeed}")

Trouble with evalfis()

I'm having trouble with the fuzzy inference system; suddenly after I reinstalled Windows OS and MATLAB in my laptop, when I tried to run the code, a message appeared: "Error: File: readfis.m Line: 1 Column: 1
The input character is not valid in MATLAB statements or expressions."
C = evalfis(B, fis_name);
Even when I try to run the example codes, the same message appears.
In a first moment I thought it could be related to the reinstallation, but after I copied the .m file into another PC and tried to run it, the situation was the same, and I don't know why...
After I tried again, I opened the specified readfis.m file; it seemed strange for me; I put it below... However, when I searched into the files of MATLAB (following path C:\Program Files\MATLAB\R2014a\toolbox\fuzzy\fuzzy) I opened the evalfis.m file, which was radically different, it was more like an usual .m file; I just copied the .m file located in the fuzzy toolbox and pasted it into the working directory, replacing the other .m file; after doing that, I could run the code succesfully.
Here I put the code of the REPLACING evalfis.m file:
function [output,IRR,ORR,ARR] = evalfis(input, fis, numofpoints);
% EVALFIS Perform fuzzy inference calculations.
%
% Y = EVALFIS(U,FIS) simulates the Fuzzy Inference System FIS for the
% input data U and returns the output data Y. For a system with N
% input variables and L output variables,
% * U is a M-by-N matrix, each row being a particular input vector
% * Y is M-by-L matrix, each row being a particular output vector.
%
% Y = EVALFIS(U,FIS,NPts) further specifies number of sample points
% on which to evaluate the membership functions over the input or output
% range. If this argument is not used, the default value is 101 points.
%
% [Y,IRR,ORR,ARR] = EVALFIS(U,FIS) also returns the following range
% variables when U is a row vector (only one set of inputs is applied):
% * IRR: the result of evaluating the input values through the membership
% functions. This is a matrix of size Nr-by-N, where Nr is the number
% of rules, and N is the number of input variables.
% * ORR: the result of evaluating the output values through the membership
% functions. This is a matrix of size NPts-by-Nr*L. The first Nr
% columns of this matrix correspond to the first output, the next Nr
% columns correspond to the second output, and so forth.
% * ARR: the NPts-by-L matrix of the aggregate values sampled at NPts
% along the output range for each output.
%
% Example:
% fis = readfis('tipper');
% out = evalfis([2 1; 4 9],fis)
% This generates the response
% out =
% 7.0169
% 19.6810
%
% See also READFIS, RULEVIEW, GENSURF.
% Kelly Liu, 10-10-97.
% Copyright 1994-2005 The MathWorks, Inc.
ni = nargin;
if ni<2
disp('Need at least two inputs');
output=[];
IRR=[];
ORR=[];
ARR=[];
return
end
% Check inputs
if ~isfis(fis)
error('The second argument must be a FIS structure.')
elseif strcmpi(fis.type,'sugeno') & ~strcmpi(fis.impMethod,'prod')
warning('Fuzzy:evalfis:ImplicationMethod','Implication method should be "prod" for Sugeno systems.')
end
[M,N] = size(input);
Nin = length(fis.input);
if M==1 & N==1,
input = input(:,ones(1,Nin));
elseif M==Nin & N~=Nin,
input = input.';
elseif N~=Nin
error(sprintf('%s\n%s',...
'The first argument should have as many columns as input variables and',...
'as many rows as independent sets of input values.'))
end
% Check the fis for empty values
checkfis(fis);
% Issue warning if inputs out of range
inRange = getfis(fis,'inRange');
InputMin = min(input,[],1);
InputMax = max(input,[],1);
if any(InputMin(:)<inRange(:,1)) | any(InputMax(:)>inRange(:,2))
warning('Fuzzy:evalfis:InputOutOfRange','Some input values are outside of the specified input range.')
end
% Compute output
if ni==2
numofpoints = 101;
end
[output,IRR,ORR,ARR] = evalfismex(input, fis, numofpoints);
...And this is the content of the REPLACED evalfis.m file:
## Copyright (C) 2011-2014 L. Markowsky <lmarkov#users.sourceforge.net>
##
## This file is part of the fuzzy-logic-toolkit.
##
## The fuzzy-logic-toolkit is free software; you can redistribute it
## and/or modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; either version 3 of
## the License, or (at your option) any later version.
##
## The fuzzy-logic-toolkit is distributed in the hope that it will be
## useful, but WITHOUT ANY WARRANTY; without even the implied warranty
## of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with the fuzzy-logic-toolkit; see the file COPYING. If not,
## see <http://www.gnu.org/licenses/>.
## -*- texinfo -*-
## #deftypefn {Function File} {#var{output} =} evalfis (#var{user_input}, #var{fis})
## #deftypefnx {Function File} {#var{output} =} evalfis (#var{user_input}, #var{fis}, #var{num_points})
## #deftypefnx {Function File} {[#var{output}, #var{rule_input}, #var{rule_output}, #var{fuzzy_output}] =} evalfis (#var{user_input}, #var{fis})
## #deftypefnx {Function File} {[#var{output}, #var{rule_input}, #var{rule_output}, #var{fuzzy_output}] =} evalfis (#var{user_input}, #var{fis}, #var{num_points})
##
## Return the crisp output(s) of an FIS for each row in a matrix of crisp input
## values.
## Also, for the last row of #var{user_input}, return the intermediate results:
##
## #table #var
## #item rule_input
## a matrix of the degree to which
## each FIS rule matches each FIS input variable
## #item rule_output
## a matrix of the fuzzy output for each (rule, FIS output) pair
## #item fuzzy_output
## a matrix of the aggregated output for each FIS output variable
## #end table
##
## The optional argument #var{num_points} specifies the number of points over
## which to evaluate the fuzzy values. The default value of #var{num_points} is
## 101.
##
## #noindent
## Argument #var{user_input}:
##
## #var{user_input} is a matrix of crisp input values. Each row
## represents one set of crisp FIS input values. For an FIS that has N inputs,
## an input matrix of z sets of input values will have the form:
##
## #example
## #group
## [input_11 input_12 ... input_1N] <-- 1st row is 1st set of inputs
## [input_21 input_22 ... input_2N] <-- 2nd row is 2nd set of inputs
## [ ... ] ...
## [input_z1 input_z2 ... input_zN] <-- zth row is zth set of inputs
## #end group
## #end example
##
## #noindent
## Return value #var{output}:
##
## #var{output} is a matrix of crisp output values. Each row represents
## the set of crisp FIS output values for the corresponding row of
## #var{user_input}. For an FIS that has M outputs, an #var{output} matrix
## corresponding to the preceding input matrix will have the form:
##
## #example
## #group
## [output_11 output_12 ... output_1M] <-- 1st row is 1st set of outputs
## [output_21 output_22 ... output_2M] <-- 2nd row is 2nd set of outputs
## [ ... ] ...
## [output_z1 output_z2 ... output_zM] <-- zth row is zth set of outputs
## #end group
## #end example
##
## #noindent
## The intermediate result #var{rule_input}:
##
## The matching degree for each (rule, input value) pair is specified by the
## #var{rule_input} matrix. For an FIS that has Q rules and N input variables,
## the matrix will have the form:
## #example
## #group
## in_1 in_2 ... in_N
## rule_1 [mu_11 mu_12 ... mu_1N]
## rule_2 [mu_21 mu_22 ... mu_2N]
## [ ... ]
## rule_Q [mu_Q1 mu_Q2 ... mu_QN]
## #end group
## #end example
##
## #noindent
## Evaluation of hedges and "not":
##
## Each element of each FIS rule antecedent and consequent indicates the
## corresponding membership function, hedge, and whether or not "not" should
## be applied to the result. The index of the membership function to be used is
## given by the positive whole number portion of the antecedent/consequent
## vector entry, the hedge is given by the fractional portion (if any), and
## "not" is indicated by a minus sign. A "0" as the integer portion in any
## position in the rule indicates that the corresponding FIS input or output
## variable is omitted from the rule.
##
## For custom hedges and the four built-in hedges "somewhat," "very,"
## "extremely," and "very very," the membership function value (without the
## hedge or "not") is raised to the power corresponding to the hedge. All
## hedges are rounded to 2 digits.
##
## For example, if "mu(x)" denotes the matching degree of the input to the
## corresponding membership function without a hedge or "not," then the final
## matching degree recorded in #var{rule_input} will be computed by applying
## the hedge and "not" in two steps. First, the hedge is applied:
##
## #example
## #group
## (fraction == .05) <=> somewhat x <=> mu(x)^0.5 <=> sqrt(mu(x))
## (fraction == .20) <=> very x <=> mu(x)^2 <=> sqr(mu(x))
## (fraction == .30) <=> extremely x <=> mu(x)^3 <=> cube(mu(x))
## (fraction == .40) <=> very very x <=> mu(x)^4
## (fraction == .dd) <=> <custom hedge> x <=> mu(x)^(dd/10)
## #end group
## #end example
##
## After applying the appropriate hedge, "not" is calculated by:
## #example
## minus sign present <=> not x <=> 1 - mu(x)
## minus sign and hedge present <=> not <hedge> x <=> 1 - mu(x)^(dd/10)
## #end example
##
## Hedges and "not" in the consequent are handled similarly.
##
## #noindent
## The intermediate result #var{rule_output}:
##
## For either a Mamdani-type FIS (that is, an FIS that does not have constant or
## linear output membership functions) or a Sugeno-type FIS (that is, an FIS
## that has only constant and linear output membership functions),
## #var{rule_output} specifies the fuzzy output for each (rule, FIS output) pair.
## The format of rule_output depends on the FIS type.
##
## For a Mamdani-type FIS, #var{rule_output} is a #var{num_points} x (Q * M)
## matrix, where Q is the number of rules and M is the number of FIS output
## variables. Each column of this matrix gives the y-values of the fuzzy
## output for a single (rule, FIS output) pair.
##
## #example
## #group
## Q cols Q cols Q cols
## --------------- --------------- ---------------
## out_1 ... out_1 out_2 ... out_2 ... out_M ... out_M
## 1 [ ]
## 2 [ ]
## ... [ ]
## num_points [ ]
## #end group
## #end example
##
## For a Sugeno-type FIS, #var{rule_output} is a 2 x (Q * M) matrix.
## Each column of this matrix gives the (location, height) pair of the
## singleton output for a single (rule, FIS output) pair.
##
## #example
## #group
## Q cols Q cols Q cols
## --------------- --------------- ---------------
## out_1 ... out_1 out_2 ... out_2 ... out_M ... out_M
## location [ ]
## height [ ]
## #end group
## #end example
##
## #noindent
## The intermediate result #var{fuzzy_output}:
##
## The format of #var{fuzzy_output} depends on the FIS type ('mamdani' or
## 'sugeno').
##
## For either a Mamdani-type FIS or a Sugeno-type FIS, #var{fuzzy_output}
## specifies the aggregated fuzzy output for each FIS output.
##
## For a Mamdani-type FIS, the aggregated #var{fuzzy_output} is a
## #var{num_points} x M matrix. Each column of this matrix gives the y-values
## of the fuzzy output for a single FIS output, aggregated over all rules.
##
## #example
## #group
## out_1 out_2 ... out_M
## 1 [ ]
## 2 [ ]
## ... [ ]
## num_points [ ]
## #end group
## #end example
##
## For a Sugeno-type FIS, the aggregated output for each FIS output is a 2 x L
## matrix, where L is the number of distinct singleton locations in the
## #var{rule_output} for that FIS output:
##
## #example
## #group
## singleton_1 singleton_2 ... singleton_L
## location [ ]
## height [ ]
## #end group
## #end example
##
## Then #var{fuzzy_output} is a vector of M structures, each of which has an index and
## one of these matrices.
##
## #noindent
## Examples:
##
## Seven examples of using evalfis are shown in:
## #itemize #bullet
## #item
## cubic_approx_demo.m
## #item
## heart_disease_demo_1.m
## #item
## heart_disease_demo_2.m
## #item
## investment_portfolio_demo.m
## #item
## linear_tip_demo.m
## #item
## mamdani_tip_demo.m
## #item
## sugeno_tip_demo.m
## #end itemize
##
## #seealso{cubic_approx_demo, heart_disease_demo_1, heart_disease_demo_2, investment_portfolio_demo, linear_tip_demo, mamdani_tip_demo, sugeno_tip_demo}
## #end deftypefn
## Author: L. Markowsky
## Keywords: fuzzy-logic-toolkit fuzzy inference system fis
## Directory: fuzzy-logic-toolkit/inst/
## Filename: evalfis.m
## Last-Modified: 20 Aug 2012
function [output, rule_input, rule_output, fuzzy_output] = ...
evalfis (user_input, fis, num_points = 101)
## If evalfis was called with an incorrect number of arguments, or
## the arguments do not have the correct type, print an error message
## and halt.
if ((nargin != 2) && (nargin != 3))
puts ("Type 'help evalfis' for more information.\n");
error ("evalfis requires 2 or 3 arguments\n");
elseif (!is_fis (fis))
puts ("Type 'help evalfis' for more information.\n");
error ("evalfis's second argument must be an FIS structure\n");
elseif (!is_input_matrix (user_input, fis))
puts ("Type 'help evalfis' for more information.\n");
error ("evalfis's 1st argument must be a matrix of input values\n");
elseif (!is_pos_int (num_points))
puts ("Type 'help evalfis' for more information.\n");
error ("evalfis's third argument must be a positive integer\n");
endif
## Call a private function to compute the output.
## (The private function is also called by gensurf.)
[output, rule_input, rule_output, fuzzy_output] = ...
evalfis_private (user_input, fis, num_points);
endfunction

Undefined variables in `if` statement

This will work as expected:
a := "111"
b := "222"
if (a != "aaa" and b != "bbb")
MsgBox, Yes
But the "Yes" message will be also shown if one of the variables is not defined
; a := "111" ; Commented line
b := "222"
if (a != "aaa" and b != "bbb")
MsgBox, Yes ; Since var "a" is not defined, I don't want this message box
Here is how I fix it:
; a := "111"
b := "222"
if ((a and b) and (a != "aaa" and b != "bbb"))
MsgBox, Yes
But from my point of view it looks like something awful. Is there exist more correct way?
Since and is commutative, you can do without the parentheses:
if a and b and a != "aaa" and b != "bbb"
ALTERNATIVE SOLUTION
Initialize your variables to the value you're testing (aaa) so that if your implementation code doesn't alter them, you'll get the desired result:
a=aaa
b=bbb
... do some stuff ...
global a,b
if a != "aaa" and b != "bbb"
MsgBox, Yes
EXPLANATION
When a is undefined, it seems like you want undefined != "aaa" to somehow evaluate to false. That's the same as saying you you want undefined == "aaa" to somehow evaluate to true. Your logic is too complex for that.
Here's a state table for your logic:
Actual Desired T1 T2
a b MsgBox MsgBox a!=aaa b!=bbb T1 and T2
----- ------ ------ ------- ------ ------ -----
undef undef Yes no true true true
undef bbb no no true false false
undef 222 Yes no true true true The example you didn't want
aaa undef no no false true false
aaa bbb no no false false false
aaa 222 no no false true false
111 undef Yes no true true true
111 bbb no no true false false
111 222 Yes Yes true true true Only one you want
The Actual MsgBox column shows when the message box appears in your original code. Desired MsgBox=Yes is what you wanted to happen. T1 and T2 are the partial calculations of your condition. T1 and T2 is the final value of your condition.
The last row shows the only state in which you want the MsgBox to appear; when a is equal to niether aaa nor undefined AND b is equal to neither bbb nor undefined.
So we can simplify the logic by initializing a to "aaa" and b to "bbb". In effect we are combining your the two conditions for each variable into a single condition by making the two values ("aaa" and undefined) equivalent.
I hope that makes sense

Pytest - Running test foo any number of times after one or more tests

I have a test like this -
class TestMyUsefulTest:
# Calling test_foo for the FIRST time
def test_foo_1(self, my_fixture):
# do something in the test method
assert 0 == 0 # I am asserting something in my test
def test_bar(self, my_fixture):
# do something in the test method
assert 0 == 0 # I am asserting something in my test
# Calling test_foo for the SECOND time
def test_foo_2(self, my_fixture):
# do something in the test method
assert 0 == 0 # I am asserting something in my test
The second time I call test_foo, I am doing the exact same thing as I did the first time.
Is there a way to call test_foo, without having to repeat the code again?
Here is the implementation based on #DJanssens' comment -
class TestMyUsefulTest:
def foo(self, a_fixture):
# do stuff with a_fixture
assert 0 == 0
def test_foo_1(self, a_fixture):
self.foo(a_fixture)
def test_bar(self, a_fixture):
assert 0 == 0
def test_foo_2(self, a_fixture):
self.foo(a_fixture)

Need help identifying and computing a number representation

I need help identifying the following number format.
For example, the following number format in MIB:
0x94 0x78 = 2680
0x94 0x78 in binary: [1001 0100] [0111 1000]
It seems that if the MSB is 1, it means another character follows it. And if it is 0, it is the end of the number.
So the value 2680 is [001 0100] [111 1000], formatted properly is [0000 1010] [0111 1000]
What is this number format called and what's a good way for computing this besides bit manipulation and shifting to a larger unsigned integer?
I have seen this called either 7bhm (7-bit has-more) or VLQ (variable length quantity); see http://en.wikipedia.org/wiki/Variable-length_quantity
This is stored big-endian (most significant byte first), as opposed to the C# BinaryReader.Read7BitEncodedInt method described at Encoding an integer in 7-bit format of C# BinaryReader.ReadString
I am not aware of any method of decoding other than bit manipulation.
Sample PHP code can be found at
http://php.net/manual/en/function.intval.php#62613
or in Python I would do something like
def encode_7bhm(i):
o = [ chr(i & 0x7f) ]
i /= 128
while i > 0:
o.insert(0, chr(0x80 | (i & 0x7f)))
i /= 128
return ''.join(o)
def decode_7bhm(s):
o = 0
for i in range(len(s)):
v = ord(s[i])
o = 128*o + (v & 0x7f)
if v & 0x80 == 0:
# found end of encoded value
break
else:
# out of string, and end not found - error!
raise TypeError
return o