Best Python code snippet using sure_python
generic.py
Source:generic.py  
...13    "Return True for values that diff should treat as a single atomic value."14    return not isinstance(x, (str, list, dict))15def default_predicates():16    return defaultdict(lambda: (operator.__eq__,))17def default_differs():18    return defaultdict(lambda: diff)19def compare_strings_approximate(x, y, threshold=0.7, maxlen=None):20    "Compare to strings with approximate heuristics."21    # TODO: Add configuration framework22    # TODO: Tune threshold with realistic sources23    # Fast cutoff when one is empty24    if bool(x) != bool(y):25        return False26    # Cutoff on equality: Python has fast hash functions for strings,27    # and lists of strings also works fine28    if len(x) == len(y) and x == y:29        return True30    # TODO: Investigate performance and quality of this difflib ratio approach,31    # possibly one of the weakest links of the notebook diffing algorithm.32    # Alternatives to try are the libraries diff-patch-match and Levenschtein33    # Informal benchmark normalized to operator ==:34    #    1.0  operator ==35    #  438.2  real_quick_ratio36    #  796.5  quick_ratio37    # 3088.2  ratio38    # The == cutoff will hit most of the time for long runs of39    # equal items, at least in the Myers diff algorithm.40    # Most other comparisons will likely not be very similar,41    # and the (real_)quick_ratio cutoffs will speed up those.42    # So the heavy ratio function is only used for close calls.43    # s = difflib.SequenceMatcher(lambda c: c in (" ", "\t"), x, y, autojunk=False)44    s = difflib.SequenceMatcher(None, x, y, autojunk=False)45    # Use only the fast ratio approximations first46    if s.real_quick_ratio() < threshold:47        return False48    if s.quick_ratio() < threshold:49        return False50    if maxlen is not None and len(x) > maxlen and len(y) > maxlen:51        # We know from above that there is not an exact similarity52        return False53    return s.ratio() > threshold54def diff(a, b, path="", predicates=None, differs=None):55    "Compute the diff of two json-like objects, list or dict or string."56    if predicates is None:57        predicates = default_predicates()58    if differs is None:59        differs = default_differs()60    if isinstance(a, list) and isinstance(b, list):61        d = diff_lists(a, b, path=path, predicates=predicates, differs=differs)62    elif isinstance(a, dict) and isinstance(b, dict):63        d = diff_dicts(a, b, path=path, predicates=predicates, differs=differs)64    elif isinstance(a, str) and isinstance(b, str):65        # Don't pass differs/predicates as the only possible use case is to66        # use a different character differ within each line or predicates67        # for comparing lines68        d = diff_strings_linewise(a, b)69    else:70        raise RuntimeError("Can currently only diff list, dict, or str objects.")71    # We can turn this off for performance after the library has been well tested:72    validate_diff(d)73    return d74def diff_sequence_multilevel(a, b, path="", predicates=None, differs=None):75    """Compute diff of two lists with configurable behaviour."""76    if predicates is None:77        predicates = default_predicates()78    if differs is None:79        differs = default_differs()80    # Invoke multilevel snake computation algorithm81    compares = predicates[path or '/']82    snakes = compute_snakes_multilevel(a, b, compares)83    # Convert snakes to diff84    return compute_diff_from_snakes(a, b, snakes, path=path, predicates=predicates, differs=differs)85def diff_lists(a, b, path="", predicates=None, differs=None, shallow_diff=None):86    """Compute diff of two lists with configurable behaviour."""87    if predicates is None:88        predicates = default_predicates()89    if differs is None:90        differs = default_differs()91    # If multiple compares are provided to this path, delegate to multilevel algorithm92    compares = predicates[path or '/']93    if len(compares) > 1:94        assert shallow_diff is None95        return diff_sequence_multilevel(a, b, path=path, predicates=predicates, differs=differs)96    # First make a shallow sequence diff with custom compare,97    # unless it's provided for us98    if shallow_diff is None:99        shallow_diff = diff_sequence(a, b, compares[0])100    # Next we recurse to diff items in sequence that are considered101    # similar by compares[0] in the loop below102    subpath = "/".join((path, "*"))103    diffit = differs[subpath]104    # Count consumed items i,j from a,b, (i="take" in patch_list)105    i, j = 0, 0106    di = SequenceDiffBuilder()107    M = len(shallow_diff)108    for ie in range(M+1):109        if ie < M:110            # Consume n more unmentioned items before this diff entry111            # Note that index can be larger than i in the case where items112            # have been deleted from a and then insertions from b occur.113            e = shallow_diff[ie]114            index = e.key115            n = max(0, index - i)116            askip, bskip = count_consumed_symbols(e)117        else:118            # Consume final items after the last diff entry119            e = None120            n = len(a) - i121            askip, bskip = 0, 0122            assert n >= 0, "Sanity check failed: Cannot have negative remaining entries"123            assert len(b) - j == n, "Sanity check failed: Base/remote indexing mismatch"124        # Recursively diff the n items that have been deemed similar125        for k in range(n):126            aval = a[i + k]127            bval = b[j + k]128            if not is_atomic(aval):129                cd = diffit(aval, bval, path=subpath, predicates=predicates, differs=differs)130                if cd:131                    di.patch(i + k, cd)  # FIXME: Not covered in tests, create test situation132        # Keep count of consumed items133        i += n + askip134        j += n + bskip135        # Insert the diff entry from shallow diff unless past the end136        # (this either adds or removes items)137        if ie < M:138            di.append(e)139    # Sanity check140    assert i == len(a), "Sanity check failed: Did not process all entries in a"141    assert j == len(b), "Sanity check failed: Did not process all entries in b"142    return di.validated()143def diff_dicts(a, b, path="", predicates=None, differs=None):144    """Compute diff of two dicts with configurable behaviour.145    Keys in both a and b will be handled based on146    Make a one-level diff of dicts a and b, using given compare147    operator to specify which items are considered the same.148    Items not mentioned in diff are items where compare(x, y) return True.149    For other items the diff will contain delete, insert, or replace entries.150    """151    if predicates is None:152        predicates = default_predicates()153    if differs is None:154        differs = default_differs()155    if not isinstance(a, dict) or not isinstance(b, dict):156        raise TypeError('Arguments to diff_dicts need to be dicts, got %r and %r' % (a, b))157    akeys = set(a.keys())158    bkeys = set(b.keys())159    di = MappingDiffBuilder()160    # Sorting keys in loops to get a deterministic diff result161    for key in sorted(akeys - bkeys):162        di.remove(key)163    # Handle values for keys in both a and b164    for key in sorted(akeys & bkeys):165        avalue = a[key]166        bvalue = b[key]167        # If types are the same and nonatomic, recurse168        if type(avalue) is type(bvalue) and not is_atomic(avalue):...test_perimeter.py
Source:test_perimeter.py  
1import unittest2from app.main.extraction.dxf_extraction_coordinator import DxfExtractionCoordinator3from app.main.dtos.request.extraction_request_file import ExtractionRequestFile4from app.main.constants import PERIMETER_INCORRECT_EG, PERIMETER_INCORRECT_1OG, PERIMETER_INCORRECT_2OG5from app.main.constants import ACCEPTABLE_PERIMETER_DEVIATION6from app.test.test_data.perimeter_validation import expect_perimeter_eg, expect_perimeter_1og, expect_perimeter_2og7'''8Description: This test class is used to validate the perimeter per room with a possible deviation of 5% using test data in app.test.test_data.test_perimeter_validation9assert values = PERIMETER_INCORRECT_{EG,1OG,2OG} specified in constants.py10'''11class TestPerimeter(unittest.TestCase):12    @classmethod13    def setUpClass(cls):14        file_path = 'app/main/media/Einfache_Plaene_Compass/'15        file_name = 'R-Bau_D_EG.dxf'16        file_name_1og = 'R-Bau_D_1OG.dxf'17        file_name_2og = 'R-Bau_D_2OG.dxf'18        floor_height = 0.019        orientation = 0.020        dxf_extraction_coordinator = DxfExtractionCoordinator()21        cls.extraction_request_file = ExtractionRequestFile(22            file_path=file_path, file_name=file_name, floor_height=floor_height, orientation=orientation23        )24        cls.extraction_request_file_1og = ExtractionRequestFile(25            file_path=file_path, file_name=file_name_1og, floor_height=floor_height, orientation=orientation26        )27        cls.extraction_request_file_2og = ExtractionRequestFile(28            file_path=file_path, file_name=file_name_2og, floor_height=floor_height, orientation=orientation29        )30        cls.simple_plan_eg = dxf_extraction_coordinator.coordinate_simple_dxf_extraction(31            cls.extraction_request_file)32        cls.simple_plan_1og = dxf_extraction_coordinator.coordinate_simple_dxf_extraction(33            cls.extraction_request_file_1og)34        35        cls.simple_plan_2og = dxf_extraction_coordinator.coordinate_simple_dxf_extraction(36            cls.extraction_request_file_2og)37    38    def test_perimeter_is_correct_simple_plan_eg(self):39        perimeter_differs = []40        expect_perimeter = expect_perimeter_eg41        42        for polygon in self.simple_plan_eg.polygons:43            try:44                room_number = polygon.room.room_number45                perimeter_calculated = polygon.perimeter46                perimeter_expect = expect_perimeter.get(room_number)47                if perimeter_expect:48                    perimeter_deviation = abs((float(49                        perimeter_expect) - float(perimeter_calculated)) / float(perimeter_expect))50                    if perimeter_deviation >= ACCEPTABLE_PERIMETER_DEVIATION:51                        perimeter_differs_data = {52                            "room_number": room_number,53                            "perimeter_calculated": perimeter_calculated,54                            "perimeter_expect": perimeter_expect,55                            "perimeter_deviation": perimeter_deviation56                        }57                        perimeter_differs.append(perimeter_differs_data)58            except (AttributeError, KeyError):59                continue60        count_perimeter_differs = len(perimeter_differs)61        self.assertEqual(count_perimeter_differs, PERIMETER_INCORRECT_EG,62                         "perimeter calculation incorrect: there area {} polygons/rooms where perimeter_calculated != measured_perimeter".format(count_perimeter_differs))63        64    def test_perimeter_is_correct_simple_plan_1og(self):65        perimeter_differs = []66        expect_perimeter = expect_perimeter_1og67        68        for polygon in self.simple_plan_1og.polygons:69            try:70                room_number = polygon.room.room_number71                perimeter_calculated = polygon.perimeter72                perimeter_expect = expect_perimeter.get(room_number)73                if perimeter_expect:74                    perimeter_deviation = abs((float(75                        perimeter_expect) - float(perimeter_calculated)) / float(perimeter_expect))76                    if perimeter_deviation >= ACCEPTABLE_PERIMETER_DEVIATION:77                        perimeter_differs_data = {78                            "room_number": room_number,79                            "perimeter_calculated": perimeter_calculated,80                            "perimeter_expect": perimeter_expect,81                            "perimeter_deviation": perimeter_deviation82                        }83                        perimeter_differs.append(perimeter_differs_data)84            except (AttributeError, KeyError):85                continue86        count_perimeter_differs = len(perimeter_differs)87        self.assertEqual(count_perimeter_differs, PERIMETER_INCORRECT_1OG,88                         "perimeter calculation incorrect: there area {} polygons/rooms where perimeter_calculated != measured_perimeter".format(count_perimeter_differs))89    def test_perimeter_is_correct_simple_plan_2og(self):90        perimeter_differs = []91        expect_perimeter = expect_perimeter_2og92        93        for polygon in self.simple_plan_2og.polygons:94            try:95                room_number = polygon.room.room_number96                perimeter_calculated = polygon.perimeter97                perimeter_expect = expect_perimeter.get(room_number)98                if perimeter_expect:99                    perimeter_deviation = abs((float(100                        perimeter_expect) - float(perimeter_calculated)) / float(perimeter_expect))101                    if perimeter_deviation >= ACCEPTABLE_PERIMETER_DEVIATION:102                        perimeter_differs_data = {103                            "room_number": room_number,104                            "perimeter_calculated": perimeter_calculated,105                            "perimeter_expect": perimeter_expect,106                            "perimeter_deviation": perimeter_deviation107                        }108                        perimeter_differs.append(perimeter_differs_data)109            except (AttributeError, KeyError):110                continue111        count_perimeter_differs = len(perimeter_differs)112        self.assertEqual(count_perimeter_differs, PERIMETER_INCORRECT_2OG,113                         "perimeter calculation incorrect: there area {} polygons/rooms where perimeter_calculated != measured_perimeter".format(count_perimeter_differs))114        115if __name__ == '__main__':...test_area.py
Source:test_area.py  
1import unittest2from app.main.extraction.dxf_extraction_coordinator import DxfExtractionCoordinator3from app.main.dtos.request.extraction_request_file import ExtractionRequestFile4from app.main.constants import AREA_INCORRECT_EG5from app.main.constants import AREA_INCORRECT_1OG6from app.main.constants import AREA_INCORRECT_2OG7from app.main.constants import ACCEPTABLE_AREA_DEVIATION8'''9Description: This test class is used to validate the calculated area per polygon using extracted room area annotations with a possible deviation of 5%10assert values = AREA_INCORRECT_{EG,1OG,2OG} specified in constants.py11'''12class TestArea(unittest.TestCase):13    @classmethod14    def setUpClass(cls):15        file_path = 'app/main/media/Einfache_Plaene_Compass/'16        file_name = 'R-Bau_D_EG.dxf'17        file_name_1og = 'R-Bau_D_1OG.dxf'18        file_name_2og = 'R-Bau_D_2OG.dxf'19        floor_height = 0.020        orientation = 0.021        dxf_extraction_coordinator = DxfExtractionCoordinator()22        cls.extraction_request_file = ExtractionRequestFile(23            file_path=file_path, file_name=file_name, floor_height=floor_height, orientation=orientation24        )25        cls.extraction_request_file_1og = ExtractionRequestFile(26            file_path=file_path, file_name=file_name_1og, floor_height=floor_height, orientation=orientation27        )28        cls.extraction_request_file_2og = ExtractionRequestFile(29            file_path=file_path, file_name=file_name_2og, floor_height=floor_height, orientation=orientation30        )31        cls.simple_plan_eg = dxf_extraction_coordinator.coordinate_simple_dxf_extraction(32            cls.extraction_request_file)33        cls.simple_plan_1og = dxf_extraction_coordinator.coordinate_simple_dxf_extraction(34            cls.extraction_request_file_1og)35        36        cls.simple_plan_2og = dxf_extraction_coordinator.coordinate_simple_dxf_extraction(37            cls.extraction_request_file_2og)38    39    def test_calculated_area_is_annotation_area_simple_plan_eg(self):40        41        area_differs = []42        for polygon in self.simple_plan_eg.polygons:43            try:44                room_number = polygon.room.room_number45                area_calculated = polygon.area46                area_annotation = polygon.room.room_area47                area_deviation = abs(48                    (float(area_annotation) - float(area_calculated)) / float(area_annotation))49                if area_deviation >= ACCEPTABLE_AREA_DEVIATION:50                    area_differs_data = {51                        "room_number":   room_number,52                        "area_calculated":   area_calculated,53                        "area_annotation":   area_annotation,54                        "area_deviation":   area_deviation55                    }56                    area_differs.append(area_differs_data)57            except (AttributeError, KeyError):58                continue59        count_area_differs = len(area_differs)60        self.assertEqual(count_area_differs, AREA_INCORRECT_EG,61                         "area calculation incorrect: there are {} polygons/rooms where area_calculated != area_annotation".format(count_area_differs))62        63    def test_calculated_area_is_annotation_area_simple_plan_1og(self):64        65        area_differs = []66        for polygon in self.simple_plan_1og.polygons:67            try:68                room_number = polygon.room.room_number69                area_calculated = polygon.area70                area_annotation = polygon.room.room_area71                area_deviation = abs(72                    (float(area_annotation) - float(area_calculated)) / float(area_annotation))73                if area_deviation >= ACCEPTABLE_AREA_DEVIATION:74                    area_differs_data = {75                        "room_number":   room_number,76                        "area_calculated":   area_calculated,77                        "area_annotation":   area_annotation,78                        "area_deviation":   area_deviation79                    }80                    area_differs.append(area_differs_data)81                    #print("\t room_number: {} | area_calculated: {} | area_annotation: {} | area_deviation: {}".format(82                    #    room_number, round(area_calculated, 2), area_annotation, round(area_deviation, 2)))83            except (AttributeError, KeyError):84                continue85        count_area_differs = len(area_differs)86        self.assertEqual(count_area_differs, AREA_INCORRECT_1OG,87                         "area calculation incorrect: there are {} polygons/rooms where area_calculated != area_annotation".format(count_area_differs))88    def test_calculated_area_is_annotation_area_simple_plan_2og(self):89        90        area_differs = []91        for polygon in self.simple_plan_2og.polygons:92            try:93                room_number = polygon.room.room_number94                area_calculated = polygon.area95                area_annotation = polygon.room.room_area96                area_deviation = abs(97                    (float(area_annotation) - float(area_calculated)) / float(area_annotation))98                if area_deviation >= ACCEPTABLE_AREA_DEVIATION:99                    area_differs_data = {100                        "room_number":   room_number,101                        "area_calculated":   area_calculated,102                        "area_annotation":   area_annotation,103                        "area_deviation":   area_deviation104                    }105                    area_differs.append(area_differs_data)106                    #print("\t room_number: {} | area_calculated: {} | area_annotation: {} | area_deviation: {}".format(107                    #    room_number, round(area_calculated, 2), area_annotation, round(area_deviation, 2)))108            except (AttributeError, KeyError):109                continue110        count_area_differs = len(area_differs)111        self.assertEqual(count_area_differs, AREA_INCORRECT_2OG,112                         "area calculation incorrect: there are {} polygons/rooms where area_calculated != area_annotation".format(count_area_differs))113if __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!!
