Best Python code snippet using pytest
inspect_utils_test.py
Source: inspect_utils_test.py
...72 def test_fn():73 pass74 self.assertTrue(inspect_utils.islambda(lambda x: x))75 self.assertFalse(inspect_utils.islambda(test_fn))76 def test_isnamedtuple(self):77 nt = collections.namedtuple('TestNamedTuple', ['a', 'b'])78 class NotANamedTuple(tuple):79 pass80 self.assertTrue(inspect_utils.isnamedtuple(nt))81 self.assertFalse(inspect_utils.isnamedtuple(NotANamedTuple))82 def test_isnamedtuple_confounder(self):83 """This test highlights false positives when detecting named tuples."""84 class NamedTupleLike(tuple):85 _fields = ('a', 'b')86 self.assertTrue(inspect_utils.isnamedtuple(NamedTupleLike))87 def test_isnamedtuple_subclass(self):88 """This test highlights false positives when detecting named tuples."""89 class NamedTupleSubclass(collections.namedtuple('Test', ['a', 'b'])):90 pass91 self.assertTrue(inspect_utils.isnamedtuple(NamedTupleSubclass))92 def test_getnamespace_globals(self):93 ns = inspect_utils.getnamespace(factory)94 self.assertEqual(ns['free_function'], free_function)95 def test_getnamespace_hermetic(self):96 # Intentionally hiding the global function to make sure we don't overwrite97 # it in the global namespace.98 free_function = object() # pylint:disable=redefined-outer-name99 def test_fn():100 return free_function101 ns = inspect_utils.getnamespace(test_fn)102 globs = six.get_function_globals(test_fn)103 self.assertTrue(ns['free_function'] is free_function)104 self.assertFalse(globs['free_function'] is free_function)105 def test_getnamespace_locals(self):...
csvtools.py
Source: csvtools.py
1from __future__ import absolute_import as _absimport, division as _division2import csv as _csv3import os as _os4from fractions import Fraction as _Fraction5from collections import namedtuple as _namedtuple6def _could_be_number(s, accept_fractions=False):7 try:8 n = eval(s)9 return isinstance(n, _Number)10 except:11 return False12def _as_number_if_possible(s, accept_fractions=True):13 """try to convert 's' to a number if it is possible"""14 if accept_fractions:15 if "/" in s:16 try:17 n = _Fraction("/".join(n.strip() for n in s.split("/")))18 return n19 except:20 return s21 try:22 n = int(s)23 return n24 except ValueError:25 try:26 n = float(s)27 return n28 except ValueError:29 s30 return s31def replace_non_alfa(s):32 TRANSLATION_STRING = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'__x+,__/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'33 return s.translate(TRANSLATION_STRING, '[]#:')34def _normalize_column_name(name):35 name = replace_non_alfa(name)36 if name and name[0] in '0123456789':37 name = 'n' + name38 name = name.strip().rstrip('_')39 return name if name else 'untitled'40def _treat_duplicates(columns):41 names = {}42 new_names = []43 for column in columns:44 if not column in names:45 names[column] = 146 new_name = column47 else:48 n = names[column]49 n += 150 names[column] = n51 new_name = "%s_%d" % (column, n)52 new_names.append(new_name)53 return new_names54def readcsv_numpy(csvfile):55 """56 Read CSV into a numpy array57 """58 import numpy59 return numpy.genfromtxt(csvfile, names=True, delimiter=',')60def readcsv(csvfile, rowname=None, transform_numbers=True, astuple=False, prefer_fractions=True, dialect='excel'):61 """62 read a CSV file into a namedtuple63 64 if the first collumn is all text: assume these are the column names65 mode: in some cases you might need to set mode='U' when reading66 files generated by excel in windows67 rowname: override the row name specified in the CSV file (if any)68 transform_numbers: convert strings to numbers if they can be converted69 prefer_fractions: the normal behaviour to treat strings like 3/4 is to treat70 them as dates. If this is True, fractions will be prefered71 astuple: do not use namedtuples, use normal tuples instead72 """73 assert dialect in _csv.list_dialects()74 mode = "U"75 f = open(csvfile, mode)76 r = _csv.reader(f, dialect=dialect)77 try:78 firstrow = next(r)79 except:80 mode = mode + 'U'81 f = open(csvfile, mode + 'U')82 r = _csv.reader(f, dialect=dialect)83 first_row = next(r)84 attributes = {}85 if firstrow[0].startswith('#'):86 # the first row contains attributes87 f.close()88 f = open(csvfile, mode)89 attribute_line = f.readline()90 attrs = attribute_line[1:].split()91 for attr in attrs:92 key, value = attr.split(':')93 attributes[key] = value94 r = _csv.reader(f, dialect=dialect)95 firstrow = next(r)96 else:97 attrs = None98 if all(not _could_be_number(x) for x in firstrow) or first_row[0].startswith('#'):99 columns = firstrow100 else:101 raise TypeError("""102 Number-like cells found in the first-row. cannot assume column names103 To load simple data you dont need this utility so use normal csv module104 """)105 normalized_columns = [_normalize_column_name(col) for col in columns]106 columns = _treat_duplicates(normalized_columns)107 if attributes:108 a_rowname = attributes.get('rowname')109 rowname = rowname if rowname is not None else a_rowname110 rowname = rowname if rowname is not None else 'Row'111 Row = _namedtuple(rowname, ' '.join(columns))112 numcolumns = len(columns)113 rows = []114 for row in r:115 if transform_numbers:116 row = [_as_number_if_possible(cell, accept_fractions=prefer_fractions) for cell in row]117 if not astuple:118 if len(row) == numcolumns:119 rows.append(Row(*row))120 else:121 row.extend([''] * (numcolumns - len(row)))122 row = row[:numcolumns]123 rows.append(Row(*row))124 else:125 rows.append(row)126 return rows127def read(*args, **kws):128 import warnings129 warnings.warn("This function has been renamed to readcsv")130 return readcsv(*args, **kws)131def readcsv_tabs(csvfile, transform_numbers=True, as_tuple=False):132 """133 read a csv file which uses tabs instead of commas as column-divider134 """135 return read(csvfile, transform_numbers=transform_numbers, as_tuple=as_tuple, dialect='excel-tab')136def writecsv(namedtuples, outfile, column_names=None, write_row_name=False):137 """138 write a sequence of named tuples to outfile as CSV139 alternatively, you can also specify the column_names. in this case it140 is not necessary for the tuples to be be namedtuples141 """142 firstrow = namedtuples[0]143 isnamedtuple = hasattr(firstrow, '_fields')144 if isnamedtuple:145 column_names = firstrow._fields146 outfile = _os.path.splitext(outfile)[0] + '.csv'147 def parse_fractions(row):148 def parse_fraction(cell):149 if isinstance(cell, Fraction):150 return "0 %s" % str(cell)151 elif isinstance(cell, str) and "/" in cell:152 return '"%s"' % str(cell)153 return cell154 row = list(map(parse_fraction, row))155 return row156 f = open(outfile, 'wb')157 f_write = f.write158 w = _csv.writer(f)159 if isnamedtuple and write_row_name:160 try:161 rowname = firstrow.__doc__.split('(')[0] # <-- this is a hack! where is the name of a namedtuple??162 except AttributeError: # maybe not a namedtuple in the end163 rowname = firstrow.__class__.__name__164 line = "# rowname:%s\n" % rowname165 f_write(line)166 if column_names:167 w.writerow(column_names)168 for row in namedtuples:169 try:170 w.writerow(row)171 except:172 w.writerow(tuple(row))173 f.close()174def _to_number(x, accept_fractions=True):175 if _could_be_number(x, accept_fractions=accept_fractions):176 if '.' in x or x in ('nan', 'inf', '-inf'):177 return float(x)178 else:179 try:180 return int(x)181 except:182 try:183 return _Fraction(x)184 except:185 return x186 else:187 return x188# class NamedTuples(list):189# def __init__(self, column_names, row_name='_'):190# self.factory = _namedtuple(row_name, column_names)191# if isinstance(column_names, basestring):192# column_names = [name.strip() for name in (column_names.split(',') if ',' in column_names else column_names.split())]193# self.column_names = column_names194# def append(self, *args, **keys):195# list.append(self, self.factory(*args, **keys))196# def writecsv(self, outfile):197# writecsv(self, outfile, self.column_names)198# @classmethod199# def readcsv(self, csvfile):200# rows = read(csvfile)201# row_name = '_'202# column_names = ' '.join(rows[0]._fields)203# out = NamedTuples(row_name, column_names)204# out.extend(rows)...
lambda_resource.py
Source: lambda_resource.py
...60 def __handler(exc, handler):61 return lambda f: excepts(exc, f, handler)62 @staticmethod63 def __multiple_items(result) -> bool:64 return isiterable(result) and not isinstance(result, dict) and not RestResource.__isnamedtuple(result)65 @staticmethod66 def __isnamedtuple(x):67 x_type = type(x)68 bases = x_type.__bases__69 if len(bases) != 1 or bases[0] != tuple:70 return False71 fields = getattr(x_type, '_fields', None)72 return isinstance(fields, tuple) and all(type(n) == str for n in fields)73 def _handle(self, event):74 safe_route = compose(75 self.__handler(Exception , self.__internal_error),76 self.__handler(MarshmallowError, self.__json_error )77 )(self.__route)78 result = safe_route(event)79 response = (80 result.as_json() if isinstance(result, HttpResponse) else...
utils.py
Source: utils.py
1def isnumber(x):2 return isinstance(x,int) or isinstance(x,float)3def istuple(x):4 return isinstance(x, tuple) and not isnamedtuple(x)5def isnamedtuple(x):6 return isinstance(x, tuple) and hasattr(x, '_asdict') and hasattr(x, '_fields')7def mktuple(*xs):8 return tuple(xs)9def decomment(file):10 lines, out, lastc, instr = file.splitlines(), [], '', False11 for line in lines: 12 outline = ''13 for c in line:14 if c in '"\'' and lastc != '\\': instr = not instr15 if c in '\\' and lastc == '\\': lastc = ''; continue16 if c in ';' and not instr: break17 outline += c18 lastc = c19 out.append(outline)...
Does TensorFlow have cross validation implemented for its users?
Docker sqlite3.OperationalError: unable to open database file
argparse parser: overriding options
Moto SNS client can't get publishing working AttributeError: 'sns.ServiceResource' object has no attribute 'publish'
fatal error: Python.h: No such file or directory
Azure DevOps - Pytest unit tests started failing
What does the "yield" keyword do?
pytest fixture of fixture, not found
How to skip the rest of tests in the class if one has failed?
How do I merge two dictionaries in a single expression?
As already discussed, tensorflow doesn't provide its own way to cross-validate the model. The recommended way is to use KFold
. It's a bit tedious, but doable. Here's a complete example of cross-validating MNIST model with tensorflow
and KFold
:
from sklearn.model_selection import KFold
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# Parameters
learning_rate = 0.01
batch_size = 500
# TF graph
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
pred = tf.nn.softmax(tf.matmul(x, W) + b)
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
init = tf.global_variables_initializer()
mnist = input_data.read_data_sets("data/mnist-tf", one_hot=True)
train_x_all = mnist.train.images
train_y_all = mnist.train.labels
test_x = mnist.test.images
test_y = mnist.test.labels
def run_train(session, train_x, train_y):
print "\nStart training"
session.run(init)
for epoch in range(10):
total_batch = int(train_x.shape[0] / batch_size)
for i in range(total_batch):
batch_x = train_x[i*batch_size:(i+1)*batch_size]
batch_y = train_y[i*batch_size:(i+1)*batch_size]
_, c = session.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
if i % 50 == 0:
print "Epoch #%d step=%d cost=%f" % (epoch, i, c)
def cross_validate(session, split_size=5):
results = []
kf = KFold(n_splits=split_size)
for train_idx, val_idx in kf.split(train_x_all, train_y_all):
train_x = train_x_all[train_idx]
train_y = train_y_all[train_idx]
val_x = train_x_all[val_idx]
val_y = train_y_all[val_idx]
run_train(session, train_x, train_y)
results.append(session.run(accuracy, feed_dict={x: val_x, y: val_y}))
return results
with tf.Session() as session:
result = cross_validate(session)
print "Cross-validation result: %s" % result
print "Test accuracy: %f" % session.run(accuracy, feed_dict={x: test_x, y: test_y})
Check out the latest blogs from LambdaTest on this topic:
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium pytest Tutorial.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium Python Tutorial.
The primary intent of Selenium test automation is to expedite the testing process. In the majority of the cases, automation tests using Selenium perform exceptionally better than the manual counterparts. However, there might be possibilities to speed up Selenium tests using Selenium test automation best practices to its truest potential. I have come across umpteen cases in my career where there was potential to speed up selenium tests.
In an ideal world, you can test your web application in the same test environment and return the same results every time. The reality can be difficult sometimes when you have flaky tests, which may be due to the complexity of the web elements you are trying to perform an action on your test case.
So you are at the beginning of 2020 and probably have committed a new year resolution as a tester to take a leap from Manual Testing To Automation . However, to automate your test scripts you need to get your hands dirty on a programming language and that is where you are stuck! Or you are already proficient in automation testing through a single programming language and are thinking about venturing into new programming languages for automation testing, along with their respective frameworks. You are bound to be confused about picking your next milestone. After all, there are numerous programming languages to choose from.
Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.
Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.
https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP
Get 100 minutes of automation test minutes FREE!!