adding a simulation mode

andrea crotti andrea.crotti.0 at gmail.com
Wed Jul 4 09:59:55 EDT 2012


2012/7/4 Steven D'Aprano <steve+comp.lang.python at pearwood.info>:
>
> Then, have your code accept the thing as an argument.
>
> E.g. instead of having a hard-coded database connection, allow the
> database connection to be set (perhaps as an argument, perhaps as a
> config option, etc.).
>
> There are libraries to help with mocks, e.g.:
>
> http://garybernhardt.github.com/python-mock-comparison/

Ah yes this part is already done, I pass an object to the entry point
of the program which represents the database connection, which looks
like this:

class MockMysqlEngine(MySqlEngine):
    # TODO: make the engine more generic would avoid this dirty hack
    def __init__(self, *args, **kwargs):
        # self.engine =
create_engine('sqlite:////home/andrea/testdb.sqlite', echo=True)
        self.engine = create_engine('sqlite://', echo=True)
        self.meta = MetaData(bind=self.engine)
        self.session_maker = sessionmaker(bind=self.engine)


Now I populate statically the schema and populate with some test data
too, but I'm also implementing a weay to just pass some CSV files so
that other people can easily write some test cases with some other
possible database configurations.

(And I use mock for a few other things)


>
>
>> For example
>>
>> copytree(src, dest) becomes:
>> if not PRETEND_ONLY:
>>     copytree(src, dest)
>
> Ewww :(
>
> Mocking the file system is probably the hardest part, because you
> generally don't have a "FileSystem" object available to be replaced. In
> effect, your program has one giant global variable, the file system.
> Worse, it's not even a named variable, it's hard-coded everywhere you use
> it.
>
> I don't know of any good solution for that. I've often thought about it,
> but don't have an answer.
>
> I suppose you could monkey-patch a bunch of stuff:
>
> if ONLY_PRETEND:
>      open = my_mock_open
>      copytree = my_mock_copytree
>      # etc.
> main()  # run your application
>
>
>
> but that would also be painful.
>

Yes there is no easy solution apparently..  But I'm also playing
around with vagrant and virtual machine generations, suppose I'm able
to really control what will be on the machine at time X, creating it
on demand with what I need, it might be a good way to solve my
problems (a bit overkill and slow maybe though).

I'll try the sys.excepthook trick first, any error should give me an
exception, so if I catch them all I think it might work already..



More information about the Python-list mailing list