How to use some method in Pytest

Best Python code snippet using pytest

TestExprCompletion.py

Source:TestExprCompletion.py Github

copy

Full Screen

1"""2Test the lldb command line completion mechanism for the 'expr' command.3"""4import lldb5from lldbsuite.test.decorators import *6from lldbsuite.test.lldbtest import *7from lldbsuite.test import lldbplatform8from lldbsuite.test import lldbutil9class CommandLineExprCompletionTestCase(TestBase):10 mydir = TestBase.compute_mydir(__file__)11 NO_DEBUG_INFO_TESTCASE = True12 def test_expr_completion(self):13 self.build()14 self.main_source = "main.cpp"15 self.main_source_spec = lldb.SBFileSpec(self.main_source)16 self.createTestTarget()17 # Try the completion before we have a context to complete on.18 self.assume_no_completions('expr some_expr')19 self.assume_no_completions('expr ')20 self.assume_no_completions('expr f')21 (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self,22 '// Break here', self.main_source_spec)23 # Completing member functions24 self.complete_exactly('expr some_expr.FooNoArgs',25 'expr some_expr.FooNoArgsBar()')26 self.complete_exactly('expr some_expr.FooWithArgs',27 'expr some_expr.FooWithArgsBar(')28 self.complete_exactly('expr some_expr.FooWithMultipleArgs',29 'expr some_expr.FooWithMultipleArgsBar(')30 self.complete_exactly('expr some_expr.FooUnderscore',31 'expr some_expr.FooUnderscoreBar_()')32 self.complete_exactly('expr some_expr.FooNumbers',33 'expr some_expr.FooNumbersBar1()')34 self.complete_exactly('expr some_expr.StaticMemberMethod',35 'expr some_expr.StaticMemberMethodBar()')36 # Completing static functions37 self.complete_exactly('expr Expr::StaticMemberMethod',38 'expr Expr::StaticMemberMethodBar()')39 # Completing member variables40 self.complete_exactly('expr some_expr.MemberVariab',41 'expr some_expr.MemberVariableBar')42 # Multiple completions43 self.completions_contain('expr some_expr.',44 ['some_expr.FooNumbersBar1()',45 'some_expr.FooUnderscoreBar_()',46 'some_expr.FooWithArgsBar(',47 'some_expr.MemberVariableBar'])48 self.completions_contain('expr some_expr.Foo',49 ['some_expr.FooNumbersBar1()',50 'some_expr.FooUnderscoreBar_()',51 'some_expr.FooWithArgsBar('])52 self.completions_contain('expr ',53 ['static_cast',54 'reinterpret_cast',55 'dynamic_cast'])56 self.completions_contain('expr 1 + ',57 ['static_cast',58 'reinterpret_cast',59 'dynamic_cast'])60 # Completion expr without spaces61 # This is a bit awkward looking for the user, but that's how62 # the completion API works at the moment.63 self.completions_contain('expr 1+',64 ['1+some_expr', "1+static_cast"])65 # Test with spaces66 self.complete_exactly('expr some_expr .FooNoArgs',67 'expr some_expr .FooNoArgsBar()')68 self.complete_exactly('expr some_expr .FooNoArgs',69 'expr some_expr .FooNoArgsBar()')70 self.complete_exactly('expr some_expr .FooNoArgs',71 'expr some_expr .FooNoArgsBar()')72 self.complete_exactly('expr some_expr. FooNoArgs',73 'expr some_expr. FooNoArgsBar()')74 self.complete_exactly('expr some_expr . FooNoArgs',75 'expr some_expr . FooNoArgsBar()')76 self.complete_exactly('expr Expr :: StaticMemberMethod',77 'expr Expr :: StaticMemberMethodBar()')78 self.complete_exactly('expr Expr ::StaticMemberMethod',79 'expr Expr ::StaticMemberMethodBar()')80 self.complete_exactly('expr Expr:: StaticMemberMethod',81 'expr Expr:: StaticMemberMethodBar()')82 # Test that string literals don't break our parsing logic.83 self.complete_exactly('expr const char *cstr = "some_e"; char c = *cst',84 'expr const char *cstr = "some_e"; char c = *cstr')85 self.complete_exactly('expr const char *cstr = "some_e" ; char c = *cst',86 'expr const char *cstr = "some_e" ; char c = *cstr')87 # Requesting completions inside an incomplete string doesn't provide any88 # completions.89 self.complete_exactly('expr const char *cstr = "some_e',90 'expr const char *cstr = "some_e')91 # Completing inside double dash should do nothing92 self.assume_no_completions('expr -i0 -- some_expr.', 10)93 self.assume_no_completions('expr -i0 -- some_expr.', 11)94 # Test with expr arguments95 self.complete_exactly('expr -i0 -- some_expr .FooNoArgs',96 'expr -i0 -- some_expr .FooNoArgsBar()')97 self.complete_exactly('expr -i0 -- some_expr .FooNoArgs',98 'expr -i0 -- some_expr .FooNoArgsBar()')99 # Addrof and deref100 self.complete_exactly('expr (*(&some_expr)).FooNoArgs',101 'expr (*(&some_expr)).FooNoArgsBar()')102 self.complete_exactly('expr (*(&some_expr)) .FooNoArgs',103 'expr (*(&some_expr)) .FooNoArgsBar()')104 self.complete_exactly('expr (* (&some_expr)) .FooNoArgs',105 'expr (* (&some_expr)) .FooNoArgsBar()')106 self.complete_exactly('expr (* (& some_expr)) .FooNoArgs',107 'expr (* (& some_expr)) .FooNoArgsBar()')108 # Addrof and deref (part 2)109 self.complete_exactly('expr (&some_expr)->FooNoArgs',110 'expr (&some_expr)->FooNoArgsBar()')111 self.complete_exactly('expr (&some_expr) ->FooNoArgs',112 'expr (&some_expr) ->FooNoArgsBar()')113 self.complete_exactly('expr (&some_expr) -> FooNoArgs',114 'expr (&some_expr) -> FooNoArgsBar()')115 self.complete_exactly('expr (&some_expr)-> FooNoArgs',116 'expr (&some_expr)-> FooNoArgsBar()')117 # Builtin arg118 self.complete_exactly('expr static_ca',119 'expr static_cast')120 # From other files121 self.complete_exactly('expr fwd_decl_ptr->Hidden',122 'expr fwd_decl_ptr->HiddenMember')123 # Types124 self.complete_exactly('expr LongClassNa',125 'expr LongClassName')126 self.complete_exactly('expr LongNamespaceName::NestedCla',127 'expr LongNamespaceName::NestedClass')128 # Namespaces129 self.complete_exactly('expr LongNamespaceNa',130 'expr LongNamespaceName::')131 # Multiple arguments132 self.complete_exactly('expr &some_expr + &some_e',133 'expr &some_expr + &some_expr')134 self.complete_exactly('expr SomeLongVarNameWithCapitals + SomeLongVarName',135 'expr SomeLongVarNameWithCapitals + SomeLongVarNameWithCapitals')136 self.complete_exactly('expr SomeIntVar + SomeIntV',137 'expr SomeIntVar + SomeIntVar')138 # Multiple statements139 self.complete_exactly('expr long LocalVariable = 0; LocalVaria',140 'expr long LocalVariable = 0; LocalVariable')141 # Custom Decls142 self.complete_exactly('expr auto l = [](int LeftHandSide, int bx){ return LeftHandS',143 'expr auto l = [](int LeftHandSide, int bx){ return LeftHandSide')144 self.complete_exactly('expr struct LocalStruct { long MemberName; } ; LocalStruct S; S.Mem',145 'expr struct LocalStruct { long MemberName; } ; LocalStruct S; S.MemberName')146 # Completing function call arguments147 self.complete_exactly('expr some_expr.FooWithArgsBar(some_exp',148 'expr some_expr.FooWithArgsBar(some_expr')149 self.complete_exactly('expr some_expr.FooWithArgsBar(SomeIntV',150 'expr some_expr.FooWithArgsBar(SomeIntVar')151 self.complete_exactly('expr some_expr.FooWithMultipleArgsBar(SomeIntVar, SomeIntVa',152 'expr some_expr.FooWithMultipleArgsBar(SomeIntVar, SomeIntVar')153 # Function return values154 self.complete_exactly('expr some_expr.Self().FooNoArgs',155 'expr some_expr.Self().FooNoArgsBar()')156 self.complete_exactly('expr some_expr.Self() .FooNoArgs',157 'expr some_expr.Self() .FooNoArgsBar()')158 self.complete_exactly('expr some_expr.Self(). FooNoArgs',159 'expr some_expr.Self(). FooNoArgsBar()')160 def test_expr_completion_with_descriptions(self):161 self.build()162 self.main_source = "main.cpp"163 self.main_source_spec = lldb.SBFileSpec(self.main_source)164 self.createTestTarget()165 (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self,166 '// Break here', self.main_source_spec)167 self.check_completion_with_desc("expr ", [168 # builtin types have no description.169 ["int", ""],170 ["float", ""],171 # VarDecls have their type as description.172 ["some_expr", "Expr &"],173 ], enforce_order = True)174 self.check_completion_with_desc("expr some_expr.", [175 # Functions have their signature as description.176 ["some_expr.~Expr()", "inline ~Expr()"],177 ["some_expr.operator=(", "inline Expr &operator=(const Expr &)"],178 # FieldDecls have their type as description.179 ["some_expr.MemberVariableBar", "int"],180 ["some_expr.StaticMemberMethodBar()", "static int StaticMemberMethodBar()"],181 ["some_expr.Self()", "Expr &Self()"],182 ["some_expr.FooNoArgsBar()", "int FooNoArgsBar()"],183 ["some_expr.FooWithArgsBar(", "int FooWithArgsBar(int)"],184 ["some_expr.FooNumbersBar1()", "int FooNumbersBar1()"],185 ["some_expr.FooUnderscoreBar_()", "int FooUnderscoreBar_()"],186 ["some_expr.FooWithMultipleArgsBar(", "int FooWithMultipleArgsBar(int, int)"],187 ], enforce_order = True)188 def assume_no_completions(self, str_input, cursor_pos = None):189 interp = self.dbg.GetCommandInterpreter()190 match_strings = lldb.SBStringList()191 if cursor_pos is None:192 cursor_pos = len(str_input)193 num_matches = interp.HandleCompletion(str_input, cursor_pos, 0, -1, match_strings)194 available_completions = []195 for m in match_strings:196 available_completions.append(m)197 self.assertEquals(num_matches, 0, "Got matches, but didn't expect any: " + str(available_completions))198 def completions_contain(self, str_input, items):199 interp = self.dbg.GetCommandInterpreter()200 match_strings = lldb.SBStringList()201 num_matches = interp.HandleCompletion(str_input, len(str_input), 0, -1, match_strings)202 common_match = match_strings.GetStringAtIndex(0)203 for item in items:204 found = False205 for m in match_strings:206 if m == item:207 found = True208 if not found:209 # Transform match_strings to a python list with strings210 available_completions = []211 for m in match_strings:212 available_completions.append(m)...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

1students = []2courses = []3all_lecturer = []4class Student:5 def __init__(self, name, surname, gender):6 self.name = name7 self.surname = surname8 self.gender = gender9 self.finished_courses = []10 self.courses_in_progress = []11 students.append(self)12 self.grades = {}13 courses.append(self.finished_courses)14 courses.append(self.courses_in_progress)15 def grades_hw(self, lecturer, course, grade):16 """Метод выставления оценок от студентов"""17 if isinstance(lecturer, Lecturer) and course in self.courses_in_progress and course in lecturer.courses_attached:18 if course in lecturer.rating_grades:19 lecturer.rating_grades[course] += [grade]20 else:21 lecturer.rating_grades[course] = [grade]22 else:23 return 'Ошибка'24 def __str__(self):25 information = '\nStudent ' + '\nИмя: ' + self.name + '\nФамилия: ' + self.surname26 information += '\nСредняя оценка за домашние задания: ' + average_grade(self.grades)27 information += '\nКурсы в процессе изучения: ' + (','.join(self.courses_in_progress))28 information += '\nЗавершенные курсы: ' + (', '.join(self.finished_courses))29 return information30 def __lt__(self, other):31 if average_grade(self.grades) < average_grade(other.grades):32 return 'Лучший результат ' + other.name + ' ' + other.surname + ' с рейтингом ' +\33 average_grade(other.grades)34 elif average_grade(self.grades) == average_grade(other.grades):35 return 'Такой же результат'36 else:37 return 'Лучший результат ' + self.name + ' ' + self.surname + ' с рейтингом ' +\38 average_grade(self.grades)39class Mentor:40 def __init__(self, name, surname):41 self.name = name42 self.surname = surname43 self.courses_attached = []44 def __repr__(self): # это как и __str__ для вывода45 return self.name + ' ' + self.surname + ' Курс: ' + repr(self.courses_attached)46class Lecturer(Mentor):47 def __init__(self, name, surname):48 super().__init__(name, surname)49 self.rating_grades = {}50 all_lecturer.append(self)51 def __str__(self):52 information = '\nЛектор' + '\nИмя: ' + self.name + '\nФамилия: ' + self.surname53 information += '\nСредняя оценка за лекцию: ' + average_grade(self.rating_grades)54 return information55 def __lt__(self, other):56 if average_grade(self.rating_grades) < average_grade(other.rating_grades):57 return 'Лучший результат ' + other.name + ' ' + other.surname + ' с рейтингом ' +\58 average_grade(other.rating_grades)59 elif average_grade(self.rating_grades) == average_grade(other.rating_grades):60 return 'Такой же результат'61 else:62 return 'Лучший результат ' + self.name + ' ' + self.surname + ' с рейтингом ' + \63 average_grade(self.rating_grades)64class Reviewer(Mentor):65 """выставлять студентам оценки за домашние задания"""66 def rate_hw(self, student, course, grade):67 if isinstance(student, Student) and course in self.courses_attached and course in student.courses_in_progress:68 if course in student.grades:69 student.grades[course] += [grade]70 else:71 student.grades[course] = [grade]72 else:73 return 'Ошибка'74 def __str__(self):75 information = '\nПроверяющий' + '\nИмя: ' + self.name + '\nФамилия: ' + self.surname76 return information77def average_grade(about_grades):78 """ Поиск среднего значения оценки """79 all_grades = []80 for subject, grades in about_grades.items():81 for grade in grades:82 all_grades.append(grade)83 if len(all_grades) == 0:84 av_grade = 085 return str(av_grade)86 elif len(all_grades) > 0:87 av_grade = round((sum(all_grades) / len(all_grades)), 1)88 return str(av_grade)89 else:90 return "Ошибка"91def average_course(course, lists):92 """среднюю оценку всех студентов по выбранному курсу"""93 grade = []94 for value in lists:95 if course in (sum(courses, [])):96 if course in value.grades:97 for x, y in value.grades.items():98 if course == x:99 grade.extend(y)100 elif course != x:101 continue102 else:103 return f"Курса {course} нет"104 if len(grade) != 0:105 result = round((sum(grade) / len(grade)), 1)106 return f"Средняя оценка по курсу {course}: {str(result)}"107 elif len(grade) == 0:108 return f"По курсу {course} нет оценок"109 else:110 return 'Неверное значение'111def lecturer_average_grade(course, lists):112 lect_av_grade = []113 for value in lists:114 if course in (sum(courses, [])):115 if course in value.rating_grades:116 for x, y in value.rating_grades.items():117 if course == x:118 lect_av_grade.append(y)119 elif course != x:120 continue121 else:122 return f"Курса {course} нет"123 if len(lect_av_grade) != 0:124 result = round((sum(sum(lect_av_grade, [])) / len(sum(lect_av_grade, []))), 1)125 return f"Средняя оценка по курсу {course}: {str(result)}"126 elif len(lect_av_grade) == 0:127 return f"По курсу {course} нет оценок"128 else:129 return 'Неверное значение'130best_student = Student('Ruoy', 'Eman', 'm')131some_student = Student('Gena', 'Ivanov', 'm')132best_lecturer = Lecturer('Petr', 'Krugov')133some_lecturer = Lecturer('Dmitry', 'Zhuk')134cool_reviewer = Reviewer('Some', 'Buddy')135some_reviewer = Reviewer('Chack', 'Firsov')136best_student.courses_in_progress += ['Python', 'GIT', 'Java', 'HTML']137some_student.courses_in_progress += ['Python', 'GIT', 'C++', 'HTML']138some_lecturer.courses_attached += ['Python', 'GIT', 'C#', 'HTML']139best_lecturer.courses_attached += ['Python', 'GIT', 'CSS', 'C++', 'HTML']140some_reviewer.courses_attached += ['Python', 'GIT', 'CSS', 'C++']141cool_reviewer.courses_attached += ['Python', 'CSS', 'HTML']142some_student.grades_hw(some_lecturer, 'Python', 9)143some_student.grades_hw(best_lecturer, 'Python', 10)144best_student.grades_hw(some_lecturer, 'Python', 10)145best_student.grades_hw(some_lecturer, 'C++', 10)146best_student.grades_hw(some_lecturer, 'GIT', 9)147some_student.grades_hw(best_lecturer, 'HTML', 7)148some_student.finished_courses += ['HTML', 'notepad']149best_student.finished_courses += ['HTML', 'C++', 'SQL']150cool_reviewer.rate_hw(best_student, 'Python', 10)151cool_reviewer.rate_hw(best_student, 'Python', 10)152cool_reviewer.rate_hw(best_student, 'Python', 9)153some_reviewer.rate_hw(some_student, 'Python', 9)154some_reviewer.rate_hw(some_student, 'Python', 8)155cool_reviewer.rate_hw(some_student, 'HTML', 5)156cool_reviewer.rate_hw(best_student, 'HTML', 6)157cool_reviewer.rate_hw(some_student, 'C++', 7)158some_reviewer.rate_hw(some_student, 'C++', 9)159some_reviewer.rate_hw(best_student, 'GIT', 7)160print(f"{some_lecturer.name} {some_lecturer.surname} рейтинг: ", average_grade(some_lecturer.rating_grades))161print(cool_reviewer)162print(repr(cool_reviewer))163print(some_lecturer)164print(some_lecturer.rating_grades)165print(best_student)166print(some_student)167print(average_course('HTML', students))168print(average_course('Python', students))169print(average_course('1C', students))170print(average_course('GIT', students))171print(average_course('C++', students))172print(lecturer_average_grade('HTML', all_lecturer))173print(lecturer_average_grade('Python', all_lecturer))174print(lecturer_average_grade('CSS', all_lecturer))175print(lecturer_average_grade('C++', all_lecturer))176print(repr(cool_reviewer))177print(cool_reviewer)178print(best_student.__lt__(some_student))179print(best_lecturer.__lt__(best_lecturer))180print(best_lecturer.__lt__(some_lecturer))181print(best_student > some_student)182print(best_lecturer < some_lecturer)...

Full Screen

Full Screen

ingest_transform_routines.py

Source:ingest_transform_routines.py Github

copy

Full Screen

1#!/usr/bin/env python2# -*- coding: UTF-8 -*-3import re4from datetime import datetime5import textacy6from bs4 import BeautifulSoup7from datadict import FindCountryCode8from datadict import FindGeo9from datadict import FindLearningPattern10_geo_finder = FindGeo()11_country_code_finder = FindCountryCode()12_learning_pattern = FindLearningPattern()13class IngestTransformRoutines(object):14 """ Transformation Routines """15 @staticmethod16 def job_role_id(some_value: str) -> str:17 """18 cleanse all the various permutations of Job Role ID19 Updated:20 abhbasu3@in.ibm.com21 Purpose: added bands 7a/7b and 6a/6b to be treated as 7 and 622 <https://github.ibm.com/GTS-CDO/unstructured-analytics/issues/652>23 :param some_value:24 :return:25 Job Role ID26 """27 some_value = some_value.replace("'", "")28 if some_value.endswith(".0"):29 some_value = some_value.split(".")[0].strip()30 if some_value.startswith("0") and len(some_value) == 6:31 return some_value[1:]32 return some_value33 @staticmethod34 def band_level(some_value: str):35 some_value = some_value.lower()36 if some_value == "d":37 return 1138 if some_value == "c":39 return 1240 if some_value == "b":41 return 1342 if some_value == "a":43 return 1444 if some_value == "aa":45 return 1546 if bool(re.search('6[a-zA-Z]', some_value)):47 return 648 if bool(re.search('7[a-zA-Z]', some_value)):49 return 750 try:51 return int(some_value)52 except ValueError:53 print("Invalid Band Level Transformation: {}".format(some_value))54 return None55 @staticmethod56 def country_code_lookup(some_value: str):57 return _country_code_finder.find_by_code(some_value)58 @staticmethod59 def country_to_region(some_value: str):60 return _geo_finder.find_region_by_country(some_value)61 @staticmethod62 def cleanse_client_name(some_value: str):63 _l_known_unknowns = [64 "blocked from view",65 "multicommercial",66 "multi commercial",67 "confidential",68 "multiple accounts",69 "legal & general",70 "multi - commercial",71 "nan"]72 _d_replace = {73 "a t & t": "at&t",74 "!bm": "ibm"}75 _d_contains = {76 "ibm": "ibm",77 "global delivery": "ibm",78 "confidential": "unknown",79 "so delivery": "ibm"}80 some_value = some_value.lower().strip()81 for value in _l_known_unknowns:82 if some_value == value:83 return "unknown"84 for key in _d_contains:85 if key in some_value:86 return _d_contains[key]87 for key in _d_replace:88 if key in some_value:89 some_value = some_value.replace(key, _d_replace[key])90 return some_value91 @staticmethod92 def tag_list(some_value: str):93 tokens = some_value.split(",")94 tokens = [x.lower().strip() for x in tokens if x and len(x)]95 if not tokens or not len(tokens):96 return None97 return tokens98 @staticmethod99 def badge_name(some_value: str) -> str:100 if "Level III" in some_value:101 return some_value.replace("Level III", "Level 3")102 elif "Level II" in some_value:103 return some_value.replace("Level II", "Level 2")104 elif "Level I" in some_value:105 return some_value.replace("Level I", "Level 1")106 return some_value107 @staticmethod108 def region_lookup(some_value: str) -> str:109 if "NAN" == some_value.upper():110 return "na"111 return some_value.lower()112 @staticmethod113 def city_normalizer(some_value: str) -> str:114 return _geo_finder.normalize_city(some_value, search_in_str=True)115 @staticmethod116 def populate_empty_month(some_value: str or None) -> int:117 def has_value() -> bool:118 if not some_value:119 return False120 if some_value.strip().lower() == "none":121 return False122 return True123 if has_value():124 return some_value125 return datetime.now().month126 @staticmethod127 def populate_empty_year(some_value: str or None) -> int:128 def has_value() -> bool:129 if not some_value:130 return False131 if some_value.strip().lower() == "none":132 return False133 return True134 if has_value():135 return some_value136 return datetime.now().year137 @staticmethod138 def normalize_month(some_value: str) -> int:139 try:140 return int(some_value)141 except ValueError:142 print(f"Invalid Month: {some_value}")143 return -1144 @staticmethod145 def normalize_year(some_value: str) -> int:146 try:147 return int(some_value)148 except ValueError:149 print(f"Invalid Year: {some_value}")150 return -1151 @staticmethod152 def geo_preprocessor(some_value: str) -> str:153 return textacy.preprocess_text(some_value,154 # fix_unicode=True, # 20-May-2019 causes error155 lowercase=True,156 no_urls=True,157 no_emails=True,158 no_phone_numbers=True,159 no_numbers=True,160 no_currency_symbols=True,161 no_punct=True,162 no_contractions=True,163 no_accents=True)164 @staticmethod165 def textacy_preprocess(some_value: str) -> str:166 return textacy.preprocess_text(some_value,167 # fix_unicode=True, # 20-May-2019 causes error168 lowercase=False,169 no_urls=False,170 no_emails=False,171 no_phone_numbers=False,172 no_numbers=False,173 no_currency_symbols=False,174 no_punct=True,175 no_contractions=False,176 no_accents=True)177 @staticmethod178 def remove_double_quotes(some_value: str) -> str:179 return some_value.replace('"', '')180 @staticmethod181 def to_boolean(some_value: str) -> bool:182 if type(some_value) == int:183 return some_value != 0184 if type(some_value) == str:185 return str(some_value).lower().strip().startswith("y")186 return bool(some_value)187 @staticmethod188 def to_bool(some_value: str) -> bool:189 return IngestTransformRoutines.to_boolean(some_value)190 @staticmethod191 def to_int(some_value: str) -> int or str:192 try:193 return int(some_value)194 except ValueError:195 return some_value196 @staticmethod197 def simple_date(some_value: str) -> str:198 """199 :param some_value:200 assume input: 2017-07-06 02:24:55201 :return:202 return output: 2017-07-06203 """204 if " " in some_value:205 return some_value.split(" ")[0].strip()206 return some_value207 @staticmethod208 def remove_html(some_value: str) -> str:209 """210 :param some_value:211 some value with HTML212 :return:213 stripped HTML214 """215 if "<" not in some_value:216 return some_value217 some_value = some_value.replace("<", " <")218 some_value = some_value.replace(">", "> ")219 return BeautifulSoup(some_value,220 features="html.parser").get_text()221 @staticmethod222 def learning_noise(input_text: str,223 is_debug: bool = False) -> str:224 """225 :param input_text:226 :param is_debug:227 :return:228 """229 normalized = _learning_pattern.remove_noise(input_text)230 if is_debug and normalized != input_text:231 print("\n".join([232 f"Identified Noise Pattern",233 f"\tOriginal Text: {input_text}",234 f"\tNormalized Text: {normalized}"]))235 return normalized236 @staticmethod237 def open_seats_status(some_value: str) -> str:238 """239 Purpose:240 transform a numeric value into an understandable text form241 Created:242 17-Apr-2019243 craig.trim@ibm.com244 * reference:245 https://github.ibm.com/GTS-CDO/unstructured-analytics/issues/50#issuecomment-10801932246 :param some_value:247 :return:248 a string value249 """250 some_value = int(some_value)251 if some_value == 1:252 return "open"253 elif some_value == 2:254 return "draft"255 elif some_value == 3:256 return "withdrawn"257 elif some_value == 4:...

Full Screen

Full Screen

test_registry.py

Source:test_registry.py Github

copy

Full Screen

1import pytest2from awxkit.api.registry import URLRegistry3class One(object):4 pass5class Two(object):6 pass7@pytest.fixture8def reg():9 return URLRegistry()10def test_url_pattern(reg):11 desired = r'^/some/resources/\d+/(\?.*)*$'12 assert reg.url_pattern(r'/some/resources/\d+/').pattern == desired13def test_methodless_get_from_empty_registry(reg):14 assert reg.get('nonexistent') is None15def test_method_get_from_empty_registry(reg):16 assert reg.get('nonexistent', 'method') is None17def test_methodless_setdefault_methodless_get(reg):18 reg.setdefault(One)19 assert reg.get('some_path') is One20def test_methodless_setdefault_method_get(reg):21 reg.setdefault(One)22 assert reg.get('some_path', 'method') is One23def test_method_setdefault_methodless_get(reg):24 reg.setdefault('method', One)25 assert reg.get('some_path') is None26def test_method_setdefault_matching_method_get(reg):27 reg.setdefault('method', One)28 assert reg.get('some_path', 'method') is One29def test_method_setdefault_nonmatching_method_get(reg):30 reg.setdefault('method', One)31 assert reg.get('some_path', 'nonexistent') is None32def test_multimethod_setdefault_matching_method_get(reg):33 reg.setdefault(('method_one', 'method_two'), One)34 assert reg.get('some_path', 'method_one') is One35 assert reg.get('some_path', 'method_two') is One36def test_multimethod_setdefault_nonmatching_method_get(reg):37 reg.setdefault(('method_one', 'method_two'), One)38 assert reg.get('some_path') is None39 assert reg.get('some_path', 'nonexistent') is None40def test_wildcard_setdefault_methodless_get(reg):41 reg.setdefault('.*', One)42 assert reg.get('some_path') is One43def test_wildcard_setdefault_method_get(reg):44 reg.setdefault('.*', One)45 assert reg.get('some_path', 'method') is One46def test_regex_method_setdefaults_over_wildcard_method_get(reg):47 reg.setdefault('.*', One)48 reg.setdefault('reg.*ex', Two)49 for _ in range(1000):50 assert reg.get('some_path', 'regex') is Two51def test_methodless_registration_with_matching_path_methodless_get(reg):52 reg.register('some_path', One)53 assert reg.get('some_path') is One54def test_methodless_registraion_with_nonmatching_path_methodless_get(reg):55 reg.register('some_path', One)56 assert reg.get('nonexistent') is None57def test_methodless_registration_with_matching_path_nonmatching_method_get(reg):58 reg.register('some_path', One)59 assert reg.get('some_path', 'method') is None60def test_method_registration_with_matching_path_matching_method_get(reg):61 reg.register('some_path', 'method', One)62 assert reg.get('some_path', 'method') is One63def test_method_registration_with_matching_path_nonmatching_method_get(reg):64 reg.register('some_path', 'method_one', One)65 assert reg.get('some_path', 'method_two') is None66def test_multimethod_registration_with_matching_path_matching_method_get(reg):67 reg.register('some_path', ('method_one', 'method_two'), One)68 assert reg.get('some_path', 'method_one') is One69 assert reg.get('some_path', 'method_two') is One70def test_multimethod_registration_with_path_matching_method_get(reg):71 reg.register('some_path', ('method_one', 'method_two'), One)72 assert reg.get('some_path', 'method_three') is None73def test_multipath_methodless_registration_with_matching_path_methodless_get(reg):74 reg.register(('some_path_one', 'some_path_two'), One)75 assert reg.get('some_path_one') is One76 assert reg.get('some_path_two') is One77def test_multipath_methodless_registration_with_matching_path_nonmatching_method_get(reg):78 reg.register(('some_path_one', 'some_path_two'), One)79 assert reg.get('some_path_one', 'method') is None80 assert reg.get('some_path_two', 'method') is None81def test_multipath_method_registration_with_matching_path_matching_method_get(reg):82 reg.register((('some_path_one', 'method_one'), ('some_path_two', 'method_two')), One)83 assert reg.get('some_path_one', 'method_one') is One84 assert reg.get('some_path_two', 'method_two') is One85def test_multipath_partial_method_registration_with_matching_path_matching_method_get(reg):86 reg.register(('some_path_one', ('some_path_two', 'method')), One)87 assert reg.get('some_path_one') is One88 assert reg.get('some_path_two', 'method') is One89def test_wildcard_method_registration_with_methodless_get(reg):90 reg.register('some_path', '.*', One)91 assert reg.get('some_path') is One92def test_wildcard_method_registration_with_method_get(reg):93 reg.register('some_path', '.*', One)94 assert reg.get('some_path', 'method') is One95def test_wildcard_and_specific_method_registration_acts_as_default(reg):96 reg.register('some_path', 'method_one', Two)97 reg.register('some_path', '.*', One)98 reg.register('some_path', 'method_two', Two)99 for _ in range(1000): # eliminate overt randomness100 assert reg.get('some_path', 'nonexistent') is One101 assert reg.get('some_path', 'method_one') is Two102 assert reg.get('some_path', 'method_two') is Two103@pytest.mark.parametrize('method', ('method', '.*'))104def test_multiple_method_registrations_disallowed_for_single_path_single_registration(reg, method):105 with pytest.raises(TypeError) as e:106 reg.register((('some_path', method), ('some_path', method)), One)107 assert str(e.value) == ('"{0.pattern}" already has registered method "{1}"'108 .format(reg.url_pattern('some_path'), method))109@pytest.mark.parametrize('method', ('method', '.*'))110def test_multiple_method_registrations_disallowed_for_single_path_multiple_registrations(reg, method):111 reg.register('some_path', method, One)112 with pytest.raises(TypeError) as e:113 reg.register('some_path', method, One)114 assert str(e.value) == ('"{0.pattern}" already has registered method "{1}"'115 .format(reg.url_pattern('some_path'), method))116def test_paths_can_be_patterns(reg):117 reg.register('.*pattern.*', One)118 assert reg.get('XYZpattern123') is One119def test_mixed_form_single_registration(reg):120 reg.register([('some_path_one', 'method_one'),121 'some_path_two',122 ('some_path_three', ('method_two', 'method_three')),123 'some_path_four', 'some_path_five'], One)124 assert reg.get('some_path_one', 'method_one') is One125 assert reg.get('some_path_one') is None126 assert reg.get('some_path_one', 'nonexistent') is None127 assert reg.get('some_path_two') is One128 assert reg.get('some_path_two', 'nonexistent') is None129 assert reg.get('some_path_three', 'method_two') is One130 assert reg.get('some_path_three', 'method_three') is One131 assert reg.get('some_path_three') is None132 assert reg.get('some_path_three', 'nonexistent') is None133 assert reg.get('some_path_four') is One134 assert reg.get('some_path_four', 'nonexistent') is None135 assert reg.get('some_path_five') is One136 assert reg.get('some_path_five', 'nonexistent') is None137def test_mixed_form_single_registration_with_methodless_default(reg):138 reg.setdefault(One)139 reg.register([('some_path_one', 'method_one'),140 'some_path_two',141 ('some_path_three', ('method_two', 'method_three')),142 'some_path_four', 'some_path_five'], Two)143 assert reg.get('some_path_one', 'method_one') is Two144 assert reg.get('some_path_one') is One145 assert reg.get('some_path_one', 'nonexistent') is One146 assert reg.get('some_path_two') is Two147 assert reg.get('some_path_two', 'nonexistent') is One148 assert reg.get('some_path_three', 'method_two') is Two149 assert reg.get('some_path_three', 'method_three') is Two150 assert reg.get('some_path_three') is One151 assert reg.get('some_path_three', 'nonexistent') is One152 assert reg.get('some_path_four') is Two153 assert reg.get('some_path_four', 'nonexistent') is One154 assert reg.get('some_path_five') is Two155 assert reg.get('some_path_five', 'nonexistent') is One156def test_mixed_form_single_registration_with_method_default(reg):157 reg.setdefault('existent', One)158 reg.register([('some_path_one', 'method_one'),159 'some_path_two',160 ('some_path_three', ('method_two', 'method_three')),161 'some_path_four', 'some_path_five'], Two)162 assert reg.get('some_path_one', 'method_one') is Two163 assert reg.get('some_path_one') is None164 assert reg.get('some_path_one', 'existent') is One165 assert reg.get('some_path_one', 'nonexistent') is None166 assert reg.get('some_path_two') is Two167 assert reg.get('some_path_two', 'existent') is One168 assert reg.get('some_path_two', 'nonexistent') is None169 assert reg.get('some_path_three', 'method_two') is Two170 assert reg.get('some_path_three', 'method_three') is Two171 assert reg.get('some_path_three') is None172 assert reg.get('some_path_three', 'existent') is One173 assert reg.get('some_path_three', 'nonexistent') is None174 assert reg.get('some_path_four') is Two175 assert reg.get('some_path_four', 'existent') is One176 assert reg.get('some_path_four', 'nonexistent') is None177 assert reg.get('some_path_five') is Two178 assert reg.get('some_path_five', 'existent') is One...

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