Best Python code snippet using autotest_python
csv.py
Source:csv.py
1#-*- coding: utf-8 -*-2# csv.py (c)2021, 2022 Henrique Moreira3"""4csv-based table5"""6# pylint: disable=missing-function-docstring7from zson.zobject import ZObject, simpler_ascii8ENCODINGS = {9 "latin-1": "ISO-8859-1",10}11TILDE = "~"12class BareTable(ZObject):13 """ Abstract basic table. """14 def __init__(self, info, encoding):15 super().__init__(info, encoding)16 self._header_string = ""17 def header_string(self) -> str:18 assert isinstance(self._header_string, str)19 return self._header_string20class CSV(BareTable):21 """ CSV-based table22 """23 _default_split = ","24 def __init__(self, info=None, encoding="utf-8"):25 """ Initializer: data should be a dictionary or a list.26 """27 self._split = CSV._default_split28 super().__init__(info, encoding)29 assert isinstance(self._table, (list, dict))30 def header(self) -> list:31 """ Returns the header fields, as a list. """32 astr = self._header_string.lstrip("#")33 if self._auto_head:34 astr = simpler_ascii(astr)35 if not astr:36 return []37 return self._to_row(astr.split(self._split))38 def rework_header(self, new_fields:list):39 oldlen = len(self.header())40 self._header_string = self._default_split.join(new_fields)41 return oldlen == len(self.header())42 def convert(self, obj) -> bool:43 """ Converts from another object """44 try:45 cont = obj.get()46 except AttributeError:47 cont = None48 if not cont:49 return self._from_object(obj)50 self._table = cont51 return True52 def load(self, path:str, header:str="a", split_chr=None) -> bool:53 """ Loads content from file, at 'path'. """54 if split_chr is not None:55 self._split = split_chr56 self._table = []57 try:58 with open(path, "r", encoding=self._encoding) as fdin:59 data = fdin.read()60 except FileNotFoundError:61 return False62 return self._from_data(data, header)63 def save(self, path:str) -> bool:64 """ Save content to a file, at 'path'. """65 astr = self._to_csv()66 try:67 with open(path, "w", encoding=self._encoding) as fdout:68 fdout.write(astr)69 except FileNotFoundError:70 return False71 return True72 def dump(self) -> str:73 """ Returns the json equivalent to this table. """74 return self.dumps(self._table)75 def dump_json(self, key=None, key_split=None) -> str:76 """ Shows dictionary with key,77 or just the header() as key.78 """79 achr = self._split if key_split is None else key_split80 if key is None:81 if achr and achr < " ":82 # Assume a semi-colon, instead of a tab (for a better json output!)83 assert achr == "\t", f"Not a tab?, ASCII={ord(achr[0])}d"84 achr = ";"85 keystr = achr.join(self.header())86 else:87 assert isinstance(key, str)88 assert not key_split, "'key_split' only when 'key' is specified"89 keystr = key90 return self.dumps(self._table, keystr)91 def dump_json_string(self):92 """ Returns the basic json list (string). """93 return self._dump_json_string(self._table)94 def rows(self):95 """ Returns the generator object for the table. """96 assert isinstance(self._table, list)97 for row in self._table:98 yield row99 def _from_data(self, data:str, header:str) -> bool:100 """ Read table from data string. """101 this = []102 lines = data.splitlines()103 self._header_string = ""104 assert header in (105 "a", # automatic106 "n", # no header107 "1", # 1-line header108 )109 if not lines:110 return True111 has_head = header == "1" or lines[0].startswith("#")112 if has_head:113 head, tail = lines[0], lines[1:]114 else:115 head, tail = "", lines116 self._header_string = head117 for line in tail:118 this = self._to_row(line.split(self._split))119 self._table.append(this)120 return True121 def _to_row(self, alist:list) -> list:122 """ Replaces '~' by ',' """123 if not alist:124 return []125 return [astr.replace(TILDE, self._split) for astr in alist]126 def _from_row(self, alist:list) -> list:127 """ Replaces ',' by '~' """128 if not alist:129 return []130 return [astr.replace(self._split, TILDE) for astr in alist]131 def _to_csv(self) -> str:132 """ Returns the csv string for the content. """133 astr = self._header_string134 if astr:135 astr += "\n"136 return astr + self._csv_payload()137 def _csv_payload(self) -> str:138 astr = ""139 for line in self._table:140 if isinstance(line, (list, tuple)):141 entry = line142 elif isinstance(line, dict):143 entry = [line[key] for key in sorted(line)]144 else:145 entry = [line]146 row = self._split.join(self._from_row(entry))147 astr += row + "\n"148 return astr149 def _from_object(self, obj) -> bool:150 """ Converts from object. """151 self._header_string = ""152 if isinstance(obj, (list, tuple)):153 self._table = obj154 return True155 if isinstance(obj, str):156 self._header_string = obj157 return True158 return False159 def __str__(self) -> str:160 return self._csv_payload()161 def __repr__(self) -> str:162 return self.dump_json()163 @staticmethod164 def set_separator(split_chr:str=","):165 assert split_chr166 assert isinstance(split_chr, str)167 CSV._default_split = split_chr168 @staticmethod169 def set_tab_separator():170 CSV._default_split = "\t"171# Main script172if __name__ == "__main__":...
csv_encoder.py
Source:csv_encoder.py
...39 for group in self._response['groups']:40 total_index = self._total_index(group, self._num_columns)41 value_table[total_index] = self._group_string(group)42 return value_table43 def _header_string(self, header_value):44 return '/'.join(header_value)45 def _process_value_table(self, value_table, row_headers):46 total_index = 047 for row_index in xrange(self._num_rows):48 row_header = self._header_string(row_headers[row_index])49 row_end_index = total_index + self._num_columns50 row_values = value_table[total_index:row_end_index]51 self._append_output_row([row_header] + row_values)52 total_index += self._num_columns53 def encode(self):54 header_values = self._response['header_values']55 assert len(header_values) == 256 row_headers, column_headers = header_values57 self._num_rows, self._num_columns = (len(row_headers),58 len(column_headers))59 value_table = self._build_value_table()60 first_line = [''] + [self._header_string(header_value)61 for header_value in column_headers]62 self._append_output_row(first_line)63 self._process_value_table(value_table, row_headers)64 return self._build_response()65class TableCsvEncoder(CsvEncoder):66 def __init__(self, request, response):67 super(TableCsvEncoder, self).__init__(request, response)68 self._column_specs = request['columns']69 def _format_row(self, row_object):70 """Extract data from a row object into a list of strings"""71 return [row_object.get(field) for field, name in self._column_specs]72 def _encode_table(self, row_objects):73 self._append_output_row([column_spec[1] # header row74 for column_spec in self._column_specs])...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!