How to use isnamedtuple method in Pytest

Best Python code snippet using pytest

inspect_utils_test.py

Source:inspect_utils_test.py Github

copy

Full Screen

...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):...

Full Screen

Full Screen

csvtools.py

Source:csvtools.py Github

copy

Full Screen

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)...

Full Screen

Full Screen

lambda_resource.py

Source:lambda_resource.py Github

copy

Full Screen

...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...

Full Screen

Full Screen

utils.py

Source:utils.py Github

copy

Full Screen

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)...

Full Screen

Full Screen

Pytest Tutorial

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.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful