Best Python code snippet using slash
stream_cdeps.py
Source:stream_cdeps.py
...72 # Get the resolved stream data variables73 stream_vars[node_name] = None74 for child in self.get_children(root=node):75 datavars = child.xml_element.text.strip()76 datavars = self._resolve_values(case, datavars)77 datavars = self._sub_glc_fields(datavars, case)78 datavars = self._add_xml_delimiter(datavars.split("\n"), "var")79 if stream_vars[node_name]:80 stream_vars[node_name] = stream_vars[node_name] + "\n " + datavars.strip()81 else:82 stream_vars[node_name] = datavars.strip()83 # endif84 elif node_name == 'stream_datafiles':85 # Get the resolved stream data files86 stream_vars[node_name] = ""87 for child in self.get_children(root=node):88 stream_datafiles = child.xml_element.text89 stream_datafiles = self._resolve_values(case, stream_datafiles)90 if 'first_year' in child.xml_element.attrib and 'last_year' in child.xml_element.attrib:91 value = child.xml_element.get('first_year')92 value = self._resolve_values(case, value)93 stream_year_first= int(value)94 value = child.xml_element.get('last_year')95 value = self._resolve_values(case, value)96 stream_year_last = int(value)97 year_first = max(stream_year_first, data_year_first)98 year_last = min(stream_year_last, data_year_last)99 stream_datafiles = self._sub_paths(stream_datafiles, year_first, year_last)100 stream_datafiles = stream_datafiles.strip()101 #endif102 if stream_vars[node_name]:103 stream_vars[node_name] += "\n " + self._add_xml_delimiter(stream_datafiles.split("\n"), "file")104 else:105 stream_vars[node_name] = self._add_xml_delimiter(stream_datafiles.split("\n"), "file")106 elif ( node_name == 'stream_meshfile'107 or node_name == 'stream_mapalgo'108 or node_name == 'stream_tintalgo'109 or node_name == 'stream_taxmode'110 or node_name == 'stream_dtlimit'):111 attributes['model_grid'] = case.get_value("GRID")112 attributes['compset'] = case.get_value("COMPSET")113 value = self._get_value_match(node, node_name[7:], attributes=attributes)114 value = self._resolve_values(case, value)115 value = value.strip()116 stream_vars[node_name] = value117 elif node_name.strip():118 # Get the other dependencies119 stream_dict = self._add_value_to_dict(stream_vars, case, node)120 # append to stream xml file121 stream_file_text = _stream_nuopc_file_template.format(**stream_vars)122 with open(streams_xml_file, 'a') as stream_file:123 stream_file.write(stream_file_text)124 # append to input_data_list125 stream_meshfile = stream_vars['stream_meshfile'].strip()126 self._add_entries_to_inputdata_list(stream_meshfile, stream_datafiles, data_list_file)127 # write close of stream xml file128 with open(streams_xml_file, 'a') as stream_file:129 stream_file.write("</file>\n")130 def _get_stream_first_and_last_dates(self, stream, case):131 """132 Get first and last dates for data for the stream file133 """134 for node in self.get_children(root=stream):135 if node.xml_element.tag == 'stream_year_first':136 data_year_first = node.xml_element.text.strip()137 data_year_first = int(self._resolve_values(case, data_year_first))138 if node.xml_element.tag == 'stream_year_last':139 data_year_last = node.xml_element.text.strip()140 data_year_last = int(self._resolve_values(case, data_year_last))141 return data_year_first, data_year_last142 def _add_entries_to_inputdata_list(self, stream_meshfile, stream_datafiles, data_list_file):143 """144 Appends input data information entries to input data list file145 and writes out the new file146 """147 lines_hash = self._get_input_file_hash(data_list_file)148 with open(data_list_file, 'a') as input_data_list:149 # write out the mesh file separately150 string = "mesh = {}\n".format(stream_meshfile)151 hashValue = hashlib.md5(string.rstrip().encode('utf-8')).hexdigest()152 if hashValue not in lines_hash:153 input_data_list.write(string)154 # now append the stream_datafile entries155 for i, filename in enumerate(stream_datafiles.split("\n")):156 if filename.strip() == '':157 continue158 string = "file{:d} = {}\n".format(i+1, filename)159 hashValue = hashlib.md5(string.rstrip().encode('utf-8')).hexdigest()160 if hashValue not in lines_hash:161 input_data_list.write(string)162 def _get_input_file_hash(self, data_list_file):163 """164 Determine a hash for the input data file165 """166 lines_hash = set()167 if os.path.isfile(data_list_file):168 with open(data_list_file, "r") as input_data_list:169 for line in input_data_list:170 hashValue = hashlib.md5(line.rstrip().encode('utf-8')).hexdigest()171 logger.debug( "Found line {} with hash {}".format(line,hashValue))172 lines_hash.add(hashValue)173 return lines_hash174 def _get_value_match(self, node, child_name, attributes=None, exact_match=False):175 '''176 Get the first best match for multiple tags in child_name based on the177 attributes input178 <values...>179 <value A="a1">X</value>180 <value A="a2">Y</value>181 <value A="a3" B="b1">Z</value>182 </values>183 </values>184 '''185 # Store nodes that match the attributes and their scores.186 matches = []187 nodes = self.get_children(child_name, root=node)188 for vnode in nodes:189 # For each node in the list start a score.190 score = 0191 if attributes:192 for attribute in self.attrib(vnode).keys():193 # For each attribute, add to the score.194 score += 1195 # If some attribute is specified that we don't know about,196 # or the values don't match, it's not a match we want.197 if exact_match:198 if attribute not in attributes or \199 attributes[attribute] != self.get(vnode, attribute):200 score = -1201 break202 else:203 if attribute not in attributes or not \204 re.search(self.get(vnode, attribute),attributes[attribute]):205 score = -1206 break207 # Add valid matches to the list.208 if score >= 0:209 matches.append((score, vnode))210 if not matches:211 return None212 # Get maximum score using either a "last" or "first" match in case of a tie213 max_score = -1214 mnode = None215 for score,node in matches:216 # take the *first* best match217 if score > max_score:218 max_score = score219 mnode = node220 return self.text(mnode)221 def _add_value_to_dict(self, stream_dict, case, node):222 """223 Adds a value to the input stream dictionary needed for the224 stream file output Returns the uppdated stream_dict225 """226 name = node.xml_element.tag227 value = node.xml_element.text228 value = self._resolve_values(case, value)229 stream_dict[name] = value230 return stream_dict231 def _resolve_values(self, case, value):232 """233 Substitues $CASEROOT env_xxx.xml variables if they appear in "value"234 Returns a string235 """236 match = _var_ref_re.search(value)237 while match:238 env_val = case.get_value(match.group('name'))239 expect(env_val is not None,240 "Namelist default for variable {} refers to unknown XML variable {}.".241 format(value, match.group('name')))242 value = value.replace(match.group(0), str(env_val), 1)243 match = _var_ref_re.search(value)244 return value245 def _sub_glc_fields(self, datavars, case):...
test_fixture_resolution.py
Source:test_fixture_resolution.py
...22 s.fixture_store.resolve()23 with s.get_started_context():24 tests = make_runnable_tests(test_something)25 _resolve = functools.partial(s.fixture_store.resolve_name, start_point=tests[0])26 def _resolve_values(path):27 return [v.value for v in _resolve(path).values]28 # check simple resolutions29 assert _resolve('fixture2').info is fixture2.__slash_fixture__30 assert _resolve('fixture2.fixture1').info is fixture1.__slash_fixture__31 # check parameter resolution32 assert _resolve_values('fixture2.fixture1.x') == [1, 2]33 assert _resolve_values('fixture2.x') == [3, 4]34 for invalid_name in ['fixture2.x.y']:35 with pytest.raises(UnknownFixtures):36 _resolve(invalid_name)37def test_resolve_fixture_object_namespace_correctness():38 with slash.Session() as s:39 store = s.fixture_store40 @store.add_fixture41 @slash.fixture42 def global_fixture_1(dependency_fixture):43 pass44 @store.add_fixture45 @slash.fixture46 def dependency_fixture():47 pass...
value.py
Source:value.py
1from types import SimpleNamespace2from src.main.python.de.ctoffer.commons.creational.singleton import singleton, classproperty3@singleton4class Config:5 def __init__(self):6 self._primitive = SimpleNamespace(**{"number": 7})7 @classproperty8 @classmethod9 def instance(cls):10 return None11 @property12 def primitive2(self):13 return self._primitive14class KwargBinding:15 def __init__(self, func):16 self._func_call = func.__call__17 self._func_name = func.__name__18 self._func_doc = func.__doc__19 self._resolve_values = list()20 @property21 def __doc__(self):22 return self._func_doc23 @property24 def __name__(self):25 return self._func_name26 def __call__(self, *args, **kwargs):27 for name, (source, default) in self._resolve_values:28 try:29 kwargs[name] = source()30 except:31 kwargs[name] = default32 self._func_call(*args, **kwargs)33 def __setitem__(self, name, value):34 source, default = value35 self._resolve_values.append((name, (source, default)))36def value(source, target, default=None):37 def outer_wrapper(func):38 if type(func) != KwargBinding:39 binding = KwargBinding(func)40 setattr(func, "__kwarg_binding", binding)41 else:42 binding = func43 binding[target] = (source, default)44 return binding45 return outer_wrapper46@value(source=lambda: Config.instance.primitive2.number, target="number", default=-1)47@value(source=lambda: Config.instance.primitive2.y, target="y", default=-1)48def my_function(a, b, number=None, y=None):49 print("a", a, "b", b, "number", number, y)50def main():51 my_function(7, b=3)52if __name__ == '__main__':...
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!!