Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is there a more efficient/better way to write my test cases in python?

is there a more efficient way to write my test cases in python? My test cases repeat themselves whenever code is repetitive there is a better way to write it but what would be a better way?
this is my code:

def are_anagrams(s1, s2):
    if len(s1) != len(s2):
        return False
    elif sorted(s1) == sorted(s2):
        return True
    else:
        return False

    #all below I want to write in a better way
#Test cases
        s1 = "danger"
        s2 = "garden"
        print(are_anagrams(s1,s2))
        t1 = "nameless"
        t2 = "salesmen"
        print(are_anagrams(t1,t2))
        a1 = "name"
        a2 = "sale"
        print(are_anagrams(a1,a2))
        b1 = "n"
        b2 = "sa"
        print(are_anagrams(b1,b2))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Don’t create named variables for values that you’re only going to use once, especially where the name doesn’t add any useful information (this applies to code in general, not just tests):

print(are_anagrams("danger", "garden"))
print(are_anagrams("nameless", "salesmen"))
print(are_anagrams("name", "sale"))
print(are_anagrams("n", "sa"))

Running your tests is easier if you assert on the expected values instead of just printing them; that way you don’t need to look at the output and compare it to what you expect it to be, you just run the test and if it doesn’t raise an AssertionError you know the code works the way you expect:

assert are_anagrams("danger", "garden")
assert are_anagrams("nameless", "salesmen")
assert not are_anagrams("name", "sale")
assert not are_anagrams("n", "sa")

Another way to write a sequence of tests like this is to create a table and then iterate through it, e.g.:

test_cases = [
    ("danger", "garden", True),
    ("nameless", "salesmen", True),
    ("name", "sale", False),
    ("n", "sa", False),
]

for s1, s2, result in test_cases:
    assert are_anagrams(s1, s2) == result

The table technique is more useful when the test cases are more complex, since it makes it easier to visually organize the test data to verify that you’re covering all the possible combinations of inputs; it also opens up the possibility of generating the table dynamically.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading