testing - How to mock a class in Python? -
i'm new python, used work ruby.
i'm trying tests python can't figure out how mock class test.
let's have real class:
from database import db class foo: def do_it(self): x = {'key': 'value'} db.save(x) # other stuff x return x now, want test if i'm doing x returns me right result, , want test if db.save called x parameter, don't want save x database. see if db.save being called, can use mock framework, how can tell foo class need use mock object , not real db object?
thank you.
edit: sorry, example wasn't enough need accomplish.
let's see new example:
from database import db class foo: db.connect() def do_it(self): x = {'key': 'value'} db.save(x) # other stuff x return x and instance, let's database down.
when import foo, raises connection error , not have time mock db.
what should do??
the answer is, don't write classes that. it's strange way anyway - there shouldn't executable code @ class level, other attribute , method definitions. should setup connection in __init__ method.
class foo(object): def __init__(self, *args, **kwargs): db.connect()
Comments
Post a Comment