Unit Tests Scope

Viewed 25

I'll try to make my question as simple as possible.

Context
Create an array that holds numbers; given the following constraints:

  • Each number should not be a duplicate of an already existing number.
  • Each number should not start with an even digit.

Question
Should each test case focus on a single behavior and assert whether this behavior conforms with all constraints (Multiple Assertion), or should each test case focus on a single behavior and a single constraint assertion?

Mock-Up

class UnitTest():
   def MultipleAssertions(self):
      #logic to add number into array
      #assertion on first constraint (duplication)
      #assertion on the second constraint (even digit)
   
   def FirstSingleAssertion(self):
      #logic to add number into array
      #assertion on first constraint (duplication)
   
   def SecondSingleAssertion(self):
      #logic to add number into array
      #assertion on second constraint (even digit)

Knowing that each test case should solely focus on a single behavior/act either way.

Thank you!

1 Answers

This would meet all the criteria.

import math

x = [1,2,3,4,5,5,5, 200, 200, 300, 700, 800, 800]

def getFirstDigit(num):
    return int(num / 10 ** int(math.log10(num)))

# get first digit of each number
f = [getFirstDigit(i) for i in x]

# remove duplicates
g = list(set(f))

# remove even numbers
result = [i for i in g if i%2!= 0]

result

the result

[1, 3, 5, 7]

If you wanted the numbers to be retained in long form (ie. 400 is accepted and not 4), you can run a variant of the above in a similar way.

Related