Skip to content

Commit

Permalink
Merge pull request #81 from cisagov/improvement/changes_to_match_deve…
Browse files Browse the repository at this point in the history
…lopment_preferences

Update to Match Best Practices
  • Loading branch information
mcdonnnj committed Jul 22, 2021
2 parents 422f11e + d9f689f commit 3c9b5d7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 16 deletions.
17 changes: 6 additions & 11 deletions src/example/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
DEFAULT_ECHO_MESSAGE: str = "Hello World from the example default!"


def example_div(dividend: float, divisor: float) -> float:
def example_div(dividend: int, divisor: int) -> float:
"""Print some logging messages."""
logging.debug("This is a debug message")
logging.info("This is an info message")
Expand All @@ -45,7 +45,7 @@ def example_div(dividend: float, divisor: float) -> float:
return dividend / divisor


def main() -> int:
def main() -> None:
"""Set up logging and call the example function."""
args: Dict[str, str] = docopt.docopt(__doc__, version=__version__)
# Validate and convert arguments as needed
Expand Down Expand Up @@ -73,7 +73,7 @@ def main() -> int:
except SchemaError as err:
# Exit because one or more of the arguments were invalid
print(err, file=sys.stderr)
return 1
sys.exit(1)

# Assign validated arguments to variables
dividend: int = validated_args["<dividend>"]
Expand All @@ -85,24 +85,19 @@ def main() -> int:
format="%(asctime)-15s %(levelname)s %(message)s", level=log_level.upper()
)

logging.info(f"{dividend} / {divisor} == {example_div(dividend, divisor)}")
logging.info("%d / %d == %f", dividend, divisor, example_div(dividend, divisor))

# Access some data from an environment variable
message: str = os.getenv("ECHO_MESSAGE", DEFAULT_ECHO_MESSAGE)
logging.info(f'ECHO_MESSAGE="{message}"')
logging.info('ECHO_MESSAGE="%s"', message)

# Access some data from our package data (see the setup.py)
secret_message: str = (
pkg_resources.resource_string("example", "data/secret.txt")
.decode("utf-8")
.strip()
)
logging.info(f'Secret="{secret_message}"')
logging.info('Secret="%s"', secret_message)

# Stop logging and clean up
logging.shutdown()
return 0


if __name__ == "__main__":
sys.exit(main())
23 changes: 18 additions & 5 deletions tests/test_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,21 +79,30 @@ def test_log_levels(level):
assert (
logging.root.hasHandlers() is False
), "root logger should not have handlers yet"
return_code = example.example.main()
return_code = None
try:
example.example.main()
except SystemExit as sys_exit:
return_code = sys_exit.code
assert return_code is None, "main() should return success"
assert (
logging.root.hasHandlers() is True
), "root logger should now have a handler"
assert (
logging.getLevelName(logging.root.getEffectiveLevel()) == level.upper()
), f"root logger level should be set to {level.upper()}"
assert return_code == 0, "main() should return success (0)"
assert return_code is None, "main() should return success"


def test_bad_log_level():
"""Validate bad log-level argument returns error."""
with patch.object(sys, "argv", ["bogus", "--log-level=emergency", "1", "1"]):
return_code = example.example.main()
assert return_code == 1, "main() should return failure"
return_code = None
try:
example.example.main()
except SystemExit as sys_exit:
return_code = sys_exit.code
assert return_code == 1, "main() should exit with error"


@pytest.mark.parametrize("dividend, divisor, quotient", div_params)
Expand Down Expand Up @@ -127,5 +136,9 @@ def test_zero_division():
def test_zero_divisor_argument():
"""Verify that a divisor of zero is handled as expected."""
with patch.object(sys, "argv", ["bogus", "1", "0"]):
return_code = example.example.main()
return_code = None
try:
example.example.main()
except SystemExit as sys_exit:
return_code = sys_exit.code
assert return_code == 1, "main() should exit with error"

0 comments on commit 3c9b5d7

Please sign in to comment.