0

I have a function

read_value_from_text()

that reads parameters from a config file and returns a dictionary in this form

{ key1 : value1, key2 : value2, ... , keyn : valuen }

the values (value1 ... valuen) are all strings that represent numbers. I want to write a unit test that checks if all values (value1,...,valuen) are "numeric" ( float or integer). Can someone suggest an efficient way to do this?

overcomer
  • 2,244
  • 3
  • 26
  • 39

3 Answers3

2

You can test whether a string is a number with:

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

is_number(x)

You can thus do:

self.assertTrue(all(is_number(v) for v in d.itervalues()))
Community
  • 1
  • 1
David Robinson
  • 77,383
  • 16
  • 167
  • 187
  • Sorry I was not clear in the question... value1... valuen are all string that rapresent numbers Like '1' or '2.3' In this case the function isinstance fails – overcomer Apr 21 '15 at 18:04
  • @overcomer I understand now. Corrected (see [here](http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python) for more on that function) – David Robinson Apr 21 '15 at 18:09
1
def isNumeric(val):
    if isinstance(val, (int, float)):
        return True
    try:
        float(val)
    except ValueError:
        return False
    else:
        return True

Sample test:

d = {}
for v in d.itervalues():
    self.assertTrue(isNumeric(v))

Well, to be honest it's validator, not unit test. Unit tests are checking code behaviour, you're checking data correctness.

Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
0
for val in my_dict.values():
    self.assertIsInstance(val, int)
dursk
  • 4,435
  • 2
  • 19
  • 30