Skip to content

Commit

Permalink
Added test case, updated Changelog, and changed functionality of new_…
Browse files Browse the repository at this point in the history
…setattr after review
  • Loading branch information
Bruce-8 committed Jul 22, 2023
1 parent 001dd04 commit 12c5ec5
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
7 changes: 4 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,10 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- When running `check_contracts` on a class with type aliases as type annotations for its attributes, the `NameError`
that appears (which indicates that the type alias is undefined) is now resolved.
- The default value of `pyta-number-of-messages` is now 0. This automatically displays all occurrences of the same error.
- For the contract checking `new_setattr` function, any variables that depend only on `klass` are now defined in the
outer function, efficiency of code was improved, and the attribute value is now restored to the original value if the
`_check_invariants` call raises an error.
- For the contract checking `new_setattr` function, the check for `ENABLE_CONTRACT_CHECKING` is now at the top of the
function, any variables that depend only on `klass` are now defined in the outer function, efficiency of code was
improved, and the attribute value is now restored to the original value if the `_check_invariants` call raises an
error.

### Bug Fixes

Expand Down
5 changes: 4 additions & 1 deletion python_ta/contracts/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,10 @@ def new_setattr(self: klass, name: str, value: Any) -> None:
Check representation invariants for this class when not within an instance method of the class.
"""
if ENABLE_CONTRACT_CHECKING:
if not ENABLE_CONTRACT_CHECKING:
super(klass, self).__setattr__(name, value)
return
else:
if name in cls_annotations:
try:
_debug(f"Checking type of attribute {attr} for {klass.__qualname__} instance")
Expand Down
19 changes: 19 additions & 0 deletions tests/test_contracts_disable_contract_checking.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import python_ta.contracts
from python_ta.contracts import check_contracts


def test_invalid_attr_type_disable_contract_checking() -> None:
"""
Test that a Person object is created with an attribute value that doesn't match the specified type annotation but
with ENABLE_CONTRACT_CHECKING = False so no error is raised.
"""

@check_contracts
class Person:
age: int

python_ta.contracts.ENABLE_CONTRACT_CHECKING = False
my_person = Person()
my_person.age = "John"
assert my_person.age == "John"
python_ta.contracts.ENABLE_CONTRACT_CHECKING = True

0 comments on commit 12c5ec5

Please sign in to comment.