Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

unit testing - Can I fake/mock the type of my mock objects in python unittests

In my python code I check the type of one of the parameters to make sure it is of the type I expect. For instance:

def myfunction(dbConnection):
    if (type(dbConnection)<>bpgsql.Connection):
        r['error'] += ' invalid database connection'

I want to pass a mock connection for testing purposes. Is there a way to make the mock object pretend to be of the correct type?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With all due respect, It looks like you guys are not quite right!

I can use duck typing as said, but there is a way to do what I intended to do in the first place:

from http://docs.python.org/dev/library/unittest.mock.html

Mock objects that use a class or an instance as a spec or spec_set are able to pass isintance tests:

>>>
>>> mock = Mock(spec=SomeClass)
>>> isinstance(mock, SomeClass)
True
>>> mock = Mock(spec_set=SomeClass())
>>> isinstance(mock, SomeClass)
True

so my example code would be like:

m = mock.MagicMock(spec=bpgsql.Connection)
isinstance(m, bpgsql.Connection) 

this returns True

All that said, I am not arguing for strict type checking in python, I say if you need to check it you can do it and it works with testing and mocking too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...