Checks if two version of a code match with the exception of the class/function name. Args: observed_code (`str`): The code found. theoretical_code (`str`): The code to match. Returns: `Optional[int]`: The index of the first line where there is a difference (if
(observed_code: str, theoretical_code: str)
| 592 | |
| 593 | |
| 594 | def check_codes_match(observed_code: str, theoretical_code: str) -> int | None: |
| 595 | """ |
| 596 | Checks if two version of a code match with the exception of the class/function name. |
| 597 | |
| 598 | Args: |
| 599 | observed_code (`str`): The code found. |
| 600 | theoretical_code (`str`): The code to match. |
| 601 | |
| 602 | Returns: |
| 603 | `Optional[int]`: The index of the first line where there is a difference (if any) and `None` if the codes |
| 604 | match. |
| 605 | """ |
| 606 | observed_code_header = observed_code.split("\n")[0] |
| 607 | theoretical_code_header = theoretical_code.split("\n")[0] |
| 608 | |
| 609 | # Catch the function/class name: it is expected that those do not match. |
| 610 | _re_class_match = re.compile(r"class\s+([^\(:]+)(?:\(|:)") |
| 611 | _re_func_match = re.compile(r"def\s+([^\(]+)\(") |
| 612 | for re_pattern in [_re_class_match, _re_func_match]: |
| 613 | if re_pattern.match(observed_code_header) is not None: |
| 614 | try: |
| 615 | observed_obj_name = re_pattern.search(observed_code_header).groups()[0] |
| 616 | except Exception: |
| 617 | raise ValueError( |
| 618 | "Tried to split a class or function. It did not work. Error comes from: \n```\n" |
| 619 | + observed_code_header |
| 620 | + "\n```\n" |
| 621 | ) |
| 622 | |
| 623 | try: |
| 624 | theoretical_name = re_pattern.search(theoretical_code_header).groups()[0] |
| 625 | except Exception: |
| 626 | raise ValueError( |
| 627 | "Tried to split a class or function. It did not work. Error comes from: \n```\n" |
| 628 | + theoretical_code_header |
| 629 | + "\n```\n" |
| 630 | ) |
| 631 | theoretical_code_header = theoretical_code_header.replace(theoretical_name, observed_obj_name) |
| 632 | |
| 633 | # Find the first diff. Line 0 is special since we need to compare with the function/class names ignored. |
| 634 | diff_index = 0 |
| 635 | if theoretical_code_header != observed_code_header: |
| 636 | return 0 |
| 637 | |
| 638 | diff_index = 1 |
| 639 | for observed_line, theoretical_line in zip(observed_code.split("\n")[1:], theoretical_code.split("\n")[1:]): |
| 640 | if observed_line != theoretical_line: |
| 641 | return diff_index |
| 642 | diff_index += 1 |
| 643 | |
| 644 | |
| 645 | def is_copy_consistent( |
no test coverage detected