Lately, I was studying the concept of unit testing in python, so I have decided to write a imperative strong password validator ( checker ) and also attach a unit test to it.
I would like to know if there is any recommendation for improving this code, Thanks!
main.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
KhodeNima's unit test learning package. | 23/11/9
"""
import string
ascii_lowercase_letters = string.ascii_lowercase
ascii_uppercase_letters = string.ascii_uppercase
ascii_numbers = string.digits
def is_master_password(literal: str):
"""Chekcs if a string literal have the requirements of a masterpasssword.
Args:
string (str): The string literal.
Raises:
ValueError: If invalid argument is passed for any parameter.
"""
if not isinstance(literal, str):
argument_type = type(literal).__name__
raise ValueError(f"Invalid argument type passed for the parameter: string | Expected: 'str' | Not: {argument_type}")
allowed_characters = ''.join([ascii_lowercase_letters, ascii_uppercase_letters, ascii_numbers])
min_password_length = 5
max_password_length = 20
string_length = len(literal)
valid_characters_count = 0
has_upper_case = False
has_lower_case = False
has_digit = False
if string_length < min_password_length:
return False
if string_length > max_password_length:
return False
for character in literal:
if character in allowed_characters:
valid_characters_count += 1
for character in literal:
if all([has_digit, has_upper_case, has_lower_case]):
break
if character.isdigit():
has_digit = True
if character.isupper():
has_upper_case = True
if character.islower():
has_lower_case = True
if not valid_characters_count == string_length or not all([has_digit, has_lower_case, has_upper_case]):
return False
return True
print(is_master_password("Reedwolf13"))
unit_test.py
"""
KhodeNima's Unit test training package | 2023/11/9
"""
import unittest
from main import (
is_master_password
)
class MasterPasswordExaminerTest(unittest.TestCase):
"""
The main program test case
"""
def test_character_validation_check(self):
"""Does the program character checking system work correctly?
"""
self.assertEqual(is_master_password("!-*&%#@$()"), False)
self.assertEqual(is_master_password('Redwolf1'), True)
def test_length_validation_check(self):
"""Does the program validate the password length correctly?
"""
self.assertEqual(is_master_password('Jsf3'), False)
self.assertEqual(is_master_password('mnbRDSAQOPJK123986532nm'), False)
def test_requirement_check(self):
"""Does the program validates the password requirements correcly? (1 Uppercase L, 1 Lowercase L, 1 Digit)
"""
self.assertEqual(is_master_password("Redwolf1"), True)
self.assertEqual(is_master_password("Redwolf"), False)
self.assertEqual(is_master_password("redwolf1"), False)
if __name__ == '__main__':
unittest.main()