How to use _original_content method in tox

Best Python code snippet using tox_python

file_content.py

Source:file_content.py Github

copy

Full Screen

1import itertools2import random3import string4import textwrap5from .decorators import is_numeric6class FileContent(object):7 def __init__(self, *args, **kwargs):8 self._randomized = False9 self._string_content = None10 self._dict_content = None11 self._original_content = None12 if len(args) != 0:13 self._original_content = args[0]14 self._params = kwargs.get('params', [])15 self._original_params = self._params16 self._values = kwargs.get('values', [])17 self._original_values = self._values18 self.reset()19 def reset(self):20 self._randomized = False21 self._params = self._original_params[:]22 self._values = self._original_values[:]23 self._string_content = None24 self._dict_content = None25 self._content = self._original_content26 if isinstance(self._original_content, dict):27 self._dict_content = self._original_content28 else:29 self._string_content = self._original_content30 @property31 def values(self):32 if not self._randomized:33 self.randomize()34 return self._values35 @property36 def params(self):37 if not self._randomized:38 self.randomize()39 return self._params40 @property41 def content(self):42 # Is this a good idea to do? Or treat this as a non-prop?43 if not self._randomized:44 self.randomize()45 return textwrap.dedent(self._content)46 @property47 def as_string(self):48 return self.content49 @property50 def as_dict(self):51 if not self._randomized:52 self.randomize()53 if self._dict_content is not None:54 return self._dict_content55 return {}56 @content.setter57 def content(self, value):58 if isinstance(value, dict):59 lines = []60 for key, val in value.items():61 if not is_numeric(val):62 line_val = "%s = '%s'" % (key, val)63 else:64 line_val = "%s = %s" % (key, val)65 lines.append(line_val)66 self._string_content = "\n".join(lines)67 self._dict_content = value68 else:69 self._string_content = value70 self._dict_content = None71 self._content = self._string_content72 @classmethod73 def random_string(cls, length=None):74 """75 Generate a random string with the combination of lowercase and76 uppercase letters.77 """78 letters = string.ascii_letters79 if not length:80 length = random.randint(5, 10)81 upper = random.choice([True, False, False])82 rand_string = ''.join(random.choice(letters) for i in range(length))83 if upper:84 return rand_string.upper()85 return rand_string.lower()86 @classmethod87 def random_int(cls):88 return random.randint(0, 1000)89 @classmethod90 def random_float(cls):91 return round(float(cls.random_int() / cls.random_int()), 3)92 @classmethod93 def random_values(cls, num_values):94 cycler = itertools.cycle([95 cls.random_string,96 cls.random_int,97 cls.random_float98 ])99 values = []100 for _ in range(num_values):101 randomizer = next(cycler)102 values.append(randomizer())103 return values104 @classmethod105 def random_params(cls, num_params):106 return [cls.random_string() for _ in range(num_params)]107 def randomize(self, **kwargs):108 """109 Generates a set of key-value pairs for creating content of a test110 module file so that the keys and values are unique for each test.111 This ensures that we are in fact not reading a previously created112 temporary module file that was not reloaded, and it also guarantees113 that we are testing different variable types.114 """115 test_cls = kwargs.get('test_cls')116 self.reset()117 if self._string_content:118 self.content = self._string_content119 elif self._dict_content:120 if test_cls:121 new_content = {}122 for k, v in self._content.items():123 new_key = "%s_%s" % (k, test_cls.file_count)124 new_content[new_key] = v125 self.content = new_content126 else:127 self.content = self._dict_content128 else:129 if self._params or self._values:130 if not self._values or (len(self._params) > len(self._values)):131 # If params are set manually, make sure they are unique for132 # each test.133 if test_cls:134 for i in range(len(self._params)):135 self._params[i] = "%s_%s" % (self._params[i], test_cls.file_count)136 self._values.extend(137 self.random_values(len(self._params) - len(self._values)))138 elif not self._params or (len(self._values) > len(self._params)):139 assert not self._params or len(self._values) > len(self._params)140 self._params.extend(141 self.random_values(len(self._values) - len(self._params)))142 assert len(self._params) == len(self._values)143 kwargs.setdefault('num_params', len(self._params))144 num_params = kwargs.get('num_params', 2)145 leftover = max(num_params - len(self._params), 0)146 self._params.extend(self.random_params(leftover))147 self._values.extend(self.random_values(leftover))148 if test_cls:149 test_cls.file_count += 1150 self.content = dict(zip(self._params, self._values))151 self._randomized = True...

Full Screen

Full Screen

sudoku.py

Source:sudoku.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-23import pandas as pd4import numpy as np56class Sudoku:7 8 def __init__(self):9 self._content = []10 self._original_content = []11 12 @classmethod13 def from_string(cls, string):14 """15 Loads sudoku from string16 """17 sudoku = cls()18 sudoku.content = np.array( [ [int(i) for i in line] 19 for line in string.split() ] )20 return sudoku21 22 @classmethod23 def from_csv(cls, filename):24 """25 Loads sudoku from csv file (comma separated value file)26 """27 sudoku = cls()28 df = pd.read_csv(filename, header=None)29 sudoku.content = df.to_numpy()30 return sudoku31 32 def to_csv(self, filename):33 """34 Loads sudoku to csv file (comma separated value file)35 """36 pd.DataFrame(self._content).to_csv(filename,37 header=None,38 index =None)39 40 @property41 def content(self):42 return self._content43 # return self.get_string()44 45 @property46 def original_content(self):47 return self._original_content48 # return self.get_string(original=True)49 50 @content.setter51 def content(self, new_content):52 # accepted input must be generalized...53 if new_content.shape != (9,9):54 raise ValueError("Expected 9x9 numpy array")55 self._original_content = new_content.copy()56 self._content = new_content.copy()57 58 def __getitem__(self, pos):59 if type(pos) is int:60 # returns a whole square61 return self._content[(pos//3)*3:(pos//3+1)*3,62 (pos% 3)*3:(pos% 3+1)*3]63 elif len(pos) == 2:64 return self._content[pos]65 elif len(pos) == 3:66 # first element is square, second and third row & column67 global_row_index = (pos[0]//3)*3 + pos[1]68 global_col_index = (pos[0]% 3)*3 + pos[2]69 return self._content[global_row_index, global_col_index]70 else:71 raise IndexError("Not a valid matrix position")72 73 def __setitem__(self, pos, value):74 if len(pos) == 2:75 if self._original_content[pos] != 0:76 raise IndexError("Cant override original number")77 self._content[pos] = value78 elif len(pos) == 3:79 # first element is square, second and third row & column80 global_ridx = (pos[0]//3)*3 + pos[1]81 global_cidx = (pos[0]% 3)*3 + pos[2]82 if self._original_content[global_ridx, global_cidx] != 0:83 raise IndexError("Cant override original number")84 self._content[global_ridx, global_cidx] = value85 else:86 raise IndexError("Not a valid matrix position")87 88 def number_of_errors(self):89 """90 Applies cost function to sudoku as is91 """92 numberOfErrors = 0 93 for i in range (0,9):94 numberOfErrors += (9 - len(np.unique(self[:,i]))) 95 numberOfErrors += (9 - len(np.unique(self[i,:])))96 return numberOfErrors97 98 def get_string(self, original=False):99 content = self._content if not original else self._original_content100 101 output = "\n"102 for i in range(len(content)):103 line = ""104 if i == 3 or i == 6:105 output += "---------------------\n"106 for j in range(len(content[i])):107 if j == 3 or j == 6:108 line += "| "109 line += str(content[i,j])+" "110 output += line+'\n'111 112 return output113 114 def __str__(self):115 return self.get_string()116 117 def __repr__(self):118 return str(self)119 120if __name__ == '__main__':121 122 startingSudoku = """123 024007000124 600000000125 003680415126 431005000127 500000032128 790000060129 209710800130 040093000131 310004750132 """133134 s1 = Sudoku.from_string(startingSudoku)135 print(s1)136 137 filename = "sudoku1.csv"138 s2 = Sudoku.from_csv(filename)139 print(s2)140 141 ...

Full Screen

Full Screen

makefile_updater.py

Source:makefile_updater.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import sys3import json4import copy5import logging6import pyparsing as pp7from .makefile_parser import MakefileParser8_LOGGER = logging.getLogger(__name__)9class MakefileUpdater(MakefileParser):10 def __init__(self):11 """ Initialize the Makefile parser12 """13 super().__init__()14 self._original_content = []15 self._updated_content = []16 def parse_file(self, file):17 """ Parse a Makefile file18 """19 _LOGGER.debug("parse_file: file: %s", file)20 file = open(file, "r")21 for line in file:22 self._original_content.append(line)23 self._parse_line(line)24 file.close()25 self._updated_content = self._original_content26 self._is_parsed = True27 def parse_text(self, text):28 """ Parse a Makefile content29 """30 splitted = text.split('\n')31 self._original_content = ["{}\n".format(i) for i in splitted[:-1]]32 self._original_content.append(splitted[-1])33 self._updated_content = self._original_content34 super().parse_text(text)35 def _get_parser_updater(self, func):36 """ Return a parser which will replace value field by the function in parameter37 """38 parser = copy.copy(self._parser)39 def pp_look_for_field(x, field):40 if x.resultsName == field:41 return x42 try:43 for v in x:44 res = pp_look_for_field(v, field)45 if res:46 return res47 except:48 return None49 return None50 value_field = pp_look_for_field(parser, 'value')51 value_field.setParseAction(func)52 return parser53 def update_content(self, var, idx=None):54 """ Update a var with his current value55 """56 if var not in self._vars:57 return False58 if self.is_containing_call(var):59 # TODO60 return False61 if idx is None:62 idx = []63 if not isinstance(idx, list):64 idx = [idx]65 i_var_values = 066 for i, line in enumerate(self._updated_content):67 result = self._parser.searchString(line)68 if result:69 if result[0]['var'] == var:70 if not idx or i_var_values in idx:71 parser_updater = self._get_parser_updater(lambda toks: self._vars[var][i_var_values])72 self._updated_content[i] = parser_updater.transformString(line) + '\n'73 i_var_values += 174 return True75 def write_output(self):76 """ Return content with update fields77 """78 return ''.join(self._updated_content)79 def write_file(self, path):80 """ Write content with update fields in a file81 """82 file = open(path, 'w')83 file.write(self.write_output())...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tox 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