doublex-1.7.2/0000755000175000017500000000000012236777524012256 5ustar piotrpiotrdoublex-1.7.2/.hgtags0000644000175000017500000000123012236777524013530 0ustar piotrpiotr4afef1efc69f21d6447585bcdf300911f16184b6 v0.3 9d106a5b924ad58d5c5b8fef4c6f7bdd1b0ae433 v1.5 3eb55b287dbf93f56fd139ad863ad5fe6e798273 v1.5.1 3eb55b287dbf93f56fd139ad863ad5fe6e798273 v1.5.1 088989a406631e0a686621669534d6a0d08e4add v1.5.1 cb8ba0df2e024d602fed236bb5ed5a7ceee91b20 v1.6 80ae08749c28b16fe38b82eae1423923512ae0c3 v1.6.1 ce8cdff71b8e3528380c305bf7d9ca75a64f6460 v1.6.2 bc4f19e466eb484e0046e17ad7821048d35c5a9e v1.6.3 9ad7b1696f919753306228eb2d8df8c92cc5f6ba v1.6.4 1094f91a921bb89a0e3fc2abedda9d91a8fbbd40 v1.6.5 3fe85008b9ee8ff34a456c71f20afcedf42e8ab4 v1.6.6 916c8e557345335449a3a85c70b1413a331e2136 v1.7 c16348f54bf84ca75b10ee1290a272f321d82cf5 v1.7.1 doublex-1.7.2/slides/0000755000175000017500000000000012236777524013541 5ustar piotrpiotrdoublex-1.7.2/slides/beamer/0000755000175000017500000000000012236777524014774 5ustar piotrpiotrdoublex-1.7.2/slides/beamer/custom.sty0000644000175000017500000000323612236777524017053 0ustar piotrpiotr\usepackage[spanish]{babel} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{times} \usepackage{graphicx} \graphicspath{{figures/}} \usepackage{listings} \newcommand{\lstfont}{\ttfamily\fontfamily{pcr}} \lstset{ % frame frame = Ltb, framerule = 0pt, aboveskip = 0.5cm, framextopmargin = 3pt, framexbottommargin = 3pt, framexleftmargin = 0.4cm, framesep = 0pt, rulesep = .4pt, %-- % caption belowcaptionskip = 5pt, %-- % text style stringstyle = \ttfamily, showstringspaces = false, basicstyle = \scriptsize\lstfont, keywordstyle = \bfseries, %-- % numbers numbers = none, numbersep = 15pt, numberstyle = \scriptsize\lstfont, numberfirstline = false, % breaklines = true, emptylines = 1, % several empty lines are shown as one % literate = % caracteres especiales {á}{{\'a}}1 {Á}{{\'A}}1 {é}{{\'e}}1 {É}{{\'E}}1 {í}{{\'i}}1 {Í}{{\'I}}1 {ó}{{\'o}}1 {Ó}{{\'O}}1 {ú}{{\'u}}1 {Ú}{{\'U}}1 {ñ}{{\~n}}1 {Ñ}{{\~N}}1 {¡}{{!`}}1 {¿}{{?`}}1 } \parskip=10pt \mode { \usetheme{Frankfurt} \setbeamercovered{transparent} % or whatever (possibly just delete it) } % Delete this, if you do not want the table of contents to pop up at % the beginning of each subsection: \AtBeginSubsection[] { \begin{frame}{Outline} \tableofcontents[currentsection,currentsubsection] \end{frame} } % If you wish to uncover everything in a step-wise fashion, uncomment % the following command: %\beamerdefaultoverlayspecification{<+->} doublex-1.7.2/slides/beamer/slides.tex0000644000175000017500000002271412236777524017007 0ustar piotrpiotr\documentclass[11pt]{beamer} \usepackage{custom} \title{doublex: Python test doubles framework} \subtitle{\bfseries\small\url{http://bitbucket.org/DavidVilla/python-doublex}} \author{\bfseries\small\texttt{@david\_vi11a}} %\institute{} \date{} %\subject{} \begin{document} \begin{frame} \titlepage \end{frame} \begin{frame}{Contents} \tableofcontents \end{frame} \section{Intro} \begin{frame}{Another doubles library for Python?} Yes, why not? \end{frame} \begin{frame}{doublex features} \begin{itemize} \item Stubs \item Spies \item Mocks \item ah hoc stub methods \item stub delegates \item stub observers \item properties \item hamcrest matchers for \textbf{all} assertions \item wrapper for legacy pyDoubles API \item doublex never instantiates your classes! \end{itemize} \end{frame} \section{Stubs} \begin{frame}[fragile]{Stubs} \framesubtitle{set fixed return value} \begin{exampleblock}{} \begin{lstlisting}[language=Python] class Collaborator: def add(self, x, y): return x + y with Stub(Collaborator) as stub: stub.add(ANY_ARG).returns(1000) assert_that(stub.add(2, 2), is_(1000)) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Stubs} \framesubtitle{\... by calling arg values} Undefined stub methods returns None. \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Stub(Collaborator) as stub: stub.add(2, 2).returns(1000) stub.add(3, ANY_ARG).returns(0) assert_that(stub.add(1, 1), is_(None)) assert_that(stub.add(2, 2), is_(1000)) assert_that(stub.add(3, 0), is_(0)) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Stubs} \framesubtitle{\... by hamcrest matcher} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Stub(Collaborator) as stub: stub.add(2, greater_than(4)).returns(4) assert_that(stub.add(2, 1), is_(None)) assert_that(stub.add(2, 5), is_(4)) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Stubs} \framesubtitle{\... by composite hamcrest matcher} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Stub(Collaborator) as stub: stub.foo(has_length(all_of( greater_than(4), less_than(8)))).returns(1000) assert_that(stub.add(2, "bad"), is_(None)) assert_that(stub.add(2, "enough"), is_(1000)) \end{lstlisting} \end{exampleblock} \end{frame} \section{Spies} \begin{frame}[fragile]{Spies} \framesubtitle{checking called methods} \begin{exampleblock}{} \begin{lstlisting}[language=Python] spy = Spy(Collaborator) spy.add(2, 3) spy.add("hi", 3.0) spy.add([1, 2], 'a') assert_that(spy.add, called()) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Spies} \framesubtitle{collaborator signature checking} \begin{exampleblock}{} \begin{lstlisting}[language=Python] spy = Spy(Collaborator) spy.add() TypeError: __main__.Collaborator.add() takes exactly 3 arguments (1 given) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Spies} \framesubtitle{checking called times (with matcher too!)} \begin{exampleblock}{} \begin{lstlisting}[language=Python] spy = Spy(Collaborator) spy.add(2, 3) spy.add("hi", 3.0) spy.add([1, 2], 'a') assert_that(spy.add, called().times(3)) assert_that(spy.add, called().times(greater_than(2))) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Spies} \framesubtitle{filter by argument value: \texttt{with\_args()})} \begin{exampleblock}{} \begin{lstlisting}[language=Python] spy = Spy(Collaborator) spy.add(2, 3) spy.add(2, 8) spy.add("hi", 3.0) assert_that(spy.add, called().with_args(2, ANY_ARG)).times(2) assert_that(spy.add, never(called().with_args(0, 0))) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Spies} \framesubtitle{filter by key argument (with matcher)} \begin{exampleblock}{} \begin{lstlisting}[language=Python] spy = Spy() spy.foo(name="Mary") assert_that(spy.foo, called().with_args(name="Mary")) assert_that(spy.foo, called().with_args(name=contains_string("ar"))) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Spies} \framesubtitle{Verbose meaning-full report messages!} \begin{exampleblock}{} \begin{lstlisting}[language=Python] spy = Spy() spy.foo(1) spy.bar("hi") assert_that(spy.foo, called().with_args(4)) AssertionError: Expected: these calls: Spy.foo(4) but: calls that actually ocurred were: Spy.foo(1) Spy.bar('hi') \end{lstlisting} \end{exampleblock} \end{frame} \subsection{ProxySpy} \begin{frame}[fragile]{ProxySpy} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with ProxySpy(Collaborator()) as spy: spy.add(2, 2).returns(1000) assert_that(spy.add(2, 2), is_(1000)) assert_that(spy.add(1, 1), is_(2)) \end{lstlisting} \end{exampleblock} \end{frame} \section{Mocks} \begin{frame}[fragile]{Mocks} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Mock() as smtp: smtp.helo() smtp.mail(ANY_ARG) smtp.rcpt("bill@apple.com") smtp.data(ANY_ARG).returns(True).times(2) smtp.helo() smtp.mail("poormen@home.net") smtp.rcpt("bill@apple.com") smtp.data("somebody there?") assert_that(smtp.data("I am afraid.."), is_(True)) assert_that(smtp, verify()) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Mocks} \framesubtitle{invocation order is important} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Mock() as mock: mock.foo() mock.bar() mock.bar() mock.foo() assert_that(mock, verify()) AssertionError: Expected: these calls: Mock.foo() Mock.bar() but: calls that actually ocurred were: Mock.bar() Mock.foo() \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Mocks} \framesubtitle{unless you do not mind: \texttt{any\_order\_verify()}} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Mock() as mock: mock.foo() mock.bar() mock.bar() mock.foo() assert_that(mock, any_order_verify()) \end{lstlisting} \end{exampleblock} \end{frame} \section{ah hoc stub methods} \begin{frame}[fragile]{ah hoc stub methods} \begin{exampleblock}{} \begin{lstlisting}[language=Python] collaborator = Collaborator() collaborator.foo = method_returning('bye') assert_that(self.collaborator.foo(), is_('bye')) collaborator.foo = method_raising(SomeException) collaborator.foo() SomeException: \end{lstlisting} \end{exampleblock} \end{frame} \section{stub observers} \begin{frame}[fragile]{stub observers} \begin{exampleblock}{} \begin{lstlisting}[language=Python] class Observer(object): def __init__(self): self.state = None def update(self, *args, **kargs): self.state = args[0] observer = Observer() stub = Stub() stub.foo.attach(observer.update) stub.foo(2) assert_that(observer.state, is_(2)) \end{lstlisting} \end{exampleblock} \end{frame} \section{stub delegates} \begin{frame}[fragile]{stub delegates} \framesubtitle{delegating to callables} \begin{exampleblock}{} \begin{lstlisting}[language=Python] def get_user(): return "Freddy" with Stub() as stub: stub.user().delegates(get_user) stub.foo().delegates(lambda: "hello") assert_that(stub.user(), is_("Freddy")) assert_that(stub.foo(), is_("hello")) \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{stub delegates} \framesubtitle{delegating to iterables} \begin{exampleblock}{} \begin{lstlisting}[language=Python] with Stub() as stub: stub.foo().delegates([1, 2, 3]) assert_that(stub.foo(), is_(1)) assert_that(stub.foo(), is_(2)) assert_that(stub.foo(), is_(3)) \end{lstlisting} \end{exampleblock} \end{frame} \section{properties} \begin{frame}[fragile]{stubbing properties} \begin{exampleblock}{} \begin{lstlisting}[language=Python] class Collaborator(object): @property def prop(self): return 1 @prop.setter def prop(self, value): pass with Spy(Collaborator) as spy: spy.prop = 2 assert_that(spy.prop, is_(2)) # double property getter invoked \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{spying properties (with matchers!)} \begin{exampleblock}{} \begin{lstlisting}[language=Python] assert_that(spy, property_got('prop')) spy.prop = 4 # double property setter invoked spy.prop = 5 # -- spy.prop = 5 # -- assert_that(spy, property_set('prop')) # set to any value assert_that(spy, property_set('prop').to(4)) assert_that(spy, property_set('prop').to(5).times(2)) assert_that(spy, never(property_set('prop').to(greater_than(6)))) \end{lstlisting} \end{exampleblock} \end{frame} \section{Mimics} \begin{frame}[fragile]{normal doubles support only duck-typing} \begin{exampleblock}{} \begin{lstlisting}[language=Python] class A(object): pass class B(A): pass >>> spy = Spy(B()) >>> isinstance(spy, Spy) True >>> isinstance(spy, B) False \end{lstlisting} \end{exampleblock} \end{frame} \begin{frame}[fragile]{Mimics support full LSP} \begin{exampleblock}{} \begin{lstlisting}[language=Python] >>> spy = Mimic(Spy, B) >>> isinstance(spy, B) True >>> isinstance(spy, A) True >>> isinstance(spy, Spy) True >>> isinstance(spy, Stub) True >>> isinstance(spy, object) True \end{lstlisting} \end{exampleblock} \end{frame} \section{Questions} \begin{frame}{} \begin{center} {\huge Questions?} \end{center} \end{frame} \end{document} %% Local Variables: %% coding: utf-8 %% mode: flyspell %% ispell-local-dictionary: "american" %% End: doublex-1.7.2/slides/beamer/Makefile0000644000175000017500000000002612236777524016432 0ustar piotrpiotrinclude arco/latex.mk doublex-1.7.2/slides/index.html0000644000175000017500000004371212236777524015545 0ustar piotrpiotr doublex

doublex

Python test doubles framework

@david_vi11a

what are doubles?

Test doubles are atrezzo objects.

why should we use doubles?

Unit tests must isolate the SUT.

So all collaborators should be replaced.

They require (and promote) your classes meets DIP and LSP.

then, instead of production class instances...

 collaborator = Collaborator()

 sut = SUT(collaborator)

 sut.exercise()
	    
...give it doubles

 double = Double(Collaborator)

 sut = SUT(double)

 sut.exercise()
	    

which is the right double?

  • Dummy: a placeholder object, never invoked
  • Fake: Q&D replacement, not suitable for production
  • Stub: returns hardcoded responses: It say you want to hear
  • Spy: Stub that records received invocations
  • Mock: holds and check programmed expectations

[ according to xunitpatterns.com/Test Double.html ]

EXAMPLE
account service

  class AccountService:
      def __init__(self, store, password_service):
	  [...]

      def create_user(self, login):
          [...]
          - raise InvalidPassword()
          - raise AlreadyExists()

      def create_group(self, group_name, user_names):
          [...]
	    

[ slides related to that example
have gray background ]

account service

collaborators


  class AccountStore:
      def save(self, login, password):
          [...]

      def has_user(self, login):
          [...]

  class PasswordService:
      def generate(self):
          [...]
	    

Stub

In a free stub, any method may be invoked:


  class AccountTests(TestCase):
      def test_account_creation(self):
          with Stub() as password_service:
              password_service.generate().returns('secret')

          service = AccountService(store=Stub(), password_service)

          service.create_user('John')
	    

Stub

... you can set return value depending on arguments


 with Stub() as stub:
     stub.foo(2, 2).returns(100)
     stub.foo(3, ANY_ARG).returns(200)

 assert_that(stub.foo(1, 1), is_(None))
 assert_that(stub.foo(2, 2), is_(100))
 assert_that(stub.foo(3, 0), is_(200))
	    

Stub

... or by hamcrest matcher


 with Stub() as stub:
     stub.foo(2, greater_than(4)).returns(100)

 assert_that(stub.foo(2, 1), is_(None))
 assert_that(stub.foo(2, 5), is_(100))
	    

Stub

... or by composite hamcrest matcher


 with Stub() as stub:
     stub.foo(2, has_length(all_of(
         greater_than(4), less_than(8)))).returns(1000)

 assert_that(stub.foo(2, "bad"), is_(None))
 assert_that(stub.foo(2, "enough"), is_(1000))
	    

Stub

interface may be restricted to a given class:


 with Stub(PasswordService) as password_service:
     password_service.generate().returns('secret')

 stub.generate()
 stub.generate(9)
TypeError: PasswordService.generate() takes exactly 1 argument (2 given)

 stub.wrong()
AttributeError: 'PasswordService' object has no attribute 'wrong'
	    

in our AccountService test:


  class AccountTests(TestCase):
      def test_account_creation(self):
          with Stub(PasswordService) as password_service:
              password_service.generate().returns('secret')

          service = AccountService(store=Stub(), password_service)

          service.create_user('John')
    

... is 'store' really called??

we need a spy

Spy

checking double invocations: called()


 store = Spy(AccountStore)
 service = AccountService(store, password_service)

 service.create_group('team', ['John', 'Peter', 'Alice'])

 assert_that(store.save, called())
    

but... is really called three times?

Spy

checking called times: times()

(also with matchers)


 store = Spy(AccountStore)
 service = AccountService(store, password_service)

 service.create_group('team', ['John', 'Peter', 'Alice'])

 assert_that(store.save, called().times(3))
 assert_that(store.save, called().times(greater_than(2)))
    

but... is really called with the right arguments?

Spy

check argument values: with_args()

(also with matchers)


 store = Spy(AccountStore)
 service = AccountService(store, password_service)

 service.create_user('John')

 assert_that(store.save, called().with_args('John', 'secret'))
 assert_that(store.save, called().with_args('John', ANY_ARG))
 assert_that(store.save,
             called().with_args(contains_string('oh'), ANY_ARG))
 assert_that(store.save,
             never(called().with_args('Alice', anything())))
    

Spy

check keyword argument

(also with matcher)


 spy = Spy()
 spy.foo(name="Mary")

 assert_that(spy.foo,
             called().with_args(name="Mary"))

 assert_that(spy.foo,
             called().with_args(name=contains_string("ar")))
    

Spy

meaning-full report messages!


 service.create_group('team', ['John', 'Alice'])

 assert_that(store.save, called().with_args('Peter'))
AssertionError:
Expected: these calls:
          AccountStore.save('Peter')
     but: calls that actually ocurred were:
          AccountStore.has_user('John')
          AccountStore.save('John', 'secret')
          AccountStore.has_user('Alice')
          AccountStore.save('Alice', 'secret')
    

ProxySpy

propagates invocations to the collaborator


 with ProxySpy(AccountStore()) as store:
     store.has_user('John').returns(True)

 service = AccountService(store, password_service)

 with self.assertRaises(AlreadyExists):
     service.create_user('John')
    

CAUTION: ProxySpy is not a true double,
this invokes the actual AccountStore instance!

Mock

programming expectations


        with Mock(AccountStore) as store:
            store.has_user('John')
            store.save('John', anything())
            store.has_user('Peter')
            store.save('Peter', anything())

        service = AccountService(store, password_service)

	service.create_group('team', ['John', 'Peter'])

        assert_that(store, verify())
    

Mock assures these invocations (and only these) are ocurred.

ah hoc stub methods


 collaborator = Collaborator()
 collaborator.foo = method_returning('bye')
 assert_that(self.collaborator.foo(), is_('bye'))

 collaborator.foo = method_raising(SomeException)
 collaborator.foo()
SomeException:
  

stub observers

attach additional behavior


 class Observer(object):
     def __init__(self):
         self.state = None

     def update(self, *args, **kargs):
         self.state = args[0]

 observer = Observer()
 stub = Stub()
 stub.foo.attach(observer.update)
 stub.foo(2)

 assert_that(observer.state, is_(2))
  

stub delegates

delegating to callables


 def get_pass():
     return "12345"

 with Stub(PasswordService) as password_service:
     password_service.generate().delegates(get_pass)

 store = Spy(AccountStore)
 service = AccountService(store, password_service)

 service.create_user('John')

 assert_that(store.save, called().with_args('John', '12345'))
    

stub delegates

delegating to iterables/generators


 with Stub(PasswordService) as password_service:
     password_service.generate().delegates(["12345", "mypass", "nope"])

 store = Spy(AccountStore)
 service = AccountService(store, password_service)

 service.create_group('team', ['John', 'Peter', 'Alice'])

 assert_that(store.save, called().with_args('John', '12345'))
 assert_that(store.save, called().with_args('Peter', 'mypass'))
 assert_that(store.save, called().with_args('Alice', 'nope'))
    

stubbing properties


 class Collaborator(object):
     @property
     def prop(self):
         return 1

     @prop.setter
     def prop(self, value):
         pass

 with Spy(Collaborator) as spy:
     spy.prop = 2

 assert_that(spy.prop, is_(2))  # double property getter invoked
    

spying properties

(also with matcher)


 assert_that(spy, property_got('prop'))

 spy.prop = 4  # double property setter invoked
 spy.prop = 5  # --
 spy.prop = 5  # --

 assert_that(spy, property_set('prop'))  # set to any value
 assert_that(spy, property_set('prop').to(4))
 assert_that(spy, property_set('prop').to(5).times(2))
 assert_that(spy,
             never(property_set('prop').to(greater_than(6))))
    

Questions?

References

doublex-1.7.2/slides/sample.py0000755000175000017500000001340612236777524015403 0ustar piotrpiotr#!/usr/bin/python # -*- mode:python; coding:utf-8; tab-width:4 -*- from unittest import TestCase from doublex import (Stub, Spy, ProxySpy, Mock, assert_that, called, ANY_ARG, never, verify, any_order_verify) from hamcrest import greater_than, anything, contains_string class AlreadyExists(Exception): pass class InvalidPassword(Exception): pass class AccountStore: def save(self, login, password): pass def has_user(self, login): pass class Group(set): def __init__(self, name): pass class PasswordService: def generate(self): pass class AccountService: def __init__(self, store, password_service): self.store = store self.password_service = password_service def create_user(self, login): if self.store.has_user(login): raise AlreadyExists() password = self.password_service.generate() if not password: raise InvalidPassword() self.store.save(login, password) def create_group(self, group_name, user_names): group = Group(group_name) for name in user_names: try: self.create_user(name) except AlreadyExists: pass group.add(name) class AccountTests(TestCase): def test_account_creation__free_stub(self): with Stub() as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_group('team', ['John', 'Peter', 'Alice']) assert_that(store.save, called()) def test_account_creation__restricted_stub(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_user('John') assert_that(store.save, called()) def test_account_creation__3_accounts(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_group('team', ['John', 'Peter', 'Alice']) assert_that(store.save, called().times(3)) assert_that(store.save, called().times(greater_than(2))) def test_account_creation__argument_values(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_user('John') assert_that(store.save, called().with_args('John', 'some')) assert_that(store.save, called().with_args('John', ANY_ARG)) assert_that(store.save, never(called().with_args('Alice', anything()))) assert_that(store.save, called().with_args(contains_string('oh'), ANY_ARG)) def test_account_creation__report_message(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') store = Spy(AccountStore) service = AccountService(store, password_service) service.create_group('team', ['John', 'Alice']) # assert_that(store.save, called().with_args('Peter')) def test_account_already_exists(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') with ProxySpy(AccountStore()) as store: store.has_user('John').returns(True) service = AccountService(store, password_service) with self.assertRaises(AlreadyExists): service.create_user('John') def test_account_behaviour_with_mock(self): with Stub(PasswordService) as password_service: password_service.generate().returns('some') with Mock(AccountStore) as store: store.has_user('John') store.save('John', 'some') store.has_user('Peter') store.save('Peter', 'some') service = AccountService(store, password_service) service.create_group('team', ['John', 'Peter']) assert_that(store, verify()) # def test_account_behaviour_with_mock_any_order(self): # with Stub(PasswordService) as password_service: # password_service.generate().returns('some') # # with Mock(AccountStore) as store: # store.has_user('John') # store.has_user('Peter') # store.save('John', 'some') # store.save('Peter', 'some') # # service = AccountService(store, password_service) # # service.create_user('John') # service.create_user('Peter') # # assert_that(store, any_order_verify()) def test_stub_delegates(self): def get_pass(): return "12345" with Stub(PasswordService) as password_service: password_service.generate().delegates(get_pass) store = Spy(AccountStore) service = AccountService(store, password_service) service.create_user('John') assert_that(store.save, called().with_args('John', '12345')) def test_stub_delegates_list(self): with Stub(PasswordService) as password_service: password_service.generate().delegates(["12345", "mypass", "nothing"]) store = Spy(AccountStore) service = AccountService(store, password_service) service.create_group('team', ['John', 'Peter', 'Alice']) assert_that(store.save, called().with_args('John', '12345')) assert_that(store.save, called().with_args('Peter', 'mypass')) assert_that(store.save, called().with_args('Alice', 'nothing')) doublex-1.7.2/slides/Makefile0000644000175000017500000000031212236777524015175 0ustar piotrpiotr LINKS=css lib plugin js all: reveal.js $(LINKS) reveal.js: git clone --depth 1 https://github.com/hakimel/reveal.js.git $(LINKS): ln -s reveal.js/$@ $@ clean: $(RM) -r reveal.js $(RM) $(LINKS) doublex-1.7.2/doc.rst0000644000175000017500000003004612236777524013560 0ustar piotrpiotrpython-doublex ============== A powerful test doubles framework for Python. This started as a try to improve and simplify pyDoubles codebase and API Source repository is: https://bitbucket.org/DavidVilla/python-doublex Design principles ================= - doubles should not have public API framework methods. It avoid silent misspelling. - non-proxified doubles does not require collaborator instances, they may use classes - hamcrest.assert_that used for all assertions - mock invocation order is required by default - compatible with old and new style classes Doubles ======= "free" Stub ----------- Hint: *Stubs tell you what you wanna hear.* A free Stub is an double object that have any method you invoke on it. Using the Stub context (``with`` keyword) you may program the double to return a specified value depending on their method argument values:: # given stub = Stub() with stub: stub.foo('hi').returns(10) stub.hello(ANY_ARG).returns(False) stub.bye().raises(SomeException) # when result = stub.foo() # then assert_that(result, is_(10)) If you do not program specific result, the method invocation returns ``None``. "checked" Stub --------------- A "checked Stub" forces the specified collaborator interface:: class Collaborator: def hello(self): return "hello" with Stub(Collaborator) as stub: stub.hello().raises(SomeException) stub.foo().returns(True) # interface mismatch exception stub.hello(1).returns(2) # interface mismatch exception If you invoke an nonexistent method you will get an ``AttributeError`` exception. "free" Spy ---------- Hint: *Spies remember everything that happens to them.* The free spy extends the *free Stub* functionality allowing you to assert on the invocation it receives since its creation:: # given with Spy() as sender: sender.helo().returns("OK") # when sender.send_mail('hi') sender.send_mail('foo@bar.net') # then assert_that(sender.helo(), is_("OK")) assert_that(sender.send_mail, called()) assert_that(sender.send_mail, called().times(2)) assert_that(sender.send_mail, called().with_args('foo@bar.net')) "checked" Spy -------------- As the ``Stubs``, checked spies force you to use the specified collaborator interface:: class Sender: def say(self): return "hi" def send_mail(self, address, force=True): [some amazing code] sender = Spy(Sender) sender.bar() # interface mismatch exception sender.send_mail() # interface mismatch exception sender.send_mail(wrong=1) # interface mismatch exception sender.send_mail('foo', wrong=1) # interface mismatch exception ProxySpy -------- Hint: *Proxy spies forward invocations to its actual instance.* The ``ProxySpy`` extends is a *verified* ``Spy`` that invoke on the actual instance all invocations it receives:: sender = ProxySpy(Sender()) # NOTE: It takes an instance (not class) sender.say('boo!') # interface mismatch exception assert_that(sender.say(), is_("hi")) assert_that(sender.say, called()) "free" Mock ----------- Hint: *Mocks force the predefined script.* Mock objects may be programmed with a sequence of method calls. Later, the double must receive exactly the same sequence of invocations (including argument values). If the sequence does not match, an AssertionError is raised:: with Mock() as smtp: smtp.helo() smtp.mail(ANY_ARG) smtp.rcpt("bill@apple.com") smtp.data(ANY_ARG).returns(True).times(2) smtp.helo() smtp.mail("poormen@home.net") smtp.rcpt("bill@apple.com") smtp.data("somebody there?") smtp.data("I am afraid..") assert_that(smtp, verify()) ``verify()`` asserts invocation order. If your test does not require strict invocation order just use ``any_order_verify()`` matcher instead:: with Mock() as mock: mock.foo() mock.bar() mock.bar() mock.foo() assert_that(mock, any_order_verify()) Programmed invocation sequence also may specify stubbed return values:: with Mock() as mock: mock.foo().returns(10) assert_that(mock.foo, is_(10)) assert_that(mock, verify()) "checked" Mock --------------- The checked variant for mocks too:: class SMTP: def helo(self): [...] def mail(self, address): [...] def rcpt(self, address): [...] with Mock(STMP) as smtp: smtp.wrong() # interface mismatch exception smtp.mail() # interface mismatch exception stub methods ------------ You may create standalone stub methods also:: collaborator = Collaborator() collaborator.foo = method_returning("bye") assertEquals("bye", self.collaborator.foo()) collaborator.foo = method_raising(SomeException) collaborator.foo() # raises SomeException properties ---------- Doublex support stub and spy properties in a pretty easy way compared with other frameworks like python-mock:: class Collaborator(object): @property def prop(self): return 1 @prop.setter def prop(self, value): pass with Spy(Collaborator) as spy: spy.prop = 2 # stubbing its value assert_that(spy.prop, is_(2)) # property getter invoked assert_that(spy, property_got('prop')) spy.prop = 4 # property setter invoked spy.prop = 5 # -- spy.prop = 5 # -- assert_that(spy, property_set('prop')) # set to any value assert_that(spy, property_set('prop').to(4)) assert_that(spy, property_set('prop').to(5).times(2)) assert_that(spy, never(property_set('prop').to(greater_than(6)))) Property doubles require: * Using "checked" doubles, ie: specify a collaborator in constructor. * collaborator must be a new-style class. doublex matchers ================ called ------ called() matches any invocation to a method:: spy.Spy() spy.m1() spy.m2(None) spy.m3("hi", 3.0) spy.m4([1, 2]) assert_that(spy.m1, called()) assert_that(spy.m2, called()) assert_that(spy.m3, called()) assert_that(spy.m4, called()) with_args --------- with_args() matches explicit argument values and hamcrest matchers:: spy.Spy() spy.m1() spy.m2(None) spy.m3(2) spy.m4("hi", 3.0) spy.m5([1, 2]) spy.m6(name="john doe") assert_that(spy.m1, called()) assert_that(spy.m2, called()) assert_that(spy.m1, called().with_args()) assert_that(spy.m2, called().with_args(None)) assert_that(spy.m3, called().with_args(2)) assert_that(spy.m4, called().with_args("hi", 3.0)) assert_that(spy.m5, called().with_args([1, 2])) assert_that(spy.m6, called().with_args(name="john doe")) assert_that(spy.m3, called().with_args(less_than(3))) assert_that(spy.m3, called().with_args(greater_than(1))) assert_that(spy.m6, called().with_args(name=contains_string("doe"))) never ----- ``never()`` is a convenient replacement for hamcrest.is_not:: assert_that(spy.m5, hamcrest.is_not(called())) # is_not() works assert_that(spy.m5, never(called())) # but we recommend due to better error report messages ANY_ARG ======= ``ANY_ARG`` is a special value that matches any subsequent argument values, including no args. For example:: spy.arg0() spy.arg1(1) spy.arg3(1, 2, 3) spy.arg_karg(1, key1='a') assert_that(spy.arg0, called().with_args(ANY_ARG)) assert_that(spy.arg1, called().with_args(ANY_ARG)) assert_that(spy.arg3, called().with_args(1, ANY_ARG)) assert_that(spy.arg_karg, called().with_args(1, ANY_ARG)) Also for stubs:: with Stub() as stub: stub.foo(ANY_ARG).returns(True) stub.bar(1, ANY_ARG).returns(True) assert_that(stub.foo(), is_(True)) assert_that(stub.foo(1), is_(True)) assert_that(stub.foo(key1='a'), is_(True)) assert_that(stub.foo(1, 2, 3, key1='a', key2='b'), is_(True)) assert_that(stub.foo(1, 2, 3), is_(True)) assert_that(stub.foo(1, key1='a'), is_(True)) But, if you want match any single value, use hamcrest matcher ``anything()``:: spy.foo(1, 2, 3) assert_that(spy.foo, called().with_args(1, hamcrest.anything(), 3)) spy.bar(1, key=2) assert_that(spy.bar, called().with_args(1, key=hamcrest.anything())) matchers, matchers, hamcrest matchers... ======================================== doublex support all hamcrest matchers, and their amazing combinations. checking spied calling args --------------------------- :: spy = Spy() spy.foo("abcd") assert_that(spy.foo, called().with_args(has_length(4))) assert_that(spy.foo, called().with_args(has_length(greater_than(3)))) assert_that(spy.foo, called().with_args(has_length(less_than(5)))) assert_that(spy.foo, never(called().with_args(has_length(greater_than(5))))) ``has_length``, ``less_than`` and ``greater_than`` are hamcrest matchers. stubbing -------- :: with Spy() as spy: spy.foo(has_length(less_than(4))).returns('<4') spy.foo(has_length(4)).returns('four') spy.foo(has_length( all_of(greater_than(4), less_than(8)))).returns('48') assert_that(spy.foo((1, 2)), is_('<4')) assert_that(spy.foo('abcd'), is_('four')) assert_that(spy.foo('abcde'), is_('48')) ``all_of``, ``has_length``, ``less_than`` and ``greater_than`` are hamcrest matchers. checking invocation 'times' --------------------------- :: spy.foo() spy.foo(1) spy.foo(1) spy.foo(2) assert_that(spy.never, never(called())) # = 0 times assert_that(spy.foo, called()) # > 0 assert_that(spy.foo, called().times(greater_than(0))) # > 0 (same) assert_that(spy.foo, called().times(4)) # = 4 assert_that(spy.foo, called().times(greater_than(2))) # > 2 assert_that(spy.foo, called().times(less_than(6))) # < 6 assert_that(spy.foo, never(called().with_args(5))) # = 0 times assert_that(spy.foo, called().with_args().times(1)) # = 1 assert_that(spy.foo, called().with_args(anything())) # > 0 assert_that(spy.foo, called().with_args(anything()).times(4)) # = 4 assert_that(spy.foo, called().with_args(1).times(2)) # = 2 assert_that(spy.foo, called().with_args(1).times(greater_than(1))) # > 1 assert_that(spy.foo, called().with_args(1).times(less_than(5))) # < 5 assert_that(spy.foo, called().with_args(1).times( all_of(greater_than(1), less_than(8)))) # 1 < times < 8 ``anything``, ``all_of``, ``less_than`` and ``greater_than`` are hamcrest matchers. Stub observers ============== Stub observers allow you to execute extra code (similar to python-mock "side effects"):: class Observer(object): def __init__(self): self.state = None def update(self, *args, **kargs): self.state = args[0] observer = Observer() stub = Stub() stub.foo.attach(observer.update) stub.foo(2) assert_that(observer.state, is_(2)) Stub delegates ============== The value returned by the stub may be delegated from a function, method or other callable...:: def get_user(): return "Freddy" with Stub() as stub: stub.user().delegates(get_user) stub.foo().delegates(lambda: "hello") assert_that(stub.user(), is_("Freddy")) assert_that(stub.foo(), is_("hello")) It may be delegated from iterables or generators too!:: with Stub() as stub: stub.foo().delegates([1, 2, 3]) assert_that(stub.foo(), is_(1)) assert_that(stub.foo(), is_(2)) assert_that(stub.foo(), is_(3)) Mimic doubles ============= Usually double instances behave as collaborator surrogates, but they do not expose the same class hierarchy, and usually this is pretty enough when the code uses "duck typing":: class A(object): pass class B(A): pass >>> spy = Spy(B()) >>> isinstance(spy, Spy) True >>> isinstance(spy, B) False But some third party library DOES strict type checking using isinstance() invalidating our doubles. For these cases you can use Mimic's. Mimic class can decorate any double class to achieve full replacement instances (Liskov principle):: >>> spy = Mimic(Spy, B) >>> isinstance(spy, B) True >>> isinstance(spy, A) True >>> isinstance(spy, Spy) True >>> isinstance(spy, Stub) True >>> isinstance(spy, object) True .. Local Variables: .. coding: utf-8 .. mode: flyspell .. ispell-local-dictionary: "american" .. End: .. LocalWords: hamcrest doublex-1.7.2/doublex/0000755000175000017500000000000012236777524013720 5ustar piotrpiotrdoublex-1.7.2/doublex/pyDoubles/0000755000175000017500000000000012236777524015666 5ustar piotrpiotrdoublex-1.7.2/doublex/pyDoubles/__init__.py0000644000175000017500000001136312236777524020003 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012,2013 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ This is a wrapper to offer the pyDoubles API implemented over the doublex package. """ import hamcrest from hamcrest.library.object.hasproperty import has_property import doublex from doublex import ANY_ARG, method_returning, method_raising, WrongApiUsage UnexpectedBehavior = AssertionError ArgsDontMatch = AssertionError ApiMismatch = TypeError def empty_stub(): return doublex.Stub() def stub(collaborator=None): return doublex.Stub(collaborator) def empty_spy(): return doublex.Spy() def spy(collaborator=None): return doublex.Spy(collaborator) def proxy_spy(collaborator): return doublex.ProxySpy(collaborator) def empty_mock(): return mock() def assert_that_was_called(method): return assert_that_method(method).was_called() class mock(doublex.Mock): def assert_that_is_satisfied(self): hamcrest.assert_that(self, doublex.verify()) def assert_expectations(self): self.assert_that_is_satisfied() class expect_call(object): def __init__(self, method): if not isinstance(method, doublex.internal.Method): raise doublex.WrongApiUsage self.method = method self.invocation = None self.with_args(ANY_ARG) def with_args(self, *args, **kargs): self.args = args self.kargs = kargs self._remove_previous() with self.method.double: self.invocation = self.method(*args, **kargs) return self def returning(self, value): self._remove_previous() with self.method.double: self.invocation = self.method(*self.args, **self.kargs).returns(value) return self def times(self, n): if n < 2: raise doublex.WrongApiUsage with self.method.double: for i in range(n - 1): self.method.double._manage_invocation(self.invocation) def _remove_previous(self): if self.invocation is None: return self.method.double._stubs.remove(self.invocation) class when(object): def __init__(self, method): self.method = method self.args = (ANY_ARG, ) self.kargs = {} def with_args(self, *args, **kargs): self.args = args self.kargs = kargs return self def then_return(self, retval): with self.method.double: self.method(*self.args, **self.kargs).returns(retval) def then_return_input(self): with self.method.double: self.method(*self.args, **self.kargs).returns_input() def then_raise(self, e): with self.method.double: self.method(*self.args, **self.kargs).raises(e) class assert_that_method(object): def __init__(self, method): if not isinstance(method, doublex.internal.Method): raise doublex.WrongApiUsage() self.method = method self.args = (ANY_ARG,) self.kargs = {} def was_called(self): return self.with_args(*self.args, **self.kargs) def was_never_called(self): hamcrest.assert_that(self.method, doublex.matchers.never(doublex.called())) def with_args(self, *args, **kargs): self.args = args self.kargs = kargs hamcrest.assert_that(self.method, doublex.called().with_args(*args, **kargs)) return self def times(self, n): hamcrest.assert_that( self.method, doublex.called().with_args(*self.args, **self.kargs).times( hamcrest.greater_than_or_equal_to(n))) #-- pyDoubles matchers -- str_containing = hamcrest.contains_string str_not_containing = lambda x: hamcrest.is_not(hamcrest.contains_string(x)) str_length = hamcrest.has_length def obj_with_fields(fields): if not isinstance(fields, dict): raise doublex.WrongApiUsage matchers = [] for key, value in list(fields.items()): matchers.append(has_property(key, value)) return hamcrest.all_of(*matchers) doublex-1.7.2/doublex/internal.py0000644000175000017500000003401412236777524016110 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012,2013 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import threading import collections import hamcrest from hamcrest.core.base_matcher import BaseMatcher try: from functools import total_ordering except ImportError: from .py27_backports import total_ordering from .safeunicode import get_string class WrongApiUsage(Exception): pass class Constant(str): def __repr__(self): return str(self) def __eq__(self, other): return self is other ANY_ARG = Constant('ANY_ARG') UNSPECIFIED = Constant('UNSPECIFIED') def add_indent(text, indent=0): return "%s%s" % (' ' * indent, text) class OperationList(list): def lookup(self, invocation): if not invocation in self: raise LookupError compatible = [i for i in self if i == invocation] return sorted(compatible)[0] def show(self, indent=0): if not self: return add_indent("No one", indent) lines = [add_indent(i, indent) for i in self] return str.join('\n', lines) def count(self, invocation, predicate=None): if predicate is None: return list.count(self, invocation) return [predicate(invocation, i) for i in self].count(True) class Observable(object): def __init__(self): self.observers = [] def attach(self, observer): self.observers.append(observer) def notify(self, *args, **kargs): for ob in self.observers: ob(*args, **kargs) class Method(Observable): def __init__(self, double, name): super(Method, self).__init__() self.double = double self.name = name self._event = threading.Event() def __call__(self, *args, **kargs): invocation = self._create_invocation(args, kargs) retval = self.double._manage_invocation(invocation) if not self.double._setting_up: self._event.set() self.notify(*args, **kargs) return retval def _create_invocation(self, args, kargs): return Invocation._from_args(self.double, self.name, args, kargs) @property def calls(self): if not isinstance(self.double, SpyBase): raise WrongApiUsage("Only Spy derivates store invocations") return [x._context for x in self.double._get_invocations_to(self.name)] def _was_called(self, context, times): invocation = Invocation(self.double, self.name, context) return self.double._received_invocation(invocation, times) def describe_to(self, description): pass def _show(self, indent=0): return add_indent(self, indent) def __repr__(self): return "%s.%s" % (self.double._classname(), self.name) def _show_history(self): method = "method '%s.%s'" % (self.double._classname(), self.name) invocations = self.double._get_invocations_to(self.name) if not invocations: return method + " never invoked" retval = method + " was invoked this way:\n" for i in invocations: retval += add_indent("%s\n" % i, 10) return retval def func_returning(value=None): return lambda *args, **kargs: value def func_returning_input(invocation): def func(*args, **kargs): if not args: raise TypeError("%s has no input args" % invocation) return args[0] return func def func_raising(e): def raise_(e): raise e return lambda *args, **kargs: raise_(e) @total_ordering class Invocation(object): def __init__(self, double, name, context=None): self._double = double self._name = name self._context = context or InvocationContext() self._context.signature = double._proxy.get_signature(name) self.__delegate = func_returning(None) @classmethod def _from_args(cls, double, name, args=(), kargs={}): return Invocation(double, name, InvocationContext(*args, **kargs)) def delegates(self, delegate): if isinstance(delegate, collections.Callable): self.__delegate = delegate return try: self.__delegate = iter(delegate).next except TypeError: reason = "delegates() must be called with callable or iterable instance (got '%s' instead)" % delegate raise WrongApiUsage(reason) def returns(self, value): self._context.retval = value self.delegates(func_returning(value)) return self def returns_input(self): if not self._context.args: raise TypeError("%s has no input args" % self) self.delegates(func_returning_input(self)) return self def raises(self, e): self.delegates(func_raising(e)) def times(self, n): if n < 1: raise WrongApiUsage("times must be >= 1. Use is_not(called()) for 0 times") for i in range(1, n): self._double._manage_invocation(self) def _apply_stub(self, actual_invocation): return actual_invocation._context.apply_on(self.__delegate) def _apply_on_collaborator(self): return self._double._proxy.perform_invocation(self) def __eq__(self, other): return self._double._proxy.same_method(self._name, other._name) and \ self._context.matches(other._context) def __lt__(self, other): return any([self._name < other._name, self._context < other._context]) def __repr__(self): return "%s.%s%s" % (self._double._classname(), self._name, self._context) def _show(self, indent=0): return add_indent(self, indent) ANY_ARG_MUST_BE_LAST = "ANY_ARG must be the last positional argument. " ANY_ARG_WITHOUT_KARGS = "Keyword arguments are not allowed if ANY_ARG is given. " ANY_ARG_CAN_BE_KARG = "ANY_ARG is not allowed as keyword value. " ANY_ARG_DOC = "See http://goo.gl/R6mOt" @total_ordering class InvocationContext(object): def __init__(self, *args, **kargs): self.update_args(args, kargs) self.retval = None self.signature = None self.check_some_args = False def update_args(self, args, kargs): self._check_ANY_ARG_sanity(args, kargs) self.args = args self.kargs = kargs def _check_ANY_ARG_sanity(self, args, kargs): try: if args.index(ANY_ARG) != len(args) - 1: raise WrongApiUsage(ANY_ARG_MUST_BE_LAST + ANY_ARG_DOC) if kargs: raise WrongApiUsage(ANY_ARG_WITHOUT_KARGS + ANY_ARG_DOC) except ValueError: pass if ANY_ARG in kargs.values(): raise WrongApiUsage(ANY_ARG_CAN_BE_KARG + ANY_ARG_DOC) def apply_on(self, method): return method(*self.args, **self.kargs) @classmethod def _assert_kargs_match(cls, kargs1, kargs2): assert sorted(kargs1.keys()) == sorted(kargs2.keys()) for key in kargs1: cls._assert_values_match(kargs1[key], kargs2[key]) @classmethod def _assert_values_match(cls, a, b): if all(isinstance(x, tuple) for x in (a, b)): return cls._assert_tuple_args_match(a, b) if all(isinstance(x, dict) for x in (a, b)): return cls._assert_kargs_match(a, b) if isinstance(a, BaseMatcher): a, b = b, a hamcrest.assert_that(a, hamcrest.is_(b)) @classmethod def _assert_tuple_args_match(cls, a, b): if len(a) != len(b): a, b = cls._adapt_tuples(a, b) for i, j in zip(a, b): cls._assert_values_match(i, j) @classmethod def _adapt_tuples(cls, a, b): if len(a) > len(b): return cls._adapt_tuples(b, a) if a[:-1] != ANY_ARG: raise AssertionError("Incompatible argument list: %s, %s" % (a, b)) a = a[:-1] + (hamcrest.anything(),) * (len(b) - len(a)) return a, b def copy(self): retval = InvocationContext(*self.args, **self.kargs) retval.signature = self.signature return retval def replace_ANY_ARG(self, actual): try: index = self.args.index(ANY_ARG) except ValueError: return self retval = self.copy() args = list(self.args[0:index]) args.extend([hamcrest.anything()] * (len(actual.args) - index)) retval.args = tuple(args) retval.kargs = actual.kargs.copy() return retval def matches(self, other): if ANY_ARG in self.args: matcher, actual = self, other else: matcher, actual = other, self matcher = matcher.replace_ANY_ARG(actual) if matcher.check_some_args: matcher.kargs = self.add_unspecifed_args(matcher) matcher_call_args = matcher.signature.get_call_args(matcher) actual_call_args = actual.signature.get_call_args(actual) try: self._assert_kargs_match(matcher_call_args, actual_call_args) return True except AssertionError: return False def add_unspecifed_args(self, context): arg_spec = context.signature.get_arg_spec() if arg_spec is None: raise WrongApiUsage( 'free spies does not support the with_some_args() matcher') if arg_spec.keywords is not None: raise WrongApiUsage( 'with_some_args() can not be applied to method %s' % self.signature) keys = arg_spec.args retval = dict((k, hamcrest.anything()) for k in keys) retval.update(context.kargs) return retval def __lt__(self, other): if ANY_ARG in other.args or self.args < other.args: return True return sorted(self.kargs.items()) < sorted(other.kargs.items()) def __str__(self): return str(InvocationFormatter(self)) def __repr__(self): return str(self) class InvocationFormatter(object): def __init__(self, context): self.context = context def __str__(self): arg_values = self._format_args(self.context.args) arg_values.extend(self._format_kargs(self.context.kargs)) retval = "(%s)" % str.join(', ', arg_values) if self.context.retval is not None: retval += "-> %s" % repr(self.context.retval) return retval @classmethod def _format_args(cls, args): return [cls._format_value(arg) for arg in args] @classmethod def _format_kargs(cls, kargs): return ['%s=%s' % (key, cls._format_value(val)) for key, val in sorted(kargs.items())] @classmethod def _format_value(cls, arg): if isinstance(arg, unicode): arg = get_string(arg) if isinstance(arg, (int, str, dict)): return repr(arg) return str(arg) class PropertyInvocation(Invocation): def __eq__(self, other): return self._name == other._name class PropertyGet(PropertyInvocation): def __init__(self, double, name): super(PropertyGet, self).__init__(double, name) def _apply_on_collaborator(self): return getattr(self._double._proxy.collaborator, self._name) def __repr__(self): return "get %s.%s" % (self._double._classname(), self._name) class PropertySet(PropertyInvocation): def __init__(self, double, name, value): self.value = value param = InvocationContext(value) super(PropertySet, self).__init__(double, name, param) def _apply_on_collaborator(self): return setattr(self._double._proxy.collaborator, self._name, self.value) def __repr__(self): return "set %s.%s to %s" % (self._double._classname(), self._name, self.value) class Property(property, Observable): def __init__(self, double, key): self.double = double self.key = key property.__init__(self, self.get_value, self.set_value) Observable.__init__(self) def manage(self, invocation): return self.double._manage_invocation(invocation) def get_value(self, obj): if not self.double._setting_up: self.notify() return self.manage(PropertyGet(self.double, self.key)) def set_value(self, obj, value): prop = self.double._proxy.get_class_attr(self.key) if prop.fset is None: raise AttributeError("can't set attribute %s" % self.key) invocation = self.manage(PropertySet(self.double, self.key, value)) if self.double._setting_up: invocation.returns(value) else: self.notify(value) class AttributeFactory(object): """Create double methods, properties or attributes from collaborator""" typemap = dict( instancemethod = Method, method_descriptor = Method, property = Property, # -- python3 -- method = Method, function = Method, ) @classmethod def create(cls, double, key): get_actual_attr = lambda double, key: double._proxy.get_attr(key) typename = double._proxy.get_attr_typename(key) factory = cls.typemap.get(typename, get_actual_attr) attr = factory(double, key) if isinstance(attr, property): setattr(double.__class__, key, attr) else: object.__setattr__(double, key, attr) for hook in double._new_attr_hooks: hook(attr) class SpyBase(object): pass class MockBase(object): pass doublex-1.7.2/doublex/test/0000755000175000017500000000000012236777524014677 5ustar piotrpiotrdoublex-1.7.2/doublex/test/async_race_condition_test.py0000644000175000017500000000147712236777524022476 0ustar piotrpiotr# -*- mode: python; coding: utf-8 -*- # All bugs by Oscar Aceña import time import thread import unittest from doublex import ProxySpy, assert_that, called class Collaborator(object): def write(self, data): time.sleep(0.3) class SUT(object): def __init__(self, collaborator): self.collaborator = collaborator def delayed_write(self): time.sleep(0.1) self.collaborator.write("something") def some_method(self): thread.start_new_thread(self.delayed_write, ()) class AsyncTests(unittest.TestCase): def test_wrong_try_to_test_an_async_invocation(self): # given spy = ProxySpy(Collaborator()) sut = SUT(spy) # when sut.some_method() # then assert_that(spy.write, called().async(1)) doublex-1.7.2/doublex/test/issue-14.py0000644000175000017500000000155612236777524016632 0ustar piotrpiotr# Thanks to Guillermo Pascual (@pasku1) # When you spy a method that has a decorator and you want to check the # arguments with a hamcrest matcher, it seems like matchers are # ignored. from functools import wraps import unittest from doublex import * from hamcrest import * class Collaborator(object): def simple_decorator(func): @wraps(func) def wrapper(self, *args, **kwargs): return func(self, *args, **kwargs) return wrapper @simple_decorator def method_with_two_arguments(self, one, two): pass class ExampleTest(unittest.TestCase): def test_spying_a_method_with_a_decorator(self): collaborator = Spy(Collaborator) collaborator.method_with_two_arguments(1, 'foo bar') assert_that(collaborator.method_with_two_arguments, called().with_args(1, ends_with('bar'))) doublex-1.7.2/doublex/test/pyDoubles_legacy_tests.py0000644000175000017500000006231612236777524021775 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- from unittest import TestCase from hamcrest import is_not, all_of, contains_string, has_length from hamcrest.library.object.hasproperty import * from doublex import * from unit_tests import Collaborator class SomeException(Exception): pass class pyDoubles__ProxySpyTests(TestCase): def setUp(self): self.spy = ProxySpy(Collaborator()) #SAME as pyDoublesSpyTests.test_override_original_method_and_is_called def test_assert_was_called(self): self.spy.hello() assert_that(self.spy.hello, called()) def test_assert_was_called_on_any_method(self): self.spy.something() assert_that(self.spy.something, called()) def test_assert_needs_always_a_method_from_a_double(self): self.failUnlessRaises( WrongApiUsage, assert_that, self.spy, called()) def test_assert_needs_always_a_method_from_a_double_not_the_original(self): self.failUnlessRaises( WrongApiUsage, assert_that, Collaborator().hello, called()) def test_one_method_called_other_wasnt(self): self.spy.something() self.failUnlessRaises( AssertionError, assert_that, self.spy.hello, called()) def test_two_methods_called_assert_on_the_first(self): self.spy.hello() self.spy.something() assert_that(self.spy.hello, called()) # # This is testing internal API! Not applicable # def test_get_method_name(self): # name = _Introspector_().method_name(self.spy.hello) # # self.assertEquals("hello", name) def test_call_original_method(self): self.assertEquals("ok", self.spy.something()) # # This is testing internal API! Not applicable # def test_get_instance_from_method(self): # spy_found = _Introspector_().double_instance_from_method(self.spy.hello) # # self.assertEquals(self.spy, spy_found) def test_assert_was_called_when_wasnt(self): self.failUnlessRaises( AssertionError, assert_that, self.spy.hello, called()) def test_was_called_with_same_parameters(self): self.spy.one_arg_method(1) assert_that(self.spy.one_arg_method, called().with_args(1)) # this is exactly the same that previous! :-S def test_was_called_with_same_parameters_in_variables(self): arg1 = 1 self.spy.one_arg_method(arg1) assert_that(self.spy.one_arg_method, called().with_args(1)) def test_was_called_with_same_parameters_when_not(self): self.spy.one_arg_method(1) args_checker = called().with_args(2) assert_that(not args_checker.matches(self.spy.one_arg_method)) def test_was_called_with_same_params_but_no_params_accepted(self): self.spy.hello() args_checker = called().with_args("something") with self.assertRaises(TypeError): assert_that(not args_checker.matches(self.spy.hello)) def test_was_called_with_several_parameters(self): self.spy.two_args_method(1, 2) args_checker = called().with_args(1, 2) assert_that(args_checker.matches(self.spy.two_args_method)) #SAME as test_was_called_with_same_parameters_when_not def test_was_called_with_parameters_not_matching(self): self.spy.one_arg_method(1) args_checker = called().with_args("2") assert_that(not args_checker.matches(self.spy.one_arg_method)) def test_was_called_with_keyed_args_not_matching(self): self.spy.kwarg_method(key_param="foo") args_checker = called().with_args(key_param="bar") assert_that(not args_checker.matches(self.spy.kwarg_method)) def test_was_called_with_keyed_args_matching(self): self.spy.kwarg_method(key_param="foo") assert_that(self.spy.kwarg_method, called().with_args(key_param="foo")) def test_recorded_call_params_are_displayed(self): self.spy.kwarg_method(key_param="foo") try: assert_that(self.spy.kwarg_method, called().with_args("bar")) except AssertionError, e: assert_that(str(e), contains_string("foo")) def test_stub_out_method(self): with self.spy: self.spy.one_arg_method(ANY_ARG).returns(3) self.assertEquals(3, self.spy.one_arg_method(5)) def test_stub_method_was_called(self): with self.spy: self.spy.one_arg_method(ANY_ARG).returns(3) self.spy.one_arg_method(5) assert_that(self.spy.one_arg_method, called().with_args(5)) def test_stub_out_method_returning_a_list(self): with self.spy: self.spy.one_arg_method(ANY_ARG).returns([1, 2, 3]) assert_that(self.spy.one_arg_method(5), is_([1, 2, 3])) def test_stub_method_returning_list_was_called(self): with self.spy: self.spy.one_arg_method(ANY_ARG).returns([1, 2, 3]) self.spy.one_arg_method(5) assert_that(self.spy.one_arg_method, called().with_args(5)) def test_stub_out_method_with_args(self): with self.spy: self.spy.one_arg_method(2).returns(3) assert_that(self.spy.one_arg_method(2), is_(3)) def test_stub_method_with_args_was_called(self): with self.spy: self.spy.one_arg_method(2).returns(3) self.spy.one_arg_method(2) assert_that(self.spy.one_arg_method, called().with_args(2)) def test_stub_out_method_with_args_calls_actual(self): with self.spy: self.spy.one_arg_method(2).returns(3) assert_that(self.spy.one_arg_method(4), is_(4)) assert_that(self.spy.one_arg_method, called().with_args(4)) def test_stub_out_method_with_several_inputs(self): with self.spy: self.spy.one_arg_method(2).returns(3) self.spy.one_arg_method(3).returns(4) assert_that(self.spy.one_arg_method(2), is_(3)) assert_that(self.spy.one_arg_method(3), is_(4)) def test_recorded_calls_work_on_several_stubs(self): with self.spy: self.spy.one_arg_method(2).returns(3) self.spy.one_arg_method(3).returns(4) self.spy.one_arg_method(2) self.spy.one_arg_method(3) assert_that(self.spy.one_arg_method, called().with_args(2)) assert_that(self.spy.one_arg_method, called().with_args(3)) def test_matching_stub_definition_is_used(self): with self.spy: self.spy.one_arg_method(ANY_ARG).returns(1000) self.spy.one_arg_method(2).returns(3) assert_that(self.spy.one_arg_method(2), is_(3)) assert_that(self.spy.one_arg_method(8), is_(1000)) def test_stub_with_kwargs(self): with self.spy: self.spy.kwarg_method(key_param=2).returns(3) assert_that(self.spy.kwarg_method(key_param=2), is_(3)) assert_that(self.spy.kwarg_method(key_param=6), is_(6)) def test_stub_raising_exception(self): with self.spy: self.spy.hello().raises(SomeException) try: self.spy.hello() self.fail("not raised") except SomeException: pass def test_stub_returning_what_receives(self): with self.spy: self.spy.method_one(ANY_ARG).returns_input() assert_that(self.spy.method_one(20), is_(20)) # Different that pyDoubles. exception raised at setup def test_stub_returning_what_receives_when_no_params(self): try: with self.spy: self.spy.hello().returns_input() self.fail("TypeError should be raised") except TypeError, e: assert_that(str(e), contains_string("Collaborator.hello() has no input args")) def test_be_able_to_return_objects(self): with self.spy: self.spy.one_arg_method(ANY_ARG).returns(Collaborator()) collaborator = self.spy.one_arg_method(1) assert_that(collaborator.one_arg_method(1), is_(1)) def test_any_arg_matcher(self): with self.spy: self.spy.two_args_method(1, ANY_ARG).returns(1000) assert_that(self.spy.two_args_method(1, 2), is_(1000)) assert_that(self.spy.two_args_method(1, 5), is_(1000)) assert_that(self.spy.two_args_method(3, 5), is_not(1000)) # Not supported by pyDoubles def test_any_arg_matcher_with_kwargs(self): with self.spy: self.spy.kwarg_method(key_param=anything()).returns(1000) self.assertEquals(1000, self.spy.kwarg_method(key_param=2)) def test_any_arg_matcher_was_called(self): with self.spy: self.spy.two_args_method(1, 2).returns(1000) self.spy.two_args_method(1, 2) assert_that(self.spy.two_args_method, called().with_args(1, ANY_ARG)) def test_stub_works_with_alias_method(self): with self.spy: self.spy.one_arg_method(1).returns(1000) self.spy.alias_method(1) assert_that(self.spy.one_arg_method, called().with_args(1)) def test_was_never_called(self): assert_that(self.spy.one_arg_method, is_not(called())) def test_was_never_called_is_false(self): self.spy.one_arg_method(1) try: assert_that(self.spy.one_arg_method, is_not(called())) self.fail("it was called indeed!") except AssertionError: pass def test_expect_several_times(self): self.spy.one_arg_method(1) try: assert_that(self.spy.one_arg_method, called().times(2)) self.fail("Should have been called 2 times") except AssertionError: pass def test_fail_incorrect_times_msg_is_human_readable(self): self.spy.one_arg_method(1) try: assert_that(self.spy.one_arg_method, called().times(5)) self.fail("Should have been called 5 times") except AssertionError, e: assert_that(str(e), contains_string("5")) assert_that(str(e), contains_string("one_arg_method")) def test_expect_several_times_matches_exactly(self): self.spy.one_arg_method(1) self.spy.one_arg_method(1) assert_that(self.spy.one_arg_method, called().times(2)) def test_expect_several_times_with_args_definition(self): self.spy.one_arg_method(1) self.spy.one_arg_method(1) assert_that(self.spy.one_arg_method, called().with_args(1).times(2)) def test_expect_several_times_with_incorrect_args(self): self.spy.one_arg_method(1) self.spy.one_arg_method(1) try: assert_that(self.spy.one_arg_method, called().with_args(2).times(2)) self.fail("Must have 1 as an argument") except AssertionError: pass def test_args_match_but_not_number_of_times(self): self.spy.one_arg_method(1) self.spy.one_arg_method(2) try: assert_that(self.spy.one_arg_method, called().with_args(1).times(2)) self.fail("Wrong assertion") except AssertionError: pass class pyDoubles__SpyTests(TestCase): def setUp(self): self.spy = Spy(Collaborator()) def test_override_original_method(self): self.assertTrue(self.spy.hello() is None) def test_override_original_method_and_is_called(self): self.spy.hello() assert_that(self.spy.hello, called()) def test_spy_without_args_is_empty_spy(self): self.spy = Spy() self.assertTrue(self.spy.hello() is None) def test_spy_can_work_from_empty_and_is_called(self): self.spy.hello() assert_that(self.spy.hello, called()) def test_spy_based_on_object_must_check_api_match(self): try: self.spy.hello("unexpected argument") self.fail('Expection should raise: Actual object does not accept parameters') except TypeError: pass def test_check_api_match_with_kwargs(self): self.assertTrue(self.spy.mixed_method(1, key_param=2) is None) def test_check_api_match_with_kwargs_not_used(self): self.assertTrue(self.spy.mixed_method(1) is None) def test_check_api_match_with_kwargs_not_matching(self): try: self.spy.mixed_method(1, 2, 3) self.fail('TypeError not detected!') except TypeError: pass def test_match_call_with_unicode_and_non_ascii_chars(self): non_ascii = u'España' self.spy.one_arg_method(non_ascii) assert_that(self.spy.one_arg_method, called().with_args(non_ascii)) def test_stub_methods_can_be_handled_separately(self): with self.spy: self.spy.one_arg_method(1).returns(1000) self.spy.two_args_method(5, 5).returns(2000) handle1 = self.spy.one_arg_method handle2 = self.spy.two_args_method self.assertEquals(1000, handle1(1)) self.assertEquals(2000, handle2(5, 5)) assert_that(handle1, called().with_args(1)) assert_that(handle2, called().with_args(5, 5)) #SAME as VerifiedSpyTests.test_check_unexisting_method def test_assert_was_called_with_method_not_in_the_api(self): try: assert_that(self.spy.unexisting_method, called()) self.fail("AttributeError should be raised") except AttributeError: pass def test_do_not_call_callable_object_if_wasnt_generated_by_the_framework(self): class CallableObj(): just_testing = True def __call__(self, *args, **kwargs): raise Exception('should not happen') obj = CallableObj() with self.spy: self.spy.one_arg_method(ANY_ARG).returns(obj) self.assertEquals(obj, self.spy.one_arg_method(1), "Wrong returned object") class pyDoubles__MockTests(TestCase): def setUp(self): self.mock = Mock(Collaborator) def test_fail_on_unexpected_call(self): try: self.mock.hello() self.fail('AssertionError should be raised') except AssertionError: pass def test_fail_on_unexpected_call_msg_is_human_readable(self): try: self.mock.hello() except AssertionError, e: assert_that(str(e), contains_string("No one")) def test_define_expectation_and_call_method(self): with self.mock: self.mock.hello() self.assertTrue(self.mock.hello() is None) def test_define_several_expectatiosn(self): with self.mock: self.mock.hello() self.mock.one_arg_method(ANY_ARG) self.assertTrue(self.mock.hello() is None) self.assertTrue(self.mock.one_arg_method(1) is None) def test_define_expectation_args(self): with self.mock: self.mock.one_arg_method(1) self.assertTrue(self.mock.one_arg_method(1) is None) def test_define_expectation_args_and_fail(self): with self.mock: self.mock.one_arg_method(1) try: self.mock.one_arg_method(2) self.fail('Unexpected call') except AssertionError: pass def test_several_expectations_with_args(self): with self.mock: self.mock.one_arg_method(1) self.mock.two_args_method(2, 3) self.assertTrue(self.mock.one_arg_method(1) is None) self.assertTrue(self.mock.two_args_method(2, 3) is None) def test_expect_call_returning_value(self): with self.mock: self.mock.one_arg_method(1).returns(1000) self.assertEquals(1000, self.mock.one_arg_method(1)) def test_assert_expectations_are_satisfied(self): with self.mock: self.mock.hello() assert_that(self.mock, is_not(verify())) def test_assert_satisfied_when_it_really_is(self): with self.mock: self.mock.hello() self.mock.hello() assert_that(self.mock, verify()) def test_number_of_calls_matter(self): with self.mock: self.mock.hello() self.mock.hello() self.mock.hello() assert_that(self.mock, is_not(verify())) # Not applicable to doublex # def test_using_when_or_expect_call_without_double(self): # self.failUnlessRaises(WrongApiUsage, # expect_call, Collaborator()) def test_expectations_on_synonyms(self): with self.mock: self.mock.one_arg_method(ANY_ARG) self.mock.alias_method(1) assert_that(self.mock, verify()) def test_several_expectations_with_different_args(self): with self.mock: self.mock.one_arg_method(1) self.mock.one_arg_method(2) self.mock.one_arg_method(1) self.mock.one_arg_method(1) assert_that(self.mock, is_not(verify())) def test_expect_several_times(self): with self.mock: self.mock.one_arg_method(1).times(2) self.mock.one_arg_method(1) assert_that(self.mock, is_not(verify())) def test_expect_several_times_matches_exactly(self): with self.mock: self.mock.one_arg_method(1).times(2) self.mock.one_arg_method(1) self.mock.one_arg_method(1) assert_that(self.mock, verify()) def test_expect_several_times_without_args_definition(self): with self.mock: self.mock.one_arg_method(ANY_ARG).times(2) self.mock.one_arg_method(1) self.mock.one_arg_method(1) assert_that(self.mock, verify()) def test_defend_agains_less_than_2_times(self): try: with self.mock: self.mock.one_arg_method(ANY_ARG).times(0) self.fail('times cant be less than 1') except WrongApiUsage: pass def test_times_and_return_value(self): with self.mock: self.mock.one_arg_method(ANY_ARG).returns(1000).times(2) self.assertEquals(1000, self.mock.one_arg_method(1)) self.assertEquals(1000, self.mock.one_arg_method(1)) assert_that(self.mock, verify()) def test_times_and_return_value_and_input_args(self): with self.mock: self.mock.one_arg_method(10).returns(1000).times(2) self.assertEquals(1000, self.mock.one_arg_method(10)) self.assertEquals(1000, self.mock.one_arg_method(10)) assert_that(self.mock, verify()) class pyDoubles__MockFromEmptyObjectTests(TestCase): def setUp(self): self.mock = Mock() def test_mock_can_work_from_empty_object(self): with self.mock as mock: mock.hello() self.mock.hello() assert_that(self.mock, verify()) # Not applicable to doublex def test_mock_without_args_is_empty_mock(self): pass def test_several_expectations_in_empty_mock(self): with self.mock: self.mock.hello() self.mock.one_arg_method(1) self.mock.hello() self.mock.one_arg_method(1) assert_that(self.mock, verify()) def test_several_expectations_with_args_in_empty_mock(self): with self.mock: self.mock.one_arg_method(1) self.mock.one_arg_method(2) self.assertTrue(self.mock.one_arg_method(1) is None) self.assertTrue(self.mock.one_arg_method(2) is None) assert_that(self.mock, verify()) class pyDoubles__StubMethodsTests(TestCase): def setUp(self): self.collaborator = Collaborator() def test_method_returning_value(self): self.collaborator.hello = method_returning("bye") self.assertEquals("bye", self.collaborator.hello()) def test_method_args_returning_value(self): self.collaborator.one_arg_method = method_returning("bye") self.assertEquals("bye", self.collaborator.one_arg_method(1)) def test_method_raising_exception(self): self.collaborator.hello = method_raising(SomeException) try: self.collaborator.hello() self.fail("exception not raised") except SomeException: pass class pyDoubles__MatchersTests(TestCase): def setUp(self): self.spy = Spy(Collaborator) def test_str_cotaining_with_exact_match(self): with self.spy: self.spy.one_arg_method(contains_string("abc")).returns(1000) self.assertEquals(1000, self.spy.one_arg_method("abc")) def test_str_containing_with_substr(self): with self.spy: self.spy.one_arg_method(contains_string("abc")).returns(1000) self.assertEqual(1000, self.spy.one_arg_method("XabcX")) def test_str_containing_with_substr_unicode(self): with self.spy: self.spy.one_arg_method(contains_string("abc")).returns(1000) self.assertEquals(1000, self.spy.one_arg_method(u"XabcñX")) def test_str_containing_but_matcher_not_used(self): with self.spy: self.spy.one_arg_method("abc").returns(1000) self.assertNotEquals(1000, self.spy.one_arg_method("XabcX")) def test_was_called_and_substr_matcher(self): self.spy.one_arg_method("XabcX") assert_that(self.spy.one_arg_method, called().with_args(contains_string("abc"))) def test_str_not_containing(self): with self.spy: self.spy.one_arg_method(is_not(contains_string("abc"))).returns(1000) self.assertNotEquals(1000, self.spy.one_arg_method("abc")) def test_str_not_containing_stubs_anything_else(self): with self.spy: self.spy.one_arg_method(is_not(contains_string("abc"))).returns(1000) self.assertEquals(1000, self.spy.one_arg_method("xxx")) def test_str_not_containing_was_called(self): self.spy.one_arg_method("abc") assert_that(self.spy.one_arg_method, called().with_args(is_not(contains_string("xxx")))) def test_several_matchers(self): with self.spy: self.spy.two_args_method( contains_string("abc"), contains_string("xxx")).returns(1000) self.assertNotEquals(1000, self.spy.two_args_method("abc", "yyy")) def test_str_length_matcher(self): with self.spy: self.spy.one_arg_method(has_length(5)).returns(1000) self.assertEquals(1000, self.spy.one_arg_method("abcde")) def test_matchers_when_passed_arg_is_none(self): with self.spy: self.spy.one_arg_method(has_length(5)).returns(1000) self.assertTrue(self.spy.one_arg_method(None) is None) def test_compare_objects_is_not_possible_without_eq_operator(self): class SomeObject(): field1 = field2 = None obj = SomeObject() obj2 = SomeObject() self.spy.one_arg_method(obj) try: assert_that(self.spy.one_arg_method, called().with_args(obj2)) self.fail("they should not match") except AssertionError: pass def test_if_doesnt_match_message_is_human_redable(self): self.spy.one_arg_method("XabcX") try: assert_that(self.spy.one_arg_method, called().with_args(contains_string("xxx"))) except AssertionError, e: assert_that(str(e), contains_string("xxx")) assert_that( str(e), contains_string("string containing")) def test_obj_with_field_matcher(self): obj = Collaborator() obj.id = 20 self.spy.one_arg_method(obj) assert_that(self.spy.one_arg_method, called().with_args(has_property('id', 20))) def test_obj_with_several_fields_matcher(self): obj = Collaborator() obj.id = 21 self.spy.one_arg_method(obj) try: assert_that( self.spy.one_arg_method, called().with_args(all_of( has_property('id', 20), has_property('test_field', 'OK')))) self.fail('Wrong assertion, id field is different') except AssertionError: pass # Not applicable to doublex, cause doublex uses hamcrest matchers # def test_obj_with_field_defends_agains_wrong_usage(self): # self.spy.one_arg_method(Collaborator()) # try: # assert_that_method( # self.spy.one_arg_method).was_called().with_args( # obj_with_fields('id = 20')) # self.fail('Wrong assertion, argument should be a dictionary') # except WrongApiUsage: # pass # NOT APPLICABLE. doubles uses hamcrest matchers #class pyDoubles__CustomMatchersTest(unittest.TestCase): # # def setUp(self): # self.spy = spy(Collaborator()) # # def test_use_custom_matcher(self): # class CustomMatcher(PyDoublesMatcher): # matcher_name = "test matcher" # # def __init__(self, arg): # self.defined_arg = arg # # def matches(self, item): # return True # # when(self.spy.one_arg_method).with_args( # CustomMatcher('zzz')).then_return(1000) # self.assertEquals(1000, self.spy.one_arg_method('xx')) # # def test_custom_matcher_do_not_follow_convention(self): # class CustomMatcher(PyDoublesMatcher): # def matches(self, item): # return False # # self.spy.one_arg_method(1) # try: # assert_that_was_called(self.spy.one_arg_method).with_args( # CustomMatcher()) # self.fail('args dont match!') # except ArgsDontMatch: # pass doublex-1.7.2/doublex/test/pyDoubles/0000755000175000017500000000000012236777524016645 5ustar piotrpiotrdoublex-1.7.2/doublex/test/pyDoubles/hamcrest_integration_tests.py0000644000175000017500000000566412236777524024665 0ustar piotrpiotr# -*- coding: utf-8 -*- """ Authors: Carlos Ble (www.carlosble.com) Ruben Bernardez (www.rubenbp.com) www.iExpertos.com License: Apache 2 (http://www.apache.org/licenses/LICENSE-2.0.html) Project home: https://bitbucket.org/carlosble/pydoubles """ import unittest from hamcrest.core.core import * from hamcrest.library.collection.isdict_containing import has_entry from hamcrest.library.object.haslength import has_length from hamcrest.library.text.isequal_ignoring_case import equal_to_ignoring_case from hamcrest.library.text.stringstartswith import starts_with from doublex.pyDoubles import * from unit_tests import Collaborator class HamcrestIntegrationTest(unittest.TestCase): def setUp(self): self.spy = spy(Collaborator()) def test_use_in_stub_method(self): when(self.spy.one_arg_method).with_args( starts_with('tt')).then_return(1000) self.assertEquals(1000, self.spy.one_arg_method('ttxe')) def test_use_in_spy_call(self): self.spy.one_arg_method('ttxe') assert_that_was_called( self.spy.one_arg_method).with_args(starts_with('tt')) def test_is_matcher(self): class Customer: pass customer = Customer() when(self.spy.one_arg_method).with_args( is_(customer)).then_return(1000) self.assertEquals(1000, self.spy.one_arg_method(customer)) def test_instance_of_matcher(self): when(self.spy.one_arg_method).with_args( instance_of(int)).then_return(1000) self.assertEquals(1000, self.spy.one_arg_method(5)) def test_all_of_matcher(self): text = 'hello' when(self.spy.one_arg_method).with_args( all_of(starts_with('h'), equal_to(text))).then_return(1000) self.assertEquals(1000, self.spy.one_arg_method(text)) def test_has_length_matcher(self): list = [10, 20, 30] when(self.spy.one_arg_method).with_args( has_length(3)).then_return(1000) self.assertEquals(1000, self.spy.one_arg_method(list)) def test_has_entry_matcher(self): list = {'one': 1, 'two': 2} when(self.spy.one_arg_method).with_args( has_entry(equal_to('two'), 2)).then_return(1000) self.assertEquals(1000, self.spy.one_arg_method(list)) def test_equal_to_ignoring_case_matcher(self): self.spy.one_arg_method('hello') assert_that_was_called(self.spy.one_arg_method).with_args( equal_to_ignoring_case('HEllO')) def test_matcher_error_is_human_readable(self): self.spy.one_arg_method('xe') try: assert_that_method(self.spy.one_arg_method).was_called().with_args( starts_with('tt')) except ArgsDontMatch, e: self.assertTrue("tt" in str(e.args)) self.assertTrue("string starting" in str(e.args)) if __name__ == "__main__": print "Use nosetest to run this tests: nosetest hamcrest_integration.py" doublex-1.7.2/doublex/test/pyDoubles/unit_tests.py0000644000175000017500000006763412236777524021440 0ustar piotrpiotr# -*- coding: utf-8 -*- """ Authors: Carlos Ble (www.carlosble.com) Ruben Bernardez (www.rubenbp.com) www.iExpertos.com License: Apache 2 (http://www.apache.org/licenses/LICENSE-2.0.html) Project home: https://bitbucket.org/carlosble/pydoubles """ import unittest import re from nose.tools import nottest from doublex.pyDoubles import * class SomeException(Exception): pass class Collaborator: """ The original object we double in tests """ test_field = "OK" def hello(self): return "hello" def something(self): return "ok" def one_arg_method(self, arg1): return arg1 def two_args_method(self, arg1, arg2): return arg1 + arg2 def kwarg_method(self, key_param=False): return key_param def mixed_method(self, arg1, key_param=False): return key_param + arg1 def void_method(self): pass def method_one(self, arg1): return 1 alias_method = one_arg_method class ProxySpyTests(unittest.TestCase): def setUp(self): self.spy = proxy_spy(Collaborator()) def test_assert_was_called(self): self.spy.hello() assert_that_was_called(self.spy.hello) def test_other_way_of_assert_called(self): self.spy.hello() assert_that_method(self.spy.hello).was_called() def test_assert_was_called_on_any_method(self): self.spy.something() assert_that_was_called(self.spy.something) def test_assert_needs_always_a_method_from_a_double(self): self.failUnlessRaises(WrongApiUsage, assert_that_was_called, self.spy) def test_assert_needs_always_a_method_from_a_double_not_the_original(self): self.failUnlessRaises(WrongApiUsage, assert_that_was_called, Collaborator().hello) def test_one_method_called_other_wasnt(self): self.spy.something() self.failUnlessRaises(UnexpectedBehavior, assert_that_was_called, self.spy.hello) def test_two_methods_called_assert_on_the_first(self): self.spy.hello() self.spy.something() assert_that_was_called(self.spy.hello) # pyDobules internal API specific # def test_get_method_name(self): # name = _Introspector_().method_name(self.spy.hello) # # self.assertEquals("hello", name) def test_call_original_method(self): self.assertEquals("ok", self.spy.something()) # pyDobules internal API specific # def test_get_instance_from_method(self): # spy_found = _Introspector_().double_instance_from_method(self.spy.hello) # # self.assertEquals(self.spy, spy_found) def test_assert_was_called_when_wasnt(self): self.failUnlessRaises(UnexpectedBehavior, assert_that_was_called, self.spy.hello) def test_was_called_with_same_parameters(self): self.spy.one_arg_method(1) assert_that_was_called(self.spy.one_arg_method).with_args(1) def test_was_called_with_same_parameters_in_variables(self): arg1 = 1 self.spy.one_arg_method(arg1) assert_that_was_called(self.spy.one_arg_method).with_args(1) def test_was_called_with_same_parameters_when_not(self): self.spy.one_arg_method(1) args_checker = assert_that_was_called(self.spy.one_arg_method) self.failUnlessRaises(ArgsDontMatch, args_checker.with_args, 2) def test_was_called_with_same_params_but_no_params_accepted(self): self.spy.hello() args_checker = assert_that_was_called(self.spy.hello) self.failUnlessRaises(TypeError, args_checker.with_args, "something") def test_was_called_with_several_parameters(self): self.spy.two_args_method(1, 2) args_checker = assert_that_was_called(self.spy.two_args_method) args_checker.with_args(1, 2) def test_was_called_with_parameters_not_matching(self): self.spy.one_arg_method(1) args_checker = assert_that_was_called(self.spy.one_arg_method) self.failUnlessRaises(ArgsDontMatch, args_checker.with_args, "2") def test_was_called_with_keyed_args_not_matching(self): self.spy.kwarg_method(key_param="foo") args_checker = assert_that_was_called(self.spy.kwarg_method) self.failUnlessRaises(ArgsDontMatch, args_checker.with_args, key_param="bar") def test_was_called_with_keyed_args_matching(self): self.spy.kwarg_method(key_param="foo") assert_that_was_called(self.spy.kwarg_method).with_args( key_param="foo") def test_recorded_call_params_are_displayed(self): self.spy.kwarg_method(key_param="foo") try: assert_that_was_called(self.spy.kwarg_method ).with_args("bar") except ArgsDontMatch, e: self.assertTrue(str(e).find("foo") != -1, str(e)) def test_stub_out_method(self): when(self.spy.one_arg_method).then_return(3) self.assertEquals(3, self.spy.one_arg_method(5)) def test_stub_method_was_called(self): when(self.spy.one_arg_method).then_return(3) self.spy.one_arg_method(5) assert_that_was_called(self.spy.one_arg_method).with_args(5) def test_stub_out_method_returning_a_list(self): when(self.spy.one_arg_method).then_return([1, 2, 3]) self.assertEquals([1, 2, 3], self.spy.one_arg_method(5)) def test_stub_method_returning_list_was_called(self): when(self.spy.one_arg_method).then_return([1, 2, 3]) self.spy.one_arg_method(5) assert_that_was_called(self.spy.one_arg_method).with_args(5) def test_stub_out_method_with_args(self): when(self.spy.one_arg_method).with_args(2).then_return(3) self.assertEquals(3, self.spy.one_arg_method(2)) def test_stub_method_with_args_was_called(self): when(self.spy.one_arg_method).with_args(2).then_return(3) self.spy.one_arg_method(2) assert_that_was_called(self.spy.one_arg_method).with_args(2) def test_stub_out_method_with_args_calls_actual(self): when(self.spy.one_arg_method).with_args(2).then_return(3) self.assertEquals(4, self.spy.one_arg_method(4)) assert_that_was_called(self.spy.one_arg_method).with_args(4) def test_stub_out_method_with_several_inputs(self): when(self.spy.one_arg_method).with_args(2).then_return(3) when(self.spy.one_arg_method).with_args(3).then_return(4) self.assertEquals(3, self.spy.one_arg_method(2)) self.assertEquals(4, self.spy.one_arg_method(3)) def test_recorded_calls_work_on_several_stubs(self): when(self.spy.one_arg_method).with_args(2).then_return(3) when(self.spy.one_arg_method).with_args(3).then_return(4) self.spy.one_arg_method(2) self.spy.one_arg_method(3) assert_that_was_called(self.spy.one_arg_method).with_args(2) assert_that_was_called(self.spy.one_arg_method).with_args(3) def test_matching_stub_definition_is_used(self): when(self.spy.one_arg_method).then_return(1000) when(self.spy.one_arg_method).with_args(2).then_return(3) self.assertEquals(3, self.spy.one_arg_method(2)) self.assertEquals(1000, self.spy.one_arg_method(8)) def test_stub_with_kwargs(self): when(self.spy.kwarg_method).with_args(key_param=2 ).then_return(3) self.assertEquals(3, self.spy.kwarg_method(key_param=2)) self.assertEquals(6, self.spy.kwarg_method(key_param=6)) def test_stub_raising_exception(self): when(self.spy.hello).then_raise(SomeException()) try: self.spy.hello() self.fail("not raised") except SomeException: pass def test_stub_returning_what_receives(self): when(self.spy.method_one).then_return_input() self.assertEquals(20, self.spy.method_one(20)) def test_stub_returning_what_receives_when_no_params(self): when(self.spy.hello).then_return_input() self.failUnlessRaises(ApiMismatch, self.spy.hello) def test_be_able_to_return_objects(self): when(self.spy.one_arg_method).then_return(Collaborator()) collaborator = self.spy.one_arg_method(1) self.assertEquals(1, collaborator.one_arg_method(1)) def test_any_arg_matcher(self): when(self.spy.two_args_method).with_args(1, ANY_ARG).then_return(1000) self.assertEquals(1000, self.spy.two_args_method(1, 2)) self.assertEquals(1000, self.spy.two_args_method(1, 5)) def test_any_arg_matcher_was_called(self): when(self.spy.two_args_method).with_args(1, 2).then_return(1000) self.spy.two_args_method(1, 2) assert_that_was_called(self.spy.two_args_method ).with_args(1, ANY_ARG) def test_stub_works_with_alias_method(self): when(self.spy.one_arg_method).with_args(1).then_return(1000) self.spy.alias_method(1) assert_that_was_called(self.spy.one_arg_method ).with_args(1) def test_was_never_called(self): assert_that_method(self.spy.one_arg_method).was_never_called() def test_was_never_called_is_false(self): self.spy.one_arg_method(1) try: assert_that_method(self.spy.one_arg_method).was_never_called() self.fail("it was called indeed!") except UnexpectedBehavior: pass def test_expect_several_times(self): self.spy.one_arg_method(1) try: assert_that_method(self.spy.one_arg_method).was_called().times(2) self.fail("Should have been called 2 times") except UnexpectedBehavior: pass def test_fail_incorrect_times_msg_is_human_readable(self): self.spy.one_arg_method(1) try: assert_that_method(self.spy.one_arg_method).was_called().times(5) self.fail("Should have been called 2 times") except UnexpectedBehavior, e: for arg in e.args: if re.search("5", arg) and re.search("one_arg_method", arg): return self.fail("No enough readable exception message") def test_expect_several_times_matches_exactly(self): self.spy.one_arg_method(1) self.spy.one_arg_method(1) assert_that_method(self.spy.one_arg_method).was_called().times(2) def test_expect_several_times_with_args_definition(self): self.spy.one_arg_method(1) self.spy.one_arg_method(1) assert_that_method(self.spy.one_arg_method).was_called().with_args(1).times(2) def test_expect_several_times_with_incorrect_args(self): self.spy.one_arg_method(1) self.spy.one_arg_method(1) try: assert_that_method(self.spy.one_arg_method).was_called().with_args(2).times(2) self.fail("Must have 1 as an argument") except ArgsDontMatch: pass def test_args_match_but_not_number_of_times(self): self.spy.one_arg_method(1) self.spy.one_arg_method(2) try: assert_that_method(self.spy.one_arg_method ).was_called().with_args(1).times(2) self.fail("Wrong assertion") except UnexpectedBehavior: pass # pyDobules internal API specific #class MethodPoolTests(unittest.TestCase): # # def setUp(self): # self.pool = _MethodPool_() # self.method_name = "some_method" # self.pool.add_invocation( # CallDescription(self.method_name, (1, 2))) # # def test_call_args_match(self): # self.assertTrue( # self.pool.matching_invocations_by_args( # CallDescription(self.method_name, (1, 2), {}))) # # def test_call_args_match_with_any(self): # self.assertTrue( # self.pool.matching_invocations_by_args( # CallDescription(self.method_name, (1, ANY_ARG), {}))) class SpyTests(unittest.TestCase): def setUp(self): self.spy = spy(Collaborator()) def test_override_original_method(self): self.assertTrue(self.spy.hello() is None) def test_override_original_method_and_is_called(self): self.spy.hello() assert_that_was_called(self.spy.hello) def test_spy_can_work_from_empty_object(self): self.spy = empty_spy() self.assertTrue(self.spy.hello() is None) def test_spy_without_args_is_empty_spy(self): self.spy = spy() self.assertTrue(self.spy.hello() is None) def test_spy_can_work_from_empty_and_is_called(self): self.spy.hello() assert_that_was_called(self.spy.hello) def test_spy_based_on_object_must_check_api_match(self): try: self.spy.hello("unexpected argument") self.fail('Expection should raise: Actual objet does not accept parameters') except ApiMismatch: pass def test_check_api_match_with_kwargs(self): self.assertTrue(self.spy.mixed_method(1, key_param=2) is None) def test_check_api_match_with_kwargs_not_used(self): self.assertTrue(self.spy.mixed_method(1) is None) def test_check_api_match_with_kwargs_not_matching(self): try: self.spy.mixed_method(1, 2, 3) self.fail('Api mismatch not detected') except ApiMismatch: pass def test_match_call_with_unicode_and_non_ascii_chars(self): non_ascii = u'España' self.spy.one_arg_method(non_ascii) assert_that_was_called(self.spy.one_arg_method).with_args( non_ascii) def test_stub_methods_can_be_handled_separately(self): when(self.spy.one_arg_method).with_args(1).then_return(1000) when(self.spy.two_args_method).with_args(5, 5).then_return(2000) handle1 = self.spy.one_arg_method handle2 = self.spy.two_args_method self.assertEquals(1000, handle1(1)) self.assertEquals(2000, handle2(5, 5)) assert_that_was_called(handle1).with_args(1) assert_that_was_called(handle2).with_args(5, 5) def test_assert_was_called_with_method_not_in_the_api(self): #:pyDoubles # self.failUnlessRaises(ApiMismatch, # assert_that_was_called, self.spy.unexisting_method) try: self.spy.unexisting_method() self.fail("Exception should be raised") except AttributeError: pass def test_do_not_call_callable_object_if_wasnt_generated_by_the_framework(self): class CallableObj(): just_testing = True def __call__(self, *args, **kwargs): raise Exception('should not happen') obj = CallableObj() when(self.spy.one_arg_method).then_return(obj) self.assertEquals(obj, self.spy.one_arg_method(1), "Wrong returned object") # bitbucket Issue #5 def test_fail_missing_fluent_method(self): try: self.spy.one_arg_method(1) assert_that_was_called(self.spy.one_arg_method).with_params(2) # should be with_args self.fail("TypeError should be raised") except AttributeError, e: expected = "'assert_that_method' object has no attribute 'with_params'" hamcrest.assert_that(str(e), hamcrest.contains_string(expected)) class MockTests(unittest.TestCase): def setUp(self): self.mock = mock(Collaborator()) def test_fail_on_unexpected_call(self): try: self.mock.hello() self.fail('UnexpectedBehavior should be raised') except UnexpectedBehavior: pass def test_fail_on_unexpected_call_msg_is_human_readable(self): try: self.mock.hello() except UnexpectedBehavior, e: for arg in e.args: if re.search("No one", arg): return self.fail("No enough readable exception message") def test_define_expectation_and_call_method(self): expect_call(self.mock.hello) self.assertTrue(self.mock.hello() is None) def test_define_several_expectatiosn(self): expect_call(self.mock.hello) expect_call(self.mock.one_arg_method) self.assertTrue(self.mock.hello() is None) self.assertTrue(self.mock.one_arg_method(1) is None) def test_define_expectation_args(self): expect_call(self.mock.one_arg_method).with_args(1) self.assertTrue(self.mock.one_arg_method(1) is None) def test_define_expectation_args_and_fail(self): expect_call(self.mock.one_arg_method).with_args(1) try: self.mock.one_arg_method(2) self.fail('Unexpected call') except UnexpectedBehavior: pass def test_several_expectations_with_args(self): expect_call(self.mock.one_arg_method).with_args(1) expect_call(self.mock.two_args_method).with_args(2, 3) self.assertTrue(self.mock.one_arg_method(1) is None) self.assertTrue(self.mock.two_args_method(2, 3) is None) def test_expect_call_returning_value(self): expect_call(self.mock.one_arg_method).with_args(1).returning(1000) self.assertEquals(1000, self.mock.one_arg_method(1)) def test_assert_expectations_are_satisfied(self): expect_call(self.mock.hello) try: self.mock.assert_that_is_satisfied() self.fail('Not satisfied!') except UnexpectedBehavior: pass def test_assert_expectations_alternative(self): expect_call(self.mock.hello) try: self.mock.assert_expectations() self.fail('Not satisfied') except UnexpectedBehavior: pass def test_assert_satisfied_when_it_really_is(self): expect_call(self.mock.hello) self.mock.hello() self.mock.assert_that_is_satisfied() def test_number_of_calls_matter(self): expect_call(self.mock.hello) self.mock.hello() self.mock.hello() self.failUnlessRaises(UnexpectedBehavior, self.mock.assert_that_is_satisfied) def test_using_when_or_expect_call_without_double(self): self.failUnlessRaises(WrongApiUsage, expect_call, Collaborator()) def test_expectations_on_synonyms(self): expect_call(self.mock.one_arg_method) self.mock.alias_method(1) self.mock.assert_that_is_satisfied() def test_several_expectations_with_different_args(self): expect_call(self.mock.one_arg_method).with_args(1) expect_call(self.mock.one_arg_method).with_args(2) self.mock.one_arg_method(1) self.mock.one_arg_method(1) self.failUnlessRaises(UnexpectedBehavior, self.mock.assert_that_is_satisfied) def test_expect_several_times(self): expect_call(self.mock.one_arg_method).with_args(1).times(2) self.mock.one_arg_method(1) self.failUnlessRaises(UnexpectedBehavior, self.mock.assert_that_is_satisfied) def test_expect_several_times_matches_exactly(self): expect_call(self.mock.one_arg_method).with_args(1).times(2) self.mock.one_arg_method(1) self.mock.one_arg_method(1) self.mock.assert_that_is_satisfied() def test_expect_several_times_without_args_definition(self): expect_call(self.mock.one_arg_method).times(2) self.mock.one_arg_method(1) self.mock.one_arg_method(1) self.mock.assert_that_is_satisfied() def test_defend_agains_less_than_2_times(self): try: expect_call(self.mock.one_arg_method).times(1) self.fail('times cant be less than 2') except WrongApiUsage: pass def test_times_and_return_value(self): expect_call(self.mock.one_arg_method).returning(1000).times(2) self.assertEquals(1000, self.mock.one_arg_method(1)) self.assertEquals(1000, self.mock.one_arg_method(1)) self.mock.assert_that_is_satisfied() def test_times_and_return_value_and_input_args(self): expect_call(self.mock.one_arg_method).with_args(10).returning(1000).times(2) self.assertEquals(1000, self.mock.one_arg_method(10)) self.assertEquals(1000, self.mock.one_arg_method(10)) self.mock.assert_that_is_satisfied() class MockFromEmptyObjectTests(unittest.TestCase): def setUp(self): self.mock = empty_mock() def test_mock_can_work_from_empty_object(self): expect_call(self.mock.hello) self.mock.hello() self.mock.assert_that_is_satisfied() def test_mock_without_args_is_empty_mock(self): self.mock = mock() expect_call(self.mock.hello) self.mock.hello() self.mock.assert_that_is_satisfied() def test_several_expectations_in_empty_mock(self): expect_call(self.mock.hello) expect_call(self.mock.one_arg_method).with_args(1) self.mock.hello() self.mock.one_arg_method(1) self.mock.assert_that_is_satisfied() def test_several_expectations_with_args_in_empty_mock(self): expect_call(self.mock.one_arg_method).with_args(1) expect_call(self.mock.one_arg_method).with_args(2) self.assertTrue(self.mock.one_arg_method(1) is None) self.assertTrue(self.mock.one_arg_method(2) is None) self.mock.assert_that_is_satisfied() class StubMethodsTests(unittest.TestCase): def setUp(self): self.collaborator = Collaborator() def test_method_returning_value(self): self.collaborator.hello = method_returning("bye") self.assertEquals("bye", self.collaborator.hello()) def test_method_args_returning_value(self): self.collaborator.one_arg_method = method_returning("bye") self.assertEquals("bye", self.collaborator.one_arg_method(1)) def test_method_raising_exception(self): self.collaborator.hello = method_raising(SomeException()) try: self.collaborator.hello() self.fail("exception not raised") except SomeException: pass class MatchersTests(unittest.TestCase): def setUp(self): self.spy = spy(Collaborator()) def test_str_cotaining_with_exact_match(self): when(self.spy.one_arg_method).with_args( str_containing("abc")).then_return(1000) self.assertEquals(1000, self.spy.one_arg_method("abc")) def test_str_containing_with_substr(self): when(self.spy.one_arg_method).with_args( str_containing("abc")).then_return(1000) self.assertEquals(1000, self.spy.one_arg_method("XabcX")) def test_str_containing_with_substr_unicode(self): when(self.spy.one_arg_method).with_args( str_containing("abc")).then_return(1000) self.assertEquals(1000, self.spy.one_arg_method(u"XabcñX")) def test_str_containing_but_matcher_not_used(self): when(self.spy.one_arg_method).with_args( "abc").then_return(1000) self.assertNotEquals(1000, self.spy.one_arg_method("XabcX")) def test_was_called_and_substr_matcher(self): self.spy.one_arg_method("XabcX") assert_that_was_called(self.spy.one_arg_method).with_args( str_containing("abc")) def test_str_not_containing(self): when(self.spy.one_arg_method).with_args( str_not_containing("abc")).then_return(1000) self.assertNotEquals(1000, self.spy.one_arg_method("abc")) def test_str_not_containing_stubs_anything_else(self): when(self.spy.one_arg_method).with_args( str_not_containing("abc")).then_return(1000) self.assertEquals(1000, self.spy.one_arg_method("xxx")) def test_str_not_containing_was_called(self): self.spy.one_arg_method("abc") assert_that_was_called(self.spy.one_arg_method).with_args( str_not_containing("xxx")) def test_several_matchers(self): when(self.spy.two_args_method).with_args( str_containing("abc"), str_containing("xxx")).then_return(1000) self.assertNotEquals(1000, self.spy.two_args_method("abc", "yyy")) def test_str_length_matcher(self): when(self.spy.one_arg_method).with_args( str_length(5)).then_return(1000) self.assertEquals(1000, self.spy.one_arg_method("abcde")) def test_matchers_when_passed_arg_is_none(self): when(self.spy.one_arg_method).with_args( str_length(5)).then_return(1000) self.assertTrue(self.spy.one_arg_method(None) is None) def test_compare_objects_is_not_possible_without_eq_operator(self): class SomeObject(): field1 = field2 = None obj = SomeObject() obj2 = SomeObject() self.spy.one_arg_method(obj) try: assert_that_method(self.spy.one_arg_method).was_called().with_args(obj2) self.fail('they should not match') except ArgsDontMatch: pass def test_if_doesnt_match_message_is_human_redable(self): self.spy.one_arg_method("XabcX") try: assert_that_was_called(self.spy.one_arg_method).with_args( str_containing("xxx")) except ArgsDontMatch, e: self.assertTrue("xxx" in str(e.args), str(e.args)) self.assertTrue("string containing" in str(e.args)) def test_obj_with_field_matcher(self): obj = Collaborator() obj.id = 20 self.spy.one_arg_method(obj) assert_that_method(self.spy.one_arg_method ).was_called().with_args(obj_with_fields({'id': 20})) def test_obj_with_several_fields_matcher(self): obj = Collaborator() obj.id = 21 self.spy.one_arg_method(obj) try: assert_that_method( self.spy.one_arg_method).was_called().with_args( obj_with_fields({ 'id': 20, 'test_field': 'OK'})) self.fail('Wrong assertion, id field is different') except ArgsDontMatch: pass def test_obj_with_field_defends_agains_wrong_usage(self): self.spy.one_arg_method(Collaborator()) try: assert_that_method( self.spy.one_arg_method).was_called().with_args( obj_with_fields('id = 20')) self.fail('Wrong assertion, argument should be a dictionary') except WrongApiUsage: pass class StubTests(unittest.TestCase): def test_free_stub(self): my_stub = empty_stub() self.assertTrue(my_stub.hello() is None) def test_restricted_stub(self): my_stub = stub(Collaborator()) when(my_stub.something).then_return(10) self.assertEquals(10, my_stub.something()) def test_restricted_stub_method_not_stubbed(self): my_stub = stub(Collaborator()) self.assertEquals(None, my_stub.hello()) # Create hamcrest matchers instead #class CustomMatchersTest(unittest.TestCase): # # def setUp(self): # self.spy = spy(Collaborator()) # # def test_use_custom_matcher(self): # class CustomMatcher(PyDoublesMatcher): # matcher_name = "test matcher" # # def __init__(self, arg): # self.defined_arg = arg # # def matches(self, item): # return True # # when(self.spy.one_arg_method).with_args( # CustomMatcher('zzz')).then_return(1000) # self.assertEquals(1000, self.spy.one_arg_method('xx')) # # def test_custom_matcher_do_not_follow_convention(self): # class CustomMatcher(PyDoublesMatcher): # def matches(self, item): # return False # # self.spy.one_arg_method(1) # try: # assert_that_was_called(self.spy.one_arg_method).with_args( # CustomMatcher()) # self.fail('args dont match!') # except ArgsDontMatch: # pass if __name__ == "__main__": print "Use nosetest to run this tests: nosetest unit.py" doublex-1.7.2/doublex/test/pyDoubles/__init__.py0000644000175000017500000000000012236777524020744 0ustar piotrpiotrdoublex-1.7.2/doublex/test/report_tests.py0000644000175000017500000002526612236777524020021 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA from unittest import TestCase from hamcrest import assert_that, is_, is_not, contains_string, greater_than from nose.tools import nottest import doublex from doublex.internal import Invocation, InvocationContext from unit_tests import ObjCollaborator def create_invocation(name, args=None, kargs=None, retval=None): stub = doublex.Stub() args = args or tuple() kargs = kargs or {} context = InvocationContext(*args, **kargs) context.retval = retval invocation = Invocation(stub, name, context) return invocation class InvocationReportTests(TestCase): def test_int_arg_method_returning_int(self): invocation = create_invocation('foo', (1,), None, retval=1) assert_that(str(invocation), is_('Stub.foo(1)-> 1')) def test_ANY_arg_method_returning_none(self): invocation = create_invocation('foo', (doublex.ANY_ARG,)) assert_that(str(invocation), is_('Stub.foo(ANY_ARG)')) # @nottest # def test_unicode_arg_method(self): # self.add_invocation('foo', (u'ñandú',)) # # print self.render() # # assert_that(self.render(), # is_("foo(u'ñandú')")) class MessageMixin(object): def assert_with_message(self, value, matcher, message): try: assert_that(value, matcher) self.fail("Exception should be raised") except AssertionError, e: assert_that(str(e).strip(), is_(message.strip())) class SpyReportTest(TestCase, MessageMixin): def test_called(self): spy = doublex.Spy() expected = ''' Expected: these calls: Spy.expected(ANY_ARG) but: calls that actually ocurred were: No one''' self.assert_with_message(spy.expected, doublex.called(), expected) def test_nerver_called(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) spy.unexpected(5) self.assert_with_message( spy.unexpected, doublex.never(doublex.called()), ''' Expected: none of these calls: Spy.unexpected(ANY_ARG) but: calls that actually ocurred were: Spy.foo(1) Spy.foo(2) Spy.unexpected(5)''') def test_hamcrest_not_called(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) spy.unexpected(5) self.assert_with_message( spy.unexpected, is_not(doublex.called()), ''' Expected: not these calls: Spy.unexpected(ANY_ARG) but: was ''') def test_called_times_int(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) self.assert_with_message( spy.foo, doublex.called().times(1), ''' Expected: these calls: Spy.foo(ANY_ARG) -- times: 1 but: calls that actually ocurred were: Spy.foo(1) Spy.foo(2)''') def test_called_times_matcher(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) self.assert_with_message( spy.foo, doublex.called().times(greater_than(3)), ''' Expected: these calls: Spy.foo(ANY_ARG) -- times: a value greater than <3> but: calls that actually ocurred were: Spy.foo(1) Spy.foo(2)''') def test_called_with(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) self.assert_with_message( spy.expected, doublex.called().with_args(3), ''' Expected: these calls: Spy.expected(3) but: calls that actually ocurred were: Spy.foo(1) Spy.foo(2)''') def test_never_called_with(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) spy.unexpected(2) self.assert_with_message( spy.unexpected, doublex.never(doublex.called().with_args(2)), ''' Expected: none of these calls: Spy.unexpected(2) but: calls that actually ocurred were: Spy.foo(1) Spy.foo(2) Spy.unexpected(2)''') def test_hamcrest_not_called_with(self): spy = doublex.Spy() spy.foo(1) spy.foo(2) spy.unexpected(2) self.assert_with_message( spy.unexpected, is_not(doublex.called().with_args(2)), ''' Expected: not these calls: Spy.unexpected(2) but: was ''') def test_called_with_matcher(self): spy = doublex.Spy() self.assert_with_message( spy.unexpected, doublex.called().with_args(greater_than(1)), ''' Expected: these calls: Spy.unexpected(a value greater than <1>) but: calls that actually ocurred were: No one''') def test_never_called_with_matcher(self): spy = doublex.Spy() spy.unexpected(2) self.assert_with_message( spy.unexpected, doublex.never(doublex.called().with_args(greater_than(1))), ''' Expected: none of these calls: Spy.unexpected(a value greater than <1>) but: calls that actually ocurred were: Spy.unexpected(2)''') def test__hamcrest_not__called_with_matcher(self): spy = doublex.Spy() spy.unexpected(2) self.assert_with_message( spy.unexpected, is_not(doublex.called().with_args(greater_than(1))), ''' Expected: not these calls: Spy.unexpected(a value greater than <1>) but: was ''') class MockReportTest(TestCase, MessageMixin): def setUp(self): self.mock = doublex.Mock() def assert_expectation_error(self, expected_message): self.assert_with_message(self.mock, doublex.verify(), expected_message) def test_expect_none_but_someting_unexpected_called(self): expected_message = ''' Expected: these calls: No one but: this call was not expected: Mock.unexpected() ''' try: self.mock.unexpected() self.fail("This should raise exception") except AssertionError, e: assert_that(str(e), is_(expected_message)) def test_expect_1_void_method_but_nothing_called(self): with self.mock: self.mock.expected() expected_message = ''' Expected: these calls: Mock.expected() but: calls that actually ocurred were: No one ''' self.assert_expectation_error(expected_message) def test_expect_2_void_methods_but_nothing_called(self): with self.mock: self.mock.foo() self.mock.bar() expected_message = ''' Expected: these calls: Mock.foo() Mock.bar() but: calls that actually ocurred were: No one ''' self.assert_expectation_error(expected_message) def test_expect_method_with_2_int_args_returning_int_but_nothing_called(self): with self.mock: self.mock.foo(1, 2).returns(1) expected_message = ''' Expected: these calls: Mock.foo(1, 2)-> 1 but: calls that actually ocurred were: No one ''' self.assert_expectation_error(expected_message) def test_except_method_with_2_str_args_returning_str_but_nothing_called(self): with self.mock: self.mock.foo('a', 'b').returns('c') expected_message = ''' Expected: these calls: Mock.foo('a', 'b')-> 'c' but: calls that actually ocurred were: No one ''' self.assert_expectation_error(expected_message) def test_except_method_with_2_kwargs_returning_dict_but_nothing_called(self): with self.mock: self.mock.foo(num=1, color='red').returns({'key': 1}) expected_message = ''' Expected: these calls: Mock.foo(color='red', num=1)-> {'key': 1} but: calls that actually ocurred were: No one ''' self.assert_expectation_error(expected_message) def test_expect_4_calls_but_only_2_called(self): with self.mock: self.mock.foo() self.mock.foo() self.mock.bar() self.mock.bar() self.mock.foo() self.mock.bar() expected_message = ''' Expected: these calls: Mock.foo() Mock.foo() Mock.bar() Mock.bar() but: calls that actually ocurred were: Mock.foo() Mock.bar() ''' self.assert_expectation_error(expected_message) class PropertyReportTests(TestCase, MessageMixin): def test_expected_get(self): spy = doublex.Spy(ObjCollaborator) expected_message = ''' Expected: these calls: get ObjCollaborator.prop but: calls that actually ocurred were: No one ''' self.assert_with_message( spy, doublex.property_got('prop'), expected_message) def test_unexpected_get(self): expected_message = ''' Expected: none of these calls: get ObjCollaborator.prop but: calls that actually ocurred were: get ObjCollaborator.prop ''' spy = doublex.Spy(ObjCollaborator) spy.prop self.assert_with_message( spy, doublex.never(doublex.property_got('prop')), expected_message) def test_expected_set(self): spy = doublex.Spy(ObjCollaborator) expected_message = ''' Expected: these calls: set ObjCollaborator.prop to ANYTHING but: calls that actually ocurred were: No one ''' self.assert_with_message( spy, doublex.property_set('prop'), expected_message) def test_unexpected_set(self): expected_message = ''' Expected: none of these calls: set ObjCollaborator.prop to ANYTHING but: calls that actually ocurred were: set ObjCollaborator.prop to unexpected ''' spy = doublex.Spy(ObjCollaborator) spy.prop = 'unexpected' self.assert_with_message( spy, doublex.never(doublex.property_set('prop')), expected_message) doublex-1.7.2/doublex/test/unit_tests.py0000644000175000017500000013235212236777524017460 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012,2013 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import sys from unittest import TestCase import itertools import thread import threading import io import copy from hamcrest import is_not, all_of, contains_string, has_length from hamcrest.library.text.stringcontainsinorder import * from hamcrest.library.object.hasproperty import * from hamcrest.library.number.ordering_comparison import * from doublex import * from doublex.matchers import MatcherRequiredError from doublex.internal import InvocationContext class InvocationContextTests(TestCase): def test_order(self): c1 = InvocationContext(1) c2 = InvocationContext(2) contexts = [c2, c1] contexts.sort() assert_that(contexts[0], is_(c1)) def test_order_ANY_ARG(self): c1 = InvocationContext(1) c2 = InvocationContext(ANY_ARG) contexts = [c2, c1] contexts.sort() assert_that(contexts[0], is_(c1)) class FreeStubTests(TestCase): def setUp(self): self.stub = Stub() def test_record_invocation(self): with self.stub: self.stub.foo().returns(2) assert_that(self.stub.foo(), is_(2)) def test_using_alias_in_context(self): with self.stub as stub: stub.foo().returns(2) assert_that(self.stub.foo(), is_(2)) def test_creating_double_with_context(self): with Stub() as stub: stub.foo().returns(2) assert_that(stub.foo(), is_(2)) def test_record_invocation_with_args(self): with self.stub: self.stub.foo(1, param='hi').returns(2) assert_that(self.stub.foo(1, param='hi'), is_(2)) def test_record_invocation_with_wrong_args_returns_None(self): with self.stub: self.stub.foo(1, param='hi').returns(2) assert_that(self.stub.foo(1, param='wrong'), is_(None)) def test_not_stubbed_method_returns_None(self): with self.stub: self.stub.foo().returns(True) assert_that(self.stub.unknown(), is_(None)) def test_returns_input(self): with Stub() as stub: stub.foo(1).returns_input() assert_that(stub.foo(1), is_(1)) def test_raises(self): with self.stub: self.stub.foo(2).raises(SomeException) try: self.stub.foo(2) self.fail("It should raise SomeException") except SomeException: pass class StubTests(TestCase): def setUp(self): self.stub = Stub(Collaborator) def test_stubbing_a_existing_method(self): with self.stub: self.stub.hello().returns("bye") assert_that(self.stub.hello(), is_("bye")) def test_from_instance(self): stub = Stub(Collaborator()) with stub: stub.hello().returns("bye") assert_that(stub.hello(), is_("bye")) def test_stubbing_a_unexisting_method_raises_error(self): try: with self.stub: self.stub.wrong().returns("bye") except AttributeError as e: expected = "'Collaborator' object has no attribute 'wrong'" assert_that(str(e), contains_string(expected)) def test_stubbing_with_wrong_args_raises_error(self): try: with self.stub: self.stub.hello(1).returns("bye") except TypeError as e: expected = "hello() takes exactly 1 argument (2 given)" if sys.version_info >= (3,): expected = "hello() takes exactly 1 positional argument (2 given)" assert_that(str(e), contains_string(expected)) # bitbucket issue #6 def test_keyword_or_positional(self): with self.stub: self.stub.kwarg_method(1).returns(1000) self.stub.kwarg_method(2).returns(2000) self.stub.kwarg_method(key_param=6).returns(6000) assert_that(self.stub.kwarg_method(1), is_(1000)) assert_that(self.stub.kwarg_method(2), is_(2000)) assert_that(self.stub.kwarg_method(key_param=6), is_(6000)) assert_that(self.stub.kwarg_method(key_param=6), is_(6000)) # FIXME: new on 1.7 def test_keyworked_or_positional_are_equivalent(self): with self.stub: self.stub.kwarg_method(1).returns(1000) self.stub.kwarg_method(key_param=6).returns(6000) assert_that(self.stub.kwarg_method(1), is_(1000)) assert_that(self.stub.kwarg_method(key_param=1), is_(1000)) assert_that(self.stub.kwarg_method(6), is_(6000)) assert_that(self.stub.kwarg_method(key_param=6), is_(6000)) def test_returning_tuple(self): with self.stub: self.stub.hello().returns((3, 4)) assert_that(self.stub.hello(), is_((3, 4))) class AccessingActualAttributes(TestCase): def test_read_class_attribute_providing_class(self): stub = Stub(Collaborator) assert_that(stub.class_attr, is_("OK")) def test_read_class_attribute_providing_instance(self): stub = Stub(Collaborator()) assert_that(stub.class_attr, is_("OK")) # New in version 1.6.5 def test_proxyspy_read_instance_attribute(self): stub = Stub(Collaborator()) assert_that(stub.instance_attr, is_(300)) class AdhocAttributesTests(TestCase): "all doubles accepts ad-hoc attributes" def test_add_attribute_for_free_stub(self): sut = Stub() sut.adhoc = 1 def test_add_attribute_for_verified_stub(self): sut = Stub(Collaborator) sut.adhoc = 1 def test_add_attribute_for_free_spy(self): sut = Spy() sut.adhoc = 1 def test_add_attribute_for_verified_spy(self): sut = Spy(Collaborator) sut.adhoc = 1 def test_add_attribute_for_proxyspy(self): sut = ProxySpy(Collaborator()) sut.adhoc = 1 def test_add_attribute_for_free_mock(self): sut = Mock() sut.adhoc = 1 def test_add_attribute_for_verified_mock(self): sut = Mock(Collaborator) sut.adhoc = 1 class FreeSpyTests(TestCase): def setUp(self): self.spy = Spy() def test_simple_invocation(self): self.spy.foo() def test_called(self): self.spy.foo() assert_that(self.spy.foo, called()) def test_not_called(self): self.spy.foo() assert_that(self.spy.bar, is_not(called())) def test_called_2_times(self): self.spy.foo() self.spy.foo() assert_that(self.spy.foo, called().times(2)) assert_that(self.spy.foo, is_not(called().times(1))) assert_that(self.spy.foo, is_not(called().times(3))) def test_called_without_args(self): self.spy.foo() assert_that(self.spy.foo, called().with_args()) def test_called_with_None(self): self.spy.foo(None) assert_that(self.spy.foo, called().with_args(None)) assert_that(self.spy.foo, is_not(called().with_args())) def test_not_called_without_args(self): self.spy.foo(1) assert_that(self.spy.foo, is_not(called().with_args())) def test_called_with_specified_args(self): self.spy.foo(1) assert_that(self.spy.foo, called().with_args(1)) def test_not_called_with_specified_args(self): self.spy.foo() self.spy.foo(2) assert_that(self.spy.foo, is_not(called().with_args(1))) def test_mixed_args(self): self.spy.send_mail('hi') self.spy.send_mail('foo@bar.net') assert_that(self.spy.send_mail, called()) assert_that(self.spy.send_mail, called().times(2)) assert_that(self.spy.send_mail, called().with_args('foo@bar.net')) def test_called_with_several_types_and_kargs(self): self.spy.foo(3.0, [1, 2], 'hi', color='red', width=10) assert_that(self.spy.foo, called().with_args( 3.0, [1, 2], 'hi', color='red', width=10)) assert_that(self.spy.foo, called().with_args( 3.0, [1, 2], 'hi', width=10, color='red')) assert_that(self.spy.foo, is_not(called().with_args( [1, 2], 'hi', width=10, color='red'))) assert_that(self.spy.foo, is_not(called().with_args( [1, 2], 3.0, 'hi', width=10, color='red'))) def test_called_with_args_and_times(self): self.spy.foo(1) self.spy.foo(1) self.spy.foo(2) assert_that(self.spy.foo, called().with_args(1).times(2)) assert_that(self.spy.foo, called().with_args(2)) assert_that(self.spy.foo, called().times(3)) # def test_called_anything_and_value(self): # spy = Spy(Collaborator) # spy.two_args_method(10, 20) # assert_that(spy.two_args_method, called().with_args(anything(), 20)) # # def test_called_name_arg_value(self): # spy = Spy(Collaborator) # spy.two_args_method(10, 20) # assert_that(spy.two_args_method, called().with_args(arg2=20)) # # def test_called_karg(self): # spy = Spy(Collaborator) # spy.mixed_method(2, True) # assert_that(spy.mixed_method, called().with_args(key_param=True)) class Spy_calls_tests(TestCase): def test_list_recorded_calls(self): class Collaborator: def method(self, *args, **kargs): pass with Spy(Collaborator) as spy: spy.method(ANY_ARG).returns(100) spy.method(1, 2, 3) spy.method(key=2, val=5) assert_that(spy.method.calls[0].args, is_((1, 2, 3))) assert_that(spy.method.calls[1].kargs, is_(dict(key=2, val=5))) assert_that(spy.method.calls[1].retval, is_(100)) def test_called_with_an_object(self): class Module: def getName(self): return "Module" class Visitor: def visitModule(self, m): pass class Parser: def __init__(self, visitor): self.visitor = visitor def accept(self, visitor): self.visitor.visitModule(Module()) visitor = Spy(Visitor) parser = Parser(visitor) parser.accept(visitor) assert_that(visitor.visitModule.calls[0].args[0].getName(), is_("Module")) class SpyTests(TestCase): def setUp(self): self.spy = Spy(Collaborator) def test_from_instance(self): spy = Spy(Collaborator()) spy.hello() assert_that(spy.hello, called()) def test_call_unexisting_method(self): try: self.spy.wrong() self.fail('AttributeError should be raised') except AttributeError as e: expected = "'Collaborator' object has no attribute 'wrong'" assert_that(str(e), contains_string(expected)) def test_check_unexisting_method(self): try: assert_that(self.spy.wrong, called()) self.fail('AttributeError should be raised') except AttributeError as e: expected = "'Collaborator' object has no attribute 'wrong'" assert_that(str(e), contains_string(expected)) def test_create_from_oldstyle_class(self): Spy(Collaborator) def test_create_from_newstyle_class(self): Spy(ObjCollaborator) def test_wrong_call_args(self): self.spy.hello() with self.assertRaises(TypeError): assert_that(self.spy.hello, called().with_args('some')) class BuiltinSpyTests(TestCase): def test_builtin_method(self): spy = Spy(list) spy.append(10) assert_that(spy.append, called().with_args(10)) def test_builtin_method_wrong_num_args(self): spy = Spy(list) try: spy.append(10, 20) self.fail('AttributeError should be raised') except TypeError as e: expected = "list.append() takes exactly 1 argument (2 given)" assert_that(str(e), contains_string(expected)) def test_wrong_builtin_method(self): spy = Spy(list) try: spy.wrong(10) self.fail('AttributeError should be raised') except AttributeError as e: expected = "'list' object has no attribute 'wrong'" assert_that(str(e), contains_string(expected)) class ProxySpyTests(TestCase): def test_must_give_argument(self): self.failUnlessRaises(TypeError, ProxySpy) def test_given_argument_can_not_be_oldstyle_class(self): self.failUnlessRaises(TypeError, ProxySpy, Collaborator) def test_given_argument_can_not_be_newstyle_class(self): self.failUnlessRaises(TypeError, ProxySpy, ObjCollaborator) def test_propagate_stubbed_calls_to_collaborator(self): class Foo: def __init__(self): self.value = 0 def store_add(self, value): self.value = value return -value foo = Foo() with ProxySpy(foo) as spy: spy.store_add(3).returns(1000) assert_that(spy.store_add(2), is_(-2)) assert_that(foo.value, is_(2)) assert_that(spy.store_add(3), is_(1000)) assert_that(foo.value, is_(3)) class MockTests(TestCase): def test_with_args(self): mock = Mock() with mock: mock.hello(1) mock.bye(2) mock.bye(3) mock.hello(1) mock.bye(2) mock.bye(3) assert_that(mock, verify()) def test_with_several_args(self): mock = Mock() with mock: mock.hello(1, 1) mock.bye(2, 2) mock.bye(3, 3) mock.hello(1, 1) mock.bye(2, 2) mock.bye(3, 3) assert_that(mock, verify()) def test_with_kargs(self): mock = Mock() with mock: mock.hello(1, name=1) mock.bye(2, value=2) mock.bye(3, value=3) mock.hello(1, name=1) mock.bye(2, value=2) mock.bye(3, value=3) assert_that(mock, verify()) def test_from_instance(self): mock = Mock(Collaborator()) with mock: mock.hello() mock.hello() assert_that(mock, verify()) class MockOrderTests(TestCase): def setUp(self): self.mock = Mock() def test_order_matters__ok(self): with self.mock: self.mock.foo() self.mock.bar() self.mock.foo() self.mock.bar() assert_that(self.mock, verify()) def test_order_matters__fail(self): with self.mock: self.mock.foo() self.mock.bar() self.mock.bar() self.mock.foo() self.failUnlessRaises( AssertionError, assert_that, self.mock, verify()) def test_method_name_order_does_not_matter_with_any_order(self): with self.mock: self.mock.foo() self.mock.bar() self.mock.bar() self.mock.foo() assert_that(self.mock, any_order_verify()) def test_args_order_does_not_matter_with_any_order(self): with self.mock: self.mock.foo(2) self.mock.foo(1) self.mock.foo(1) self.mock.foo(2) assert_that(self.mock, any_order_verify()) def test_kwargs_order_does_not_matter_with_any_order(self): with self.mock: self.mock.foo(1, key='a') self.mock.foo(1, key='b') self.mock.foo(1, key='b') self.mock.foo(1, key='a') assert_that(self.mock, any_order_verify()) def test_several_args_with_any_order(self): with self.mock: self.mock.foo(2, 2) self.mock.bar(1) self.mock.foo(1, 1) self.mock.bar(2) self.mock.foo(1, 1) self.mock.bar(1) self.mock.foo(2, 2) self.mock.bar(2) assert_that(self.mock, any_order_verify()) def test_several_args_with_matcher_any_order(self): with self.mock: self.mock.foo(2, anything()) self.mock.bar(1) self.mock.foo(1, anything()) self.mock.bar(2) self.mock.foo(1, 1) self.mock.bar(1) self.mock.foo(2, 2) self.mock.bar(2) assert_that(self.mock, any_order_verify()) class DisplayResultsTests(TestCase): def setUp(self): with Spy() as self.empty_spy: self.empty_spy.foo(ANY_ARG).returns(True) with Spy(Collaborator) as self.spy: self.spy.method_one(ANY_ARG).returns(2) def test_empty_spy_stub_method(self): assert_that(self.empty_spy.foo._show_history(), reason="method 'Spy.foo' never invoked") def test_spy_stub_method(self): assert_that(self.spy.method_one._show_history(), reason="method 'Collaborator.method_one' never invoked") def test_empty_spy_stub_method_invoked(self): self.empty_spy.foo() expected = [ "method 'Spy.foo' was invoked", "foo()"] assert_that(self.empty_spy.foo._show_history(), string_contains_in_order(*expected)) def test_spy_stub_method_invoked(self): self.spy.method_one(1) expected = [ "method 'Collaborator.method_one' was invoked", 'method_one(1)'] assert_that(self.spy.method_one._show_history(), string_contains_in_order(*expected)) def test_empty_spy_non_stubbed_method_invoked(self): self.empty_spy.bar(1, 3.0, "text", key1="text", key2=[1, 2]) expected = [ "method 'Spy.bar' was invoked", "bar(1, 3.0, 'text', key1='text', key2=[1, 2])"] assert_that(self.empty_spy.bar._show_history(), string_contains_in_order(*expected)) def test_spy_several_invoked_same_method(self): self.spy.mixed_method(5, True) self.spy.mixed_method(8, False) expected = "method 'Collaborator.mixed_method' was invoked" assert_that(self.spy.mixed_method._show_history(), contains_string(expected)) class FrameworApiTest(TestCase): def test_called_requires_spy(self): stub = Stub() try: assert_that(stub.method, called()) self.fail('exception should be raised') except WrongApiUsage as e: assert_that(str(e), contains_string('takes a spy method (got')) class ApiMismatchTest(TestCase): def setUp(self): self.spy = Spy(Collaborator) def test_default_params(self): self.spy.mixed_method(1) def test_give_karg(self): self.spy.mixed_method(1, key_param=True) def test_give_karg_without_key(self): self.spy.mixed_method(1, True) def test_fail_missing_method(self): try: self.spy.missing() self.fail("TypeError should be raised") except AttributeError as e: expected = "'Collaborator' object has no attribute 'missing'" assert_that(str(e), contains_string(expected)) def test_fail_wrong_args(self): try: self.spy.hello("wrong") self.fail("TypeError should be raised") except TypeError as e: expected = "Collaborator.hello() takes exactly 1 argument (2 given)" if sys.version_info >= (3,): expected = "Collaborator.hello() takes exactly 1 positional argument (2 given)" assert_that(str(e), contains_string(expected)) def test_fail_wrong_kargs(self): try: self.spy.kwarg_method(wrong_key=1) self.fail("TypeError should be raised") except TypeError as e: expected = "Collaborator.kwarg_method() got an unexpected keyword argument 'wrong_key'" assert_that(str(e), contains_string(expected)) class ANY_ARG_StubTests(TestCase): def setUp(self): self.stub = Stub() def test_any_args(self): with self.stub: self.stub.foo(ANY_ARG).returns(True) assert_that(self.stub.foo(), is_(True)) assert_that(self.stub.foo(1), is_(True)) assert_that(self.stub.foo(key1='a'), is_(True)) assert_that(self.stub.foo(1, 2, 3, key1='a', key2='b'), is_(True)) def test_fixed_args_and_any_args(self): with self.stub: self.stub.foo(1, ANY_ARG).returns(True) assert_that(self.stub.foo(1, 2, 3), is_(True)) assert_that(self.stub.foo(1, key1='a'), is_(True)) def test_ANY_ARG_must_be_last_positional_argument(self): with self.assertRaises(WrongApiUsage): with self.stub: self.stub.method(1, ANY_ARG, 3).returns(True) class ANY_ARG_SpyTests(TestCase): def setUp(self): self.spy = Spy() def test_no_args(self): self.spy.foo() assert_that(self.spy.foo, called().with_args(ANY_ARG)) assert_that(self.spy.foo, never(called().with_args(anything()))) def test_one_arg(self): self.spy.foo(1) assert_that(self.spy.foo, called()) assert_that(self.spy.foo, called().with_args(ANY_ARG)) assert_that(self.spy.foo, called().with_args(anything())) def test_one_karg(self): self.spy.foo(key='val') assert_that(self.spy.foo, called().with_args(ANY_ARG)) def test_three_args(self): self.spy.foo(1, 2, 3) assert_that(self.spy.foo, called().with_args(1, ANY_ARG)) assert_that(self.spy.foo, never(called().with_args(2, ANY_ARG))) def test_args_and_kargs(self): self.spy.foo(1, 2, 3, key1='a', key2='b') assert_that(self.spy.foo, called().with_args(1, ANY_ARG)) assert_that(self.spy.foo, never(called().with_args(2, ANY_ARG))) def test__called__and__called_with_args__ANY_ARGS_is_the_same(self): self.spy.foo() self.spy.foo(3) self.spy.foo('hi') self.spy.foo(None) assert_that(self.spy.foo, called().times(4)) assert_that(self.spy.foo, called().with_args(ANY_ARG).times(4)) # issue 9 def test_ANY_ARG_forbbiden_as_keyword_value(self): person = Spy() person.set_info(name="John", surname="Doe") assert_that(person.set_info, called().with_args(name=anything(), surname="Doe")) with self.assertRaises(WrongApiUsage): assert_that(person.set_info, called().with_args(name=ANY_ARG, surname="Doe")) def test_ANY_ARG_must_be_last_positional_argument(self): self.spy.method(1, 2, 3) with self.assertRaises(WrongApiUsage): assert_that(self.spy.method, called().with_args(1, ANY_ARG, 3)) def test_ANY_ARG_must_be_last_positional_argument_with_xarg(self): self.spy.method(1, 2, 3, name='Bob') with self.assertRaises(WrongApiUsage): assert_that(self.spy.method, called().with_args(1, ANY_ARG, name='Bob')) def test_ANY_ARG_must_be_last_positional_argument__restricted_spy(self): spy = Spy(Collaborator) with self.assertRaises(WrongApiUsage): assert_that(spy.two_args_method, called().with_args(ANY_ARG, 2)) with self.assertRaises(WrongApiUsage): assert_that(spy.three_args_method, called().with_args(1, ANY_ARG, 3)) class MatcherTests(TestCase): def setUp(self): self.spy = Spy() def test_check_has_length(self): self.spy.foo("abcd") assert_that(self.spy.foo, called().with_args(has_length(4))) assert_that(self.spy.foo, called().with_args(has_length(greater_than(3)))) assert_that(self.spy.foo, called().with_args(has_length(less_than(5)))) assert_that(self.spy.foo, is_not(called().with_args(has_length(greater_than(5))))) def test_stub_has_length(self): with self.spy: self.spy.foo(has_length(less_than(4))).returns('<4') self.spy.foo(has_length(4)).returns('four') self.spy.foo( has_length( all_of(greater_than(4), less_than(8)))).returns('48') assert_that(self.spy.foo((1, 2)), is_('<4')) assert_that(self.spy.foo('abcd'), is_('four')) assert_that(self.spy.foo('abcde'), is_('48')) def test_stub_contains_string(self): with Stub() as stub: stub.method(contains_string("some")).returns(1000) assert_that(stub.method("awesome"), is_(1000)) # doc def test_times_arg_may_be_matcher(self): self.spy.foo() self.spy.foo(1) self.spy.foo(1) self.spy.foo(2) assert_that(self.spy.never, is_not(called())) # = 0 times assert_that(self.spy.foo, called()) # > 0 assert_that(self.spy.foo, called().times(greater_than(0))) # > 0 (same) assert_that(self.spy.foo, called().times(4)) # = 4 assert_that(self.spy.foo, called().times(greater_than(2))) # > 2 assert_that(self.spy.foo, called().times(less_than(6))) # < 6 assert_that(self.spy.foo, is_not(called().with_args(5))) # = 0 times assert_that(self.spy.foo, called().with_args().times(1)) # = 1 assert_that(self.spy.foo, called().with_args(anything())) # > 0 assert_that(self.spy.foo, called().with_args(ANY_ARG).times(4)) # = 4 assert_that(self.spy.foo, called().with_args(1).times(2)) # = 2 assert_that(self.spy.foo, called().with_args(1).times(greater_than(1))) # > 1 assert_that(self.spy.foo, called().with_args(1).times(less_than(5))) # < 5 # doc def test_called_args(self): self.spy.m1() self.spy.m2(None) self.spy.m3(2) self.spy.m4("hi", 3.0) self.spy.m5([1, 2]) self.spy.m6(name="john doe") assert_that(self.spy.m1, called()) assert_that(self.spy.m2, called()) assert_that(self.spy.m1, called().with_args()) assert_that(self.spy.m2, called().with_args(None)) assert_that(self.spy.m3, called().with_args(2)) assert_that(self.spy.m4, called().with_args("hi", 3.0)) assert_that(self.spy.m5, called().with_args([1, 2])) assert_that(self.spy.m6, called().with_args(name="john doe")) assert_that(self.spy.m3, called().with_args(less_than(3))) assert_that(self.spy.m3, called().with_args(greater_than(1))) assert_that(self.spy.m6, called().with_args(name=contains_string("doe"))) # new on 1.7 def test_assert_that_requires_a_matcher(self): self.assertRaises(MatcherRequiredError, assert_that, self.spy.m1, True) class StubObserverTests(TestCase): def setUp(self): self.stub = Stub() def test_observer_called(self): observer = Observer() self.stub.foo.attach(observer.update) self.stub.foo(2) assert_that(observer.state, is_(2)) def test_observer_called_tested_using_a_doublex_spy(self): observer = Spy() self.stub.foo.attach(observer.update) self.stub.foo(2) assert_that(observer.update, called().with_args(2)) class StubDelegateTests(TestCase): def setUp(self): self.stub = Stub() def assert_012(self, method): for x in range(3): assert_that(method(), is_(x)) def test_delegate_to_other_method(self): with self.stub: self.stub.foo().delegates(Collaborator().hello) assert_that(self.stub.foo(), is_("hello")) def test_delegate_to_list(self): with self.stub: self.stub.foo().delegates(range(3)) self.assert_012(self.stub.foo) def test_delegate_to_generator(self): with self.stub: self.stub.foo().delegates(x for x in range(3)) self.assert_012(self.stub.foo) def test_delegate_to_count(self): with self.stub: self.stub.foo().delegates(itertools.count()) self.assert_012(self.stub.foo) def test_delegate_to_lambda(self): with self.stub: self.stub.foo().delegates(lambda: 2) assert_that(self.stub.foo(), is_(2)) def test_delegate_to_another_stub(self): stub2 = Stub() with stub2: stub2.bar().returns("hi!") with self.stub: self.stub.foo().delegates(stub2.bar) assert_that(self.stub.foo(), is_("hi!")) def test_not_delegable_object(self): try: with self.stub: self.stub.foo().delegates(None) self.fail("Exception should be raised") except WrongApiUsage as e: expected = "delegates() must be called with callable or iterable instance (got 'None' instead)" assert_that(str(e), contains_string(expected)) class MockDelegateTest(TestCase): def setUp(self): self.mock = Mock() def assert_012(self, method): for x in range(3): assert_that(method(), is_(x)) def test_delegate_to_list_is_only_an_expectation(self): with self.mock: self.mock.foo().delegates(range(3)) self.mock.foo() assert_that(self.mock, verify()) class MimicTests(TestCase): class A(object): def method_a(self, n): return n + 1 class B(A): def method_b(self): return "hi" def test_normal_spy_does_not_inherit_collaborator_superclasses(self): spy = Spy(self.B) assert_that(not isinstance(spy, self.B)) def test_mimic_spy_DOES_inherit_collaborator_superclasses(self): spy = Mimic(Spy, self.B) for cls in [self.B, self.A, Spy, Stub, object]: assert_that(spy, instance_of(cls)) def test_mimic_stub_works(self): stub = Mimic(Stub, self.B) with stub: stub.method_a(2).returns(3) assert_that(stub.method_a(2), is_(3)) def test_mimic_stub_from_instance(self): stub = Mimic(Stub, self.B()) with stub: stub.method_a(2).returns(3) assert_that(stub.method_a(2), is_(3)) def test_mimic_spy_works(self): spy = Mimic(Spy, self.B) with spy: spy.method_a(5).returns(True) assert_that(spy.method_a(5), is_(True)) assert_that(spy.method_a, called()) assert_that(spy.method_a, called().with_args(5)) def test_mimic_proxy_spy_works(self): spy = Mimic(ProxySpy, self.B()) assert_that(spy.method_a(5), is_(6)) assert_that(spy.method_a, called()) assert_that(spy.method_a, called().with_args(5)) def test_mimic_mock_works(self): mock = Mimic(Mock, self.B) with mock: mock.method_a(2) mock.method_a(2) assert_that(mock, verify()) class PropertyTests(TestCase): def test_stub_notset_property_is_None(self): stub = Stub(ObjCollaborator) assert_that(stub.prop, is_(None)) def test_stub_property(self): stub = Stub(ObjCollaborator) with stub: stub.prop = 2 assert_that(stub.prop, is_(2)) def test_spy_get_property_using_class(self): spy = Spy(ObjCollaborator) skip = spy.prop assert_that(spy, property_got('prop')) def test_spy_get_property_using_instance(self): spy = Spy(ObjCollaborator()) skip = spy.prop assert_that(spy, property_got('prop')) def test_spy_not_get_property(self): spy = Spy(ObjCollaborator) assert_that(spy, never(property_got('prop'))) def test_spy_get_property_fail(self): spy = Spy(ObjCollaborator) self.failUnlessRaises( AssertionError, assert_that, spy, property_got('prop')) def test_spy_set_property_using_class(self): spy = Spy(ObjCollaborator) spy.prop = 2 assert_that(spy, property_set('prop')) def test_spy_set_property_using_instance(self): spy = Spy(ObjCollaborator()) spy.prop = 2 assert_that(spy, property_set('prop')) def test_spy_not_set_property(self): spy = Spy(ObjCollaborator) assert_that(spy, never(property_set('prop'))) def test_spy_set_property_fail(self): spy = Spy(ObjCollaborator) self.failUnlessRaises( AssertionError, assert_that, spy, property_set('prop')) def test_spy_set_property_to(self): spy = Spy(ObjCollaborator) spy.prop = 2 assert_that(spy, property_set('prop').to(2)) assert_that(spy, never(property_set('prop').to(5))) def test_spy_set_property_times(self): spy = Spy(ObjCollaborator) spy.prop = 2 spy.prop = 3 assert_that(spy, property_set('prop').to(2)) assert_that(spy, property_set('prop').to(3)) assert_that(spy, property_set('prop').times(2)) def test_spy_set_property_to_times(self): spy = Spy(ObjCollaborator) spy.prop = 3 spy.prop = 3 assert_that(spy, property_set('prop').to(3).times(2)) def test_properties_are_NOT_shared_among_doubles(self): stub1 = Stub(ObjCollaborator) stub2 = Stub(ObjCollaborator) stub1.prop = 1000 assert_that(stub2.prop, is_not(1000)) assert_that(stub1.__class__ is not stub2.__class__) def test_spy_get_readonly_property_with_deco(self): spy = Spy(ObjCollaborator) skip = spy.prop_deco_readonly assert_that(spy, property_got('prop_deco_readonly')) def test_spy_SET_readonly_property_with_deco(self): spy = Spy(ObjCollaborator) try: spy.prop_deco_readonly = 'wrong' self.fail('should raise exception') except AttributeError: pass def test_hamcrest_matchers(self): spy = Spy(ObjCollaborator) spy.prop = 2 spy.prop = 3 assert_that(spy, property_set('prop').to(greater_than(1)). times(less_than(3))) def test_proxy_spy_get_actual_property(self): collaborator = ObjCollaborator() sut = ProxySpy(collaborator) assert_that(sut.prop, is_(1)) def test_proxy_spy_get_stubbed_property(self): collaborator = ObjCollaborator() with ProxySpy(collaborator) as sut: sut.prop = 2 assert_that(sut.prop, is_(2)) def test_proxy_spy_set_property(self): collaborator = ObjCollaborator() sut = ProxySpy(collaborator) sut.prop = 20 assert_that(sut.prop, is_(20)) assert_that(collaborator.prop, is_(20)) class AsyncTests(TestCase): class SUT(object): def __init__(self, collaborator): self.collaborator = collaborator def send_data(self, data=0): thread.start_new_thread(self.collaborator.write, (data,)) def test_spy_call_without_async_feature(self): # given barrier = threading.Event() with Spy() as spy: spy.write.attach(lambda *args: barrier.set) sut = AsyncTests.SUT(spy) # when sut.send_data() barrier.wait(1) # test probably FAILS without this # then assert_that(spy.write, called()) def test_spy_call_with_async_feature(self): # given spy = Spy() sut = AsyncTests.SUT(spy) # when sut.send_data() # then assert_that(spy.write, called().async(timeout=1)) def test_spy_async_support_1_call_only(self): # given spy = Spy() sut = AsyncTests.SUT(spy) # when sut.send_data(3) sut.send_data(3) # then with self.assertRaises(WrongApiUsage): assert_that(spy.write, called().async(timeout=1).with_args(3).times(2)) def test_spy_async_stubbed(self): # given with Spy() as spy: spy.write(ANY_ARG).returns(100) sut = AsyncTests.SUT(spy) # when sut.send_data(3) # then assert_that(spy.write, called().async(timeout=1)) # FIXME: new on 1.7 class with_some_args_matcher_tests(TestCase): def test_one_arg(self): spy = Spy(Collaborator) spy.mixed_method(5) assert_that(spy.mixed_method, called().with_args(5)) assert_that(spy.mixed_method, called().with_args(arg1=5)) def test_two_arg(self): spy = Spy(Collaborator) spy.two_args_method(5, 10) assert_that(spy.two_args_method, called().with_args(5, 10)) assert_that(spy.two_args_method, called().with_args(arg1=5, arg2=10)) assert_that(spy.two_args_method, called().with_some_args(arg1=5)) assert_that(spy.two_args_method, called().with_some_args(arg2=10)) assert_that(spy.two_args_method, called().with_some_args()) def test_free_spy(self): spy = Spy() spy.foo(1, 3) with self.assertRaises(WrongApiUsage): assert_that(spy.foo, called().with_some_args()) # FIXME: new on 1.7 class Stub_default_behavior_tests(TestCase): def test_set_return_globally(self): StubClone = Stub._clone_class() set_default_behavior(StubClone, method_returning(20)) stub = StubClone() assert_that(stub.unknown(), is_(20)) def test_set_exception_globally(self): StubClone = Stub._clone_class() set_default_behavior(StubClone, method_raising(SomeException)) stub = StubClone() with self.assertRaises(SomeException): stub.unknown() def test_set_return_by_instance(self): stub = Stub() set_default_behavior(stub, method_returning(20)) assert_that(stub.unknown(), is_(20)) def test_set_exception_by_instance(self): stub = Stub() set_default_behavior(stub, method_raising(SomeException)) with self.assertRaises(SomeException): stub.unknown() def test_restricted_stub(self): stub = Stub(Collaborator) set_default_behavior(stub, method_returning(30)) with stub: stub.hello().returns(1000) assert_that(stub.something(), is_(30)) assert_that(stub.hello(), is_(1000)) # FIXME: new on 1.7 class Spy_default_behavior_tests(TestCase): def test_set_return_globally(self): SpyClone = Spy._clone_class() set_default_behavior(SpyClone, method_returning(20)) spy = SpyClone() assert_that(spy.unknown(7), is_(20)) assert_that(spy.unknown, called().with_args(7)) assert_that(spy.unknown, never(called().with_args(9))) def test_set_return_by_instance(self): spy = Spy() set_default_behavior(spy, method_returning(20)) assert_that(spy.unknown(7), is_(20)) assert_that(spy.unknown, called().with_args(7)) # FIXME: new on 1.7 class ProxySpy_default_behavior_tests(TestCase): def test_this_change_proxyspy_default_behavior(self): spy = ProxySpy(Collaborator()) assert_that(spy.hello(), is_("hello")) set_default_behavior(spy, method_returning(40)) assert_that(spy.hello(), is_(40)) # FIXME: new on tip class orphan_methods_tests(TestCase): def setUp(self): self.obj = Collaborator() def test_stub_method(self): with Stub() as stub: stub.method(1).returns(100) stub.method(2).returns(200) self.obj.foo = stub.method assert_that(self.obj.foo(0), is_(None)) assert_that(self.obj.foo(1), is_(100)) assert_that(self.obj.foo(2), is_(200)) def test_spy_method(self): with Spy() as spy: spy.method(1).returns(100) spy.method(2).returns(200) spy.method(3).raises(SomeException) self.obj.foo = spy.method assert_that(self.obj.foo(0), is_(None)) assert_that(self.obj.foo(1), is_(100)) assert_that(self.obj.foo(2), is_(200)) with self.assertRaises(SomeException): self.obj.foo(3) assert_that(self.obj.foo, called().times(4)) assert_that(spy.method, called().times(4)) # def test_spy_method__brief_method(self): # with method() as self.obj.foo: # self.obj.foo().returns(100) # self.obj.foo(2).returns(200) # # assert_that(self.obj.foo(), is_(100)) # assert_that(self.obj.foo(2), is_(200)) # assert_that(self.obj.foo(3), is_(None)) # # assert_that(self.obj.foo, called().times(3)) # assert_that(spy.method, called().times(3)) # FIXME: new on 1.7.2 class VarArgsTest(TestCase): def test_stub_args(self): stub = Stub(Collaborator) with stub: stub.varargs(1).returns(10) stub.varargs(1, 2).returns(200) stub.varargs(1, 3, ANY_ARG).returns(300) stub.varargs(2, anything()).returns(400) assert_that(stub.varargs(42), is_(None)) assert_that(stub.varargs(1), is_(10)) assert_that(stub.varargs(1, 2), is_(200)) assert_that(stub.varargs(1, 2, 7), is_(None)) assert_that(stub.varargs(1, 3), is_(300)) assert_that(stub.varargs(1, 3, 7), is_(300)) assert_that(stub.varargs(1, 5), is_(None)) assert_that(stub.varargs(2), is_(None)) assert_that(stub.varargs(2, 3), is_(400)) assert_that(stub.varargs(2, 3, 4), is_(None)) def test_spy_args(self): spy = Spy(Collaborator) spy.varargs(1, 2, 3) assert_that(spy.varargs, called()) assert_that(spy.varargs, called().with_args(1, 2, 3)) assert_that(spy.varargs, called().with_args(1, ANY_ARG)) def test_spy_kargs(self): spy = Spy(Collaborator) spy.varargs(one=1, two=2) assert_that(spy.varargs, called()) assert_that(spy.varargs, called().with_args(one=1, two=2)) assert_that(spy.varargs, called().with_args(one=1, two=anything())) def test_with_some_args_is_not_applicable(self): spy = Spy(Collaborator) spy.varargs(one=1, two=2) try: assert_that(spy.varargs, called().with_some_args(one=1)) self.fail('exception should be raised') except WrongApiUsage as e: assert_that(str(e), contains_string('with_some_args() can not be applied to method Collaborator.varargs(self, *args, **kargs)')) # FIXME: new on 1.7.2 class TracerTests(TestCase): def setUp(self): self.out = io.BytesIO() self.tracer = Tracer(self.out.write) def test_trace_single_method(self): with Stub() as stub: stub.foo(ANY_ARG).returns(1) self.tracer.trace(stub.foo) stub.foo(1, two=2) assert_that(self.out.getvalue(), is_("Stub.foo(1, two=2)")) def test_trace_single_non_stubbed_method(self): stub = Stub() self.tracer.trace(stub.non) stub.non(1, "two") assert_that(self.out.getvalue(), is_("Stub.non(1, 'two')")) def test_trace_all_double_INSTANCE_methods(self): stub = Stub() self.tracer.trace(stub) stub.bar(2, "three") assert_that(self.out.getvalue(), is_("Stub.bar(2, 'three')")) def test_trace_all_double_CLASS_methods(self): self.tracer.trace(Stub) stub = Stub() stub.fuzz(3, "four") assert_that(self.out.getvalue(), is_("Stub.fuzz(3, 'four')")) def test_trace_get_property(self): stub = Stub(ObjCollaborator) self.tracer.trace(stub) stub.prop assert_that(self.out.getvalue(), is_("ObjCollaborator.prop gotten")) def test_trace_set_property(self): stub = Stub(ObjCollaborator) self.tracer.trace(stub) stub.prop = 2 assert_that(self.out.getvalue(), is_("ObjCollaborator.prop set to 2")) class SomeException(Exception): pass class Observer(object): def __init__(self): self.state = None def update(self, *args, **kargs): self.state = args[0] class ObjCollaborator(object): def __init__(self): self._propvalue = 1 def no_args(self): return 1 def prop_getter(self): return self._propvalue def prop_setter(self, value): self._propvalue = value prop = property(prop_getter, prop_setter) @property def prop_deco_readonly(self): return 2 class Collaborator: """ The original object we double in tests """ class_attr = "OK" def __init__(self): self.instance_attr = 300 def hello(self): return "hello" def something(self): return "ok" def one_arg_method(self, arg1): return arg1 def two_args_method(self, arg1, arg2): return arg1 + arg2 def three_args_method(self, arg1, arg2, arg3): return arg1 + arg2 + arg3 def kwarg_method(self, key_param=False): return key_param def mixed_method(self, arg1, key_param=False): return key_param + arg1 def void_method(self): pass def method_one(self, arg1): return 1 def varargs(self, *args, **kargs): return len(args) alias_method = one_arg_method doublex-1.7.2/doublex/test/README0000644000175000017500000000007712236777524015563 0ustar piotrpiotrTo run all tests just run "nosetests" in the parent directory. doublex-1.7.2/doublex/test/__init__.py0000644000175000017500000000000012236777524016776 0ustar piotrpiotrdoublex-1.7.2/doublex/tracer.py0000644000175000017500000000276412236777524015563 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- from .doubles import Stub from .internal import Method, WrongApiUsage class MethodTracer(object): def __init__(self, logger, method): self.logger = logger self.method = method def __call__(self, *args, **kargs): self.logger(str(self.method._create_invocation(args, kargs))) class PropertyTracer(object): def __init__(self, logger, prop): self.logger = logger self.prop = prop def __call__(self, *args, **kargs): propname = "%s.%s" % (self.prop.double._classname(), self.prop.key) if args: self.logger("%s set to %s" % (propname, args[0])) else: self.logger("%s gotten" % (propname)) class Tracer(object): def __init__(self, logger): self.logger = logger def trace(self, target): if isinstance(target, Method): self.trace_method(target) elif isinstance(target, Stub) or issubclass(target, Stub): self.trace_double(target) else: raise WrongApiUsage('Can not trace %s' % target) def trace_method(self, method): method.attach(MethodTracer(self.logger, method)) def trace_double(self, double): def attach_new_method(attr): if isinstance(attr, Method): attr.attach(MethodTracer(self.logger, attr)) else: attr.attach(PropertyTracer(self.logger, attr)) double._new_attr_hooks.append(attach_new_method) doublex-1.7.2/doublex/safeunicode.py0000644000175000017500000000131712236777524016561 0ustar piotrpiotr# -*- coding: utf-8 -*- import sys def __if_number_get_string(number): converted_str = number if isinstance(number, (int, float)): converted_str = str(number) return converted_str def get_unicode(strOrUnicode, encoding='utf-8'): strOrUnicode = __if_number_get_string(strOrUnicode) if isinstance(strOrUnicode, unicode): return strOrUnicode return unicode(strOrUnicode, encoding, errors='ignore') def get_string(strOrUnicode, encoding='utf-8'): strOrUnicode = __if_number_get_string(strOrUnicode) if sys.version_info >= (3,): return strOrUnicode if isinstance(strOrUnicode, unicode): return strOrUnicode.encode(encoding) return strOrUnicode doublex-1.7.2/doublex/proxy.py0000644000175000017500000001427212236777524015461 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012,2013 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import inspect try: from inspect import getcallargs except ImportError: from .py27_backports import getcallargs from .internal import ANY_ARG def create_proxy(collaborator): if collaborator is None: return DummyProxy() return CollaboratorProxy(collaborator) class Proxy(object): def assure_signature_matches(self, invocation): pass def collaborator_classname(self): return None def get_signature(self, method_name): if self.is_property(method_name): return PropertySignature(self, method_name) if not self.is_method_or_func(method_name): return BuiltinSignature(self, method_name) return MethodSignature(self, method_name) def is_property(self, attr_name): attr = getattr(self.collaborator_class, attr_name) return isinstance(attr, property) def is_method_or_func(self, method_name): func = getattr(self.collaborator, method_name) if inspect.ismethod(func): func = func.im_func return inspect.isfunction(func) class DummyProxy(Proxy): def get_attr_typename(self, key): return 'instancemethod' def same_method(self, name1, name2): return name1 == name2 def get_signature(self, method_name): return DummySignature() def get_class(something): if inspect.isclass(something): return something else: return something.__class__ class CollaboratorProxy(Proxy): '''Represent the collaborator object''' def __init__(self, collaborator): self.collaborator = collaborator self.collaborator_class = get_class(collaborator) def isclass(self): return inspect.isclass(self.collaborator) def get_class_attr(self, key): return getattr(self.collaborator_class, key) def get_attr(self, key): return getattr(self.collaborator, key) def collaborator_classname(self): return self.collaborator_class.__name__ def assure_signature_matches(self, invocation): signature = self.get_signature(invocation._name) signature.assure_matches(invocation._context) def get_attr_typename(self, key): def raise_no_attribute(): reason = "'%s' object has no attribute '%s'" % \ (self.collaborator_classname(), key) raise AttributeError(reason) try: attr = getattr(self.collaborator_class, key) return type(attr).__name__ except AttributeError: if self.collaborator is self.collaborator_class: raise_no_attribute() try: attr = getattr(self.collaborator, key) return type(attr).__name__ except AttributeError: raise_no_attribute() def same_method(self, name1, name2): return getattr(self.collaborator, name1) == \ getattr(self.collaborator, name2) def perform_invocation(self, invocation): method = getattr(self.collaborator, invocation._name) return invocation._context.apply_on(method) class Signature(object): def __init__(self, proxy, name): self.proxy = proxy self.name = name self.method = getattr(proxy.collaborator, name) def get_arg_spec(self): pass def get_call_args(self, context): retval = context.kargs.copy() for n, i in enumerate(context.args): retval['_positional_%s' % n] = i return retval def __eq__(self, other): return (self.proxy, self.name, self.method) == \ (other.proxy, other.name, other.method) class DummySignature(Signature): def __init__(self): pass class BuiltinSignature(Signature): "builtin collaborator method signature" def assure_matches(self, context): doc = self.method.__doc__ if not ')' in doc: return rpar = doc.find(')') params = doc[:rpar] nkargs = params.count('=') nargs = params.count(',') + 1 - nkargs if len(context.args) != nargs: raise TypeError('%s.%s() takes exactly %s argument (%s given)' % ( self.proxy.collaborator_classname(), self.name, nargs, len(context.args))) class MethodSignature(Signature): "colaborator method signature" def __init__(self, proxy, name): super(MethodSignature, self).__init__(proxy, name) self.argspec = inspect.getargspec(self.method) def get_arg_spec(self): retval = inspect.getargspec(self.method) del retval.args[0] return retval def get_call_args(self, context): args = context.args # print self.name, args if self.proxy.isclass(): args = (None,) + args # self retval = getcallargs(self.method, *args, **context.kargs) del retval['self'] return retval def assure_matches(self, context): if ANY_ARG in context.args: return try: self.get_call_args(context) except TypeError as e: raise TypeError("%s.%s" % (self.proxy.collaborator_classname(), e)) def __repr__(self): return "%s.%s%s" % (self.proxy.collaborator_classname(), self.name, inspect.formatargspec(*self.argspec)) class PropertySignature(Signature): def __init__(self, proxy, name): pass def assure_matches(self, context): pass doublex-1.7.2/doublex/matchers.py0000644000175000017500000002040012236777524016074 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012,2013 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import time import hamcrest from hamcrest.core.matcher import Matcher from hamcrest.core.base_matcher import BaseMatcher from hamcrest import is_, instance_of from .internal import ( Method, InvocationContext, ANY_ARG, MockBase, SpyBase, PropertyGet, PropertySet, WrongApiUsage, Invocation) __all__ = ['called', 'never', 'verify', 'any_order_verify', 'property_got', 'property_set', 'assert_that', 'wait_that', 'is_', 'instance_of'] # just hamcrest aliases at_least = hamcrest.greater_than_or_equal_to at_most = hamcrest.less_than_or_equal_to any_time = hamcrest.greater_than(0) class MatcherRequiredError(Exception): pass def assert_that(actual, matcher=None, reason=''): if matcher and not isinstance(matcher, Matcher): raise MatcherRequiredError("%s should be a hamcrest Matcher" % str(matcher)) return hamcrest.assert_that(actual, matcher, reason) def wait_that(actual, matcher, reason='', delta=1, timeout=5): ''' Poll the given matcher each 'delta' seconds until 'matcher' matches 'actual' or 'timeout' is reached. ''' exc = None init = time.time() timeout_reached = False while 1: try: if time.time() - init > timeout: timeout_reached = True break assert_that(actual, matcher, reason) break except AssertionError as e: time.sleep(delta) exc = e if timeout_reached: msg = exc.args[0] + ' after {0} seconds'.format(timeout) exc.args = msg, raise exc class OperationMatcher(BaseMatcher): pass class MethodCalled(OperationMatcher): def __init__(self, context=None, times=any_time): self.context = context or InvocationContext(ANY_ARG) self._times = times self._async_timeout = None def _matches(self, method): self._assure_is_spied_method(method) self.method = method if not self._async_timeout: return method._was_called(self.context, self._times) if self._async_timeout: if self._times != any_time: raise WrongApiUsage("'times' and 'async' are exclusive") self.method._event.wait(self._async_timeout) return method._was_called(self.context, self._times) def _assure_is_spied_method(self, method): if not isinstance(method, Method) or not isinstance(method.double, SpyBase): raise WrongApiUsage("takes a spy method (got %s instead)" % method) def describe_to(self, description): description.append_text('these calls:\n') description.append_text(self.method._show(indent=10)) description.append_text(str(self.context)) if self._times != any_time: description.append_text(' -- times: %s' % self._times) def describe_mismatch(self, actual, description): description.append_text("calls that actually ocurred were:\n") description.append_text(self.method.double._recorded.show(indent=10)) def with_args(self, *args, **kargs): self.context.update_args(args, kargs) return self def with_some_args(self, **kargs): self.context.update_args(tuple(), kargs) self.context.check_some_args = True return self def async(self, timeout): self._async_timeout = timeout return self def times(self, n): self._times = n return self def called(): return MethodCalled() class never(BaseMatcher): def __init__(self, matcher): if not isinstance(matcher, OperationMatcher): raise WrongApiUsage( "takes called/called_with instance (got %s instead)" % matcher) self.matcher = matcher def _matches(self, item): return not self.matcher.matches(item) def describe_to(self, description): description.append_text('none of ').append_description_of(self.matcher) def describe_mismatch(self, actual, description): self.matcher.describe_mismatch(actual, description) class MockIsExpectedInvocation(BaseMatcher): 'assert the invocation is a mock expectation' def __init__(self, invocation): self.invocation = invocation def _matches(self, mock): self.mock = mock return self.invocation in mock._stubs def describe_to(self, description): description.append_text("these calls:\n") description.append_text(self.mock._stubs.show(indent=10)) def describe_mismatch(self, actual, description): description.append_text("this call was not expected:\n") description.append_text(self.invocation._show(indent=10)) class verify(BaseMatcher): def _matches(self, mock): if not isinstance(mock, MockBase): raise WrongApiUsage("takes Mock instance (got %s instead)" % mock) self.mock = mock return self._expectations_match() def _expectations_match(self): return self.mock._stubs == self.mock._recorded def describe_to(self, description): description.append_text("these calls:\n") description.append_text(self.mock._stubs.show(indent=10)) def describe_mismatch(self, actual, description): description.append_text('calls that actually ocurred were:\n') description.append_text(self.mock._recorded.show(indent=10)) class any_order_verify(verify): def _expectations_match(self): return sorted(self.mock._stubs) == sorted(self.mock._recorded) class property_got(OperationMatcher): def __init__(self, propname, times=any_time): super(property_got, self).__init__() self.propname = propname self._times = times def _matches(self, double): self.double = double self.operation = PropertyGet(self.double, self.propname) return double._received_invocation( self.operation, 1, cmp_pred=Invocation.__eq__) def times(self, n): self._times = n return self def describe_to(self, description): description.append_text('these calls:\n') description.append_text(self.operation._show(indent=10)) if self._times != any_time: description.append_text(' -- times: %s' % self._times) def describe_mismatch(self, actual, description): description.append_text('calls that actually ocurred were:\n') description.append_text(self.double._recorded.show(indent=10)) class property_set(OperationMatcher): def __init__(self, property_name, value=hamcrest.anything(), times=any_time): super(property_set, self).__init__() self.property_name = property_name self.value = value self._times = times def _matches(self, double): self.double = double self.operation = PropertySet(self.double, self.property_name, self.value) return self.double._received_invocation( self.operation, self._times, cmp_pred=Invocation.__eq__) def to(self, value): self.value = value return self def times(self, n): self._times = n return self def describe_to(self, description): description.append_text('these calls:\n') description.append_text(self.operation._show(indent=10)) if self._times != any_time: description.append_text(' -- times: %s' % self._times) def describe_mismatch(self, actual, description): description.append_text('calls that actually ocurred were:\n') description.append_text(self.double._recorded.show(indent=10)) doublex-1.7.2/doublex/__init__.py0000644000175000017500000000041512236777524016031 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- from functools import partial from .doubles import * from .matchers import * from .tracer import Tracer from .internal import WrongApiUsage def set_default_behavior(double, func): double._default_behavior = func doublex-1.7.2/doublex/py27_backports.py0000644000175000017500000001237112236777524017147 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- from inspect import getargspec, ismethod def total_ordering(cls): """Class decorator that fills in missing ordering methods""" convert = { '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)), ('__le__', lambda self, other: self < other or self == other), ('__ge__', lambda self, other: not self < other)], '__le__': [('__ge__', lambda self, other: not self <= other or self == other), ('__lt__', lambda self, other: self <= other and not self == other), ('__gt__', lambda self, other: not self <= other)], '__gt__': [('__lt__', lambda self, other: not (self > other or self == other)), ('__ge__', lambda self, other: self > other or self == other), ('__le__', lambda self, other: not self > other)], '__ge__': [('__le__', lambda self, other: (not self >= other) or self == other), ('__gt__', lambda self, other: self >= other and not self == other), ('__lt__', lambda self, other: not self >= other)] } roots = set(dir(cls)) & set(convert) if not roots: raise ValueError('must define at least one ordering operation: < > <= >=') root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__ for opname, opfunc in convert[root]: if opname not in roots: opfunc.__name__ = opname opfunc.__doc__ = getattr(int, opname).__doc__ setattr(cls, opname, opfunc) return cls def getcallargs(func, *positional, **named): """Get the mapping of arguments to values. A dict is returned, with keys the function argument names (including the names of the * and ** arguments, if any), and values the respective bound values from 'positional' and 'named'.""" args, varargs, varkw, defaults = getargspec(func) f_name = func.__name__ arg2value = {} # The following closures are basically because of tuple parameter unpacking. assigned_tuple_params = [] def assign(arg, value): if isinstance(arg, str): arg2value[arg] = value else: assigned_tuple_params.append(arg) value = iter(value) for i, subarg in enumerate(arg): try: subvalue = next(value) except StopIteration: raise ValueError('need more than %d %s to unpack' % (i, 'values' if i > 1 else 'value')) assign(subarg,subvalue) try: next(value) except StopIteration: pass else: raise ValueError('too many values to unpack') def is_assigned(arg): if isinstance(arg,str): return arg in arg2value return arg in assigned_tuple_params if ismethod(func) and func.im_self is not None: # implicit 'self' (or 'cls' for classmethods) argument positional = (func.im_self,) + positional num_pos = len(positional) num_total = num_pos + len(named) num_args = len(args) num_defaults = len(defaults) if defaults else 0 for arg, value in zip(args, positional): assign(arg, value) if varargs: if num_pos > num_args: assign(varargs, positional[-(num_pos-num_args):]) else: assign(varargs, ()) elif 0 < num_args < num_pos: raise TypeError('%s() takes %s %d %s (%d given)' % ( f_name, 'at most' if defaults else 'exactly', num_args, 'arguments' if num_args > 1 else 'argument', num_total)) elif num_args == 0 and num_total: if varkw: if num_pos: # XXX: We should use num_pos, but Python also uses num_total: raise TypeError('%s() takes exactly 0 arguments ' '(%d given)' % (f_name, num_total)) else: raise TypeError('%s() takes no arguments (%d given)' % (f_name, num_total)) for arg in args: if isinstance(arg, str) and arg in named: if is_assigned(arg): raise TypeError("%s() got multiple values for keyword " "argument '%s'" % (f_name, arg)) else: assign(arg, named.pop(arg)) if defaults: # fill in any missing values with the defaults for arg, value in zip(args[-num_defaults:], defaults): if not is_assigned(arg): assign(arg, value) if varkw: assign(varkw, named) elif named: unexpected = next(iter(named)) if isinstance(unexpected, unicode): unexpected = unexpected.encode(sys.getdefaultencoding(), 'replace') raise TypeError("%s() got an unexpected keyword argument '%s'" % (f_name, unexpected)) unassigned = num_args - len([arg for arg in args if is_assigned(arg)]) if unassigned: num_required = num_args - num_defaults raise TypeError('%s() takes %s %d %s (%d given)' % ( f_name, 'at least' if defaults else 'exactly', num_required, 'arguments' if num_required > 1 else 'argument', num_total)) return arg2value doublex-1.7.2/doublex/doubles.py0000644000175000017500000001427712236777524015742 0ustar piotrpiotr# -*- coding:utf-8; tab-width:4; mode:python -*- # doublex # # Copyright © 2012, 2013 David Villa Alises # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import inspect import hamcrest from .internal import (ANY_ARG, OperationList, Method, MockBase, SpyBase, AttributeFactory, WrongApiUsage) from .proxy import create_proxy, get_class from .matchers import MockIsExpectedInvocation __all__ = ['Stub', 'Spy', 'ProxySpy', 'Mock', 'Mimic', 'method_returning', 'method_raising', 'ANY_ARG'] class Stub(object): _default_behavior = lambda x: None _new_attr_hooks = [] def __new__(cls, collaborator=None): '''Creates a fresh class clone per instance. This is required due to ad-hoc stub properties are class attributes''' klass = cls._clone_class() return object.__new__(klass) @classmethod def _clone_class(cls): return type(cls.__name__, (cls,), dict(cls.__dict__)) def __init__(self, collaborator=None): self._proxy = create_proxy(collaborator) self._stubs = OperationList() self._setting_up = False self._new_attr_hooks = self._new_attr_hooks[:] self.__class__.__setattr__ = self.__setattr__hook def __enter__(self): self._setting_up = True return self def __exit__(self, *args): self._setting_up = False def _manage_invocation(self, invocation): self._proxy.assure_signature_matches(invocation) if self._setting_up: self._stubs.append(invocation) return invocation self._prepare_invocation(invocation) stubbed_retval = self._default_behavior() if invocation in self._stubs: stubbed = self._stubs.lookup(invocation) stubbed_retval = stubbed._apply_stub(invocation) actual_retval = self._perform_invocation(invocation) retval = stubbed_retval if stubbed_retval is not None else actual_retval invocation._context.retval = retval return retval def _prepare_invocation(self, invocation): pass def _perform_invocation(self, invocation): return None def __getattr__(self, key): AttributeFactory.create(self, key) return object.__getattribute__(self, key) def __setattr__hook(self, key, value): if key in self.__dict__: object.__setattr__(self, key, value) return try: AttributeFactory.create(self, key) except AttributeError: # collaborator has not attribute 'key', creaing it ad-hoc pass # descriptor protocol compliant object.__setattr__(self, key, value) def _classname(self): name = self._proxy.collaborator_classname() return name or self.__class__.__name__ class Spy(Stub, SpyBase): def __init__(self, collaborator=None): self._recorded = OperationList() super(Spy, self).__init__(collaborator) def _prepare_invocation(self, invocation): self._recorded.append(invocation) def _received_invocation(self, invocation, times, cmp_pred=None): return hamcrest.is_(times).matches( self._recorded.count(invocation, cmp_pred)) def _get_invocations_to(self, name): return [i for i in self._recorded if self._proxy.same_method(name, i._name)] class ProxySpy(Spy): def __init__(self, collaborator): self._assure_is_instance(collaborator) super(ProxySpy, self).__init__(collaborator) def _assure_is_instance(self, thing): if thing is None or inspect.isclass(thing): raise TypeError("ProxySpy takes an instance (got %s instead)" % thing) def _perform_invocation(self, invocation): return invocation._apply_on_collaborator() class Mock(Spy, MockBase): def _prepare_invocation(self, invocation): hamcrest.assert_that(self, MockIsExpectedInvocation(invocation)) super(Mock, self)._prepare_invocation(invocation) def Mimic(double, collab): def __getattribute__hook(self, key): if key in ['__class__', '__dict__', '_get_method', '_methods'] or \ key in [x[0] for x in inspect.getmembers(double)] or \ key in self.__dict__: return object.__getattribute__(self, key) return self._get_method(key) def _get_method(self, key): if key not in list(self._methods.keys()): typename = self._proxy.get_attr_typename(key) if typename not in ['instancemethod', 'function', 'method']: raise WrongApiUsage( "Mimic does not support attribute '%s' (type '%s')" % (key, typename)) method = Method(self, key) self._methods[key] = method return self._methods[key] assert issubclass(double, Stub), \ "Mimic() takes a double class as first argument (got %s instead)" & double collab_class = get_class(collab) generated_class = type( "Mimic_%s_for_%s" % (double.__name__, collab_class.__name__), (double, collab_class) + collab_class.__bases__, dict(_methods = {}, __getattribute__ = __getattribute__hook, _get_method = _get_method)) return generated_class(collab) def method_returning(value): with Stub() as stub: method = Method(stub, 'orphan') method(ANY_ARG).returns(value) return method def method_raising(exception): with Stub() as stub: method = Method(stub, 'orphan') method(ANY_ARG).raises(exception) return method doublex-1.7.2/make0000755000175000017500000000120412236777524013116 0ustar piotrpiotr#!/usr/bin/make -f # -*- mode:makefile -*- URL_AUTH=svn+ssh://${ALIOTH_USER}@svn.debian.org/svn/python-modules/packages/doublex/trunk URL_ANON=svn://svn.debian.org/svn/python-modules/packages/doublex/trunk debian: if [ ! -z "$${ALIOTH_USER}" ]; then \ svn co ${URL_AUTH} -N; \ else \ svn co ${URL_ANON} -N; \ fi mv trunk/.svn . rmdir trunk svn up debian wiki: hg clone ssh://hg@bitbucket.org/DavidVilla/python-doublex/wiki clean: find . -name *.pyc -delete find . -name *.pyo -delete find . -name *~ -delete $(RM) -r dist build *.egg-info $(RM) -r .svn debian MANIFEST $(RM) -r *.egg-info $(RM) -r slides/reveal.js doublex-1.7.2/CHANGES.rst0000644000175000017500000000242712236777524014065 0ustar piotrpiotr20131107 ======== - Release 1.7.2 - [NEW] support for varargs (*args, **kargs) methods - [NEW] tracer for doubles, methods and properties 20130712 ======== - Release 1.6.8 - [NEW] with_some_args matcher - [NEW] set_default_behavior module function to define behavior for non stubbed methods. 20130513 ======== - ANY_ARG is not allowed as keyword value - ANY_ARG must be the last positional argument value 20130427 ======== - Release 1.6.6 - [FIXED] stub/empty_stub were missing in pyDoubles wrapper 20130215 ======== - Release 1.6.3 - async race condition bug fixed 20130211 ======== - Access to spy invocations with _method_.calls 20130110 ======== - Release 1.6 - Ad-hoc stub attributes - AttributeFactory callable types: function, method (Closes: #bitbucket:issue/7) - BuiltingSignature for non Python functions 20121118 ======== - ProxySpy propagates stubbed invocations too 20121025 ======== - Merge feature-async branch: Spy async checking 20121008 ======== - release 1.5 to replace pyDoubles 20120928 ======== - ANY_ARG must be different to any other thing. 20120911 ======== - API CHANGE: called_with() is now called().with_args() (magmax suggestion) .. Local Variables: .. coding: utf-8 .. mode: rst .. mode: flyspell .. ispell-local-dictionary: "american" .. End: doublex-1.7.2/ToDo0000644000175000017500000000012512236777524013044 0ustar piotrpiotr- function doubles (supporting __call__ method) - orphan spy methods - double chains doublex-1.7.2/setup.py0000755000175000017500000000304712236777524013777 0ustar piotrpiotr#!/usr/bin/python import os import sys from setuptools import setup, find_packages # hack to prevent 'test' target exception: # http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html import multiprocessing, logging config = dict( name = 'doublex', version = '1.7.1', description = 'Test doubles for Python', keywords = ['unit test', 'double', 'stub', 'spy', 'mock'], author = 'David Villa Alises', author_email = 'David.Villa@gmail.com', url = 'https://bitbucket.org/DavidVilla/python-doublex', packages = find_packages(), data_files = [('', ['README.rst']), ('share/doc/python-doublex', ['README.rst'])], test_suite = 'doublex.test', license = 'GPLv3', long_description = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(), classifiers = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', ]) if sys.version_info >= (3,): config.update( use_2to3 = True, ) setup(**config) doublex-1.7.2/doublex.svg0000644000175000017500000001043212236777524014441 0ustar piotrpiotr image/svg+xml X X doublex-1.7.2/MANIFEST.in0000644000175000017500000000002312236777524014007 0ustar piotrpiotrinclude README.rst doublex-1.7.2/.hgignore0000644000175000017500000000003312236777524014055 0ustar piotrpiotrsyntax: glob .svn/* *.pyc doublex-1.7.2/BUGS0000644000175000017500000000007212236777524012740 0ustar piotrpiotr Spy stubbed method avoid collaborator method invocation doublex-1.7.2/pydoubles-site/0000755000175000017500000000000012236777524015226 5ustar piotrpiotrdoublex-1.7.2/pydoubles-site/release-notes0000644000175000017500000000607212236777524017724 0ustar piotrpiotr

doublex 1.6.6

doublex 1.6.5

doublex 1.6.4

  • Asynchronous spy assertion race condition bug fixed.
  • Reading double attributes returns collaborator.class attribute values by default.

doublex 1.6.2

  • Invocation stubbed return value is now stored.
  • New low level spy API: double method  "calls" property provides access to invocations and their argument values. Each 'call' has an "args" sequence and "kargs dictionary". This provides support to perform individual assertions and direct access to invocation argument values. (see test and doc).

doublex 1.6

  • First release supporting Python-3 (up to Python-3.2) [fixes issue 7].
  • Ad-hoc stub attributes (see test).
  • Partial support for non native Python functions.
  • ProxySpy propagated stubbed invocations too (see test).

doublex 1.5.1

This release includes support for asynchronous spy assertions. See this blog post for the time being, soon in the official documentation.

doublex/pyDoubles 1.5

Since this release the pyDoubles API is provided as a wrapper to doublex. However, there are small differences. pyDoubles matchers are not supported anymore, although you may get the same feature using standard hamcrest matchers. Anyway, legacy pyDoubles matchers are provided as hamcrest aliases. In most cases the only required change in your code is the module name, that change from:
from pyDoubles.framework.*
to:
from doublex.pyDoubles import *
If you have problems migrating to the new 1.5 release or migrating from pyDoubles to doublex, please ask for help in the discussion forum or in the issue tracker. doublex-1.7.2/pydoubles-site/support0000644000175000017500000000115712236777524016671 0ustar piotrpiotr

Free support

Mailing list: http://groups.google.com/group/pydoubles Issue tracker, mercurial repository: https://bitbucket.org/carlosble/pydoubles/overview Thanks to BitBucket!

Commercial support

The development team of pyDoubles is a software company based in Spain. We are happy to help other companies with the usage and extension of pyDoubles. If you want to have custom features or direct support, please contact us at info@iexpertos.com doublex-1.7.2/pydoubles-site/pydoubles-documentation0000644000175000017500000002716312236777524022037 0ustar piotrpiotr
class SimpleExample(unittest.TestCase):
   def test_ask_the_sender_to_send_the_report(self):
        sender = spy(Sender())
        service = SavingsService(sender)

        service.analyze_month()
        assert_that_method(sender.send_email).was_called(
                        ).with_args('reports@x.com', ANY_ARG)

Import the framework in your tests

import unittest
from doublex.pyDoubles import *
If you are afraid of importing everything from the pyDoubles.framework module, you can use custom imports, although it has been carefully designed to not conflict with your own classes.
import unittest
from doublex.pyDoubles import stub, spy, mock
from doublex.pyDoubles import when, expect_call, assert_that_method
from doublex.pyDoubles import method_returning, method_raising
You can import Hamcrest matchers which are fully supported:
from hamcrest import *

Which doubles do you need?

You can choose to stub out a method in a regular object instance, to stub the whole object, or to create three types of spies and two types of mock objects.

Stubs

There are several ways to stub out methods.
Stub out a single method
If you just need to replace a single method in the collaborator object and you don't care about the input parameters, you can stub out just that single method:
collaborator = Collaborator() # create the actual object
collaborator.some_calculation = method_returning(10)
Now, when your production code invokes the method "some_calculation" in the collaborator object, the framework will return 10, no matter what parameters are passed in as the input. If you want the method to raise an exception when called use this:
collaborator.some_calculation = method_raising(ApplicationException())
You can pass in any type of exception.
Stub out the whole object
Now the collaborator instance won't be the actual object but a replacement.
collaborator = stub(Collaborator())
Any method will return "None" when called with any input parameters. If you want to change the return value you can use the "when" sentence:
when(collaborator.some_calculation).then_return(10)
Now, when your production code invokes "some_calculation" method, the stub will return 10, no matter what arguments are passed in. You can also specify different return values depending on the input:
when(collaborator.some_calculation).with_args(5).then_return(10)
when(collaborator.some_calculation).with_args(10).then_return(20)
This means that "collaborator.some_calculation(5)" will return 10, and that it will return 20 when the input is 10. You can define as many input/output specifications as you want.
when(collaborator.some_calculation).with_args(5).then_return(10)
when(collaborator.some_calculation).then_return(20)
This time, "collaborator.some_calculation(5)" will return 10, and it will return 20 in any other case.
Any argument matches
The special keyword ANY_ARG is a wildcard for any argument in the stubbed method:
when(collaborator.some_other_method).with_args(5, ANY_ARG).then_return(10)
The method "some_other_method" will return 10 as long as the first parameter is 5, no matter what the second parameter is. You can use any combination of "ANY_ARG" arguments. But remember that if all of them are ANY, you shouldn't specify the arguments, just use this:
when(collaborator.some_other_method).then_return(10)
It is also possible to make the method return exactly the first parameter passed in:
when(collaborator.some_other_method).then_return_input()
So this call: collaborator.some_other_method(10) wil return 10.
Matchers
You can also specify that arguments will match a certain function. Say that you want to return a value only if the input argument contains the substring "abc":
when(collaborator.some_method).with_args(
        str_containing("abc")).then_return(10)
In the last release, pyDoubles matchers are just aliases for the hamcrest counterparts. See release notes.
Hamcrest Matchers
Since pyDoubles v1.2, we fully support Hamcrest matchers. They are used exactly like pyDoubles matchers:
from hamcrest import *
from doublex.pyDoubles import *

    def test_has_entry_matcher(self):
        list = {'one':1, 'two':2}
        when(self.spy.one_arg_method).with_args(
            has_entry(equal_to('two'), 2)).then_return(1000)
        assert_that(1000, equal_to(self.spy.one_arg_method(list)))

    def test_all_of_matcher(self):
        text = 'hello'
        when(self.spy.one_arg_method).with_args(
            all_of(starts_with('h'), instance_of(str))).then_return(1000)
        assert_that(1000, equal_to(self.spy.one_arg_method(text)))
Note that the tests above are just showhing the pyDoubles framework working together with Hamcrest, they are not good examples of unit tests for your production code. The method assert_that comes from Hamcrest, as well as the matchers: has_entry, equal_to, all_of, starts_with, instance_of. Notice that all_of and any_of, allow you to define more than one matcher for a single argument, which is really powerful. For more informacion on matchers, read this blog post.
Stub out the whole unexisting object
If the Collaborator class does not exist yet, or you don't want the framework to check that the call to the stub object method matches the actual API in the actual object, you can use an "empty" stub.
collaborator = empty_stub()
when(collaborator.alpha_operation).then_return("whatever")
The framework is creating the method "alpha_operation" dynamically and making it return "whatever". The use of empty_stub, empty_spy or empty_mock is not recommended because you lose the API match check. We only use them as the construction of the object is too complex among other circumstances.

Spies

Please read the documentation above about stubs, because the API to define method behaviors is the same for stubs and spies. To create the object:
collaborator = spy(Collaborator())
After the execution of the system under test, we want to validate that certain call was made:
assert_that_method(collaborator.send_email).was_called()
That will make the test pass if method "send_email" was invoked one or more times, no matter what arguments were passed in. We can also be precise about the arguments:
assert_that_method(collaborator.send_email).was_called().with_args("example@iexpertos.com")
Notice that you can combine the "when" statement with the called assertion:
def test_sut_asks_the_collaborator_to_send_the_email(self):
   sender = spy(Sender())
   when(sender.send_email).then_return(SUCCESS)
   object_under_test = Sut(sender)

   object_under_test.some_action()

   assert_that_method(
 sender.send_email).was_called().with_args("example@iexpertos.com")
Any other call to any method in the "sender" double will return "None" and will not interrupt the test. We are not telling all that happens between the sender and the SUT, we are just asserting on what we want to verify. The ANY_ARG matcher can be used to verify the call as well:
assert_that_method(collaborator.some_other_method).was_called().with_args(5, ANY_ARG)
Matchers can also be used in the assertion:
assert_that_method(collaborator.some_other_method).was_called().with_args(5, str_containing("abc"))
It is also possible to assert that wasn't called using:
assert_that_method(collaborator.some_method).was_never_called()
You can assert on the number of times a call was made:
assert_that_method(collaborator.some_method).was_called().times(2)
assert_that_method(collaborator.some_method).was_called(
     ).with_args(SOME_VALUE, OTHER_VALUE).times(2)
You can also create an "empty_spy" to not base the object in a certain instance:
sender = empty_spy()
The ProxySpy
There is a special type of spy supported by the framework which is the ProxySpy:
collaborator = proxy_spy(Collaborator())
The proxy spy will record any call made to the object but rather than replacing the actual methods in the actual object, it will execute them. So the actual methods in the Collaborator will be invoked by default. You can replace the methods one by one using the "when" statement:
when(collaborator.some_calculation).then_return(1000)
Now "some_calculation" method will be a stub method but the remaining methods in the class will be the regular implementation. The ProxySpy might be interesting when you don't know what the actual method will return in a given scenario, but still you want to check that some call is made. It can be used for debugging purposes.

Mocks

Before calls are made, they have to be expected:
def test_sut_asks_the_collaborator_to_send_the_email(self):
   sender = mock(Sender())
   expect_call(sender.send_email)
   object_under_test = Sut(sender)

   object_under_test.some_action()

   sender.assert_that_is_satisfied()
The test is quite similar to the one using a spy. However the framework behaves different. If any other call to the sender is made during "some_action", the test will fail. This makes the test more fragile. However, it makes sure that this interaction is the only one between the two objects, and this might be important for you.
More precise expectations
You can also expect the call to have certain input parameters:
expect_call(sender.send_email).with_args("example@iexpertos.com")
Setting the return of the expected call
Additionally, if you want to return anything when the expected call occurs, there are two ways:
expect_call(sender.send_email).returning(SUCCESS)
Which will return SUCCESS whatever arguments you pass in, or
expect_call(sender.send_email).with_args("wrong_email").returning(FAILURE)
Which expects the method to be invoked with "wrong_email" and will return FAILURE. Mocks are strict so if you expect the call to happen several times, be explicit with that:
expect_call(sender.send_email).times(2)
expect_call(sender.send_email).with_args("admin@iexpertos.com").times(2)
Make sure the "times" part is at the end of the sentence:
expect_call(sender.send_email).with_args("admin@iexpertos.com").returning('OK').times(2)
As you might have seen, the "when" statement is not used for mocks, only for stubs and spies. Mock objects use the "expect_call" syntax together with the "assert_that_is_satisfied" (instance method).

More documentation

The best and most updated documentation are the unit tests of the framework itself. We encourage the user to read the tests and see what features are supported in every commit into the source code repository: pyDoublesTests/unit.py You can also read about what's new in every release in the blog doublex-1.7.2/pydoubles-site/doublex-documentation0000644000175000017500000000413312236777524021463 0ustar piotrpiotrFor the time being you can find the doublex API documentation at: https://bitbucket.org/DavidVilla/python-doublex/wiki

What provides doublex respect to pyDoubles?

Respect to pyDoubles, doublex...:
  • Use just hamcrest matchers (for all features).
  • Only ProxySpy requires an instance. Other doubles accept a class too, and they never instantiate it.
  • Stub observers: Notify arbitrary hooks when methods are invoked. Useful to add "side effects".
  • Stub delegates: Use callables, iterables or generators to create stub return values.
  • Mimic doubles: doubles that inherit the same collaborator subclasses. This provides full LSP for code that make strict type checking.
doublex support all the issues notified in the pyDoubles issue tracker: And other features requested in the user group:   doublex-1.7.2/pydoubles-site/overview0000644000175000017500000001045512236777524017024 0ustar piotrpiotr

What is pyDoubles?

pyDoubles is a test doubles framework for the Python platform. Test doubles frameworks are also called mocking frameworks. pyDoubles can be used as a testing tool or as a Test Driven Development tool. It generates stubs, spies, and mock objects using a fluent interface that will make your unit tests more readable. Moreover, it's been designed to make your tests less fragile when possible. The development of pyDoubles has been completely test-driven from scratch. The project is under continuous evolution, but you can extend the framework with your own requirements. The code is simple and well documented with unit tests.

What is doublex?

doublex is a new doubles framework that optionally provides the pyDoubles legacy API. It supports all the pyDoubles features and some more that can not be easely backported. If you are a pyDoubles user you can run your tests using doublex.pyDoubles module. However, we recommed the native doublex API for your new developments.

Supported test doubles

Find out what test doubles are according to Gerard Meszaros. pyDoubles offers mainly three kind of doubles:

Stub

Replaces the implementation of one or more methods in the object instance which plays the role of collaborator or dependency, returning the value that we explicitly write down in the test. A stub is actually a method but it is also common to use the noun stub for a class with stubbed methods. The stub does not have any kind or memory. Stubs are used mainly for state validation or along with spies or mocks.

Spy

Replaces the implementation as a stub does, but it is also able to register and remember what methods are called during the test execution and how they are invoked. They are used for interaction/behavior verification.

Mock

Contains the same features than the Stub and therefore the Spy, but it is very strict in the behavior specification it should expect from the System Under Tests. Before calling any method in the mock object, the framework should be told (in the test) which methods we expect to be called in order for them to succeed. Otherwise, the test will fail with an "UnexpectedBehavior" exception. Mock objects are used when we have to be very precise in the behavior specification. They usually make the tests more fragile than a spy but still are necessary in many cases. It is common to use mock objects together with stubs in tests.

New to test doubles?

A unit test is comprised of three parts: Arrange/Act/Assert or Given/When/Then or whatever you want to call them. The scenario has to be created, exercised, and eventually we verify that the expected behavior happened. The test doubles framework is used to create the scenario (create the objects), and verify behavior after the execution but it does not make sense to invoke test doubles' methods in the test code. If you call the doubles' methods in the test code, you are testing the framework itself, which has been already tested (better than that, we crafted it using TDD). Make sure the calls to the doubles' methods happen in your production code.

Why another framework?

pyDoubles is inspired in mockito and jMock for Java, and also inspired in Rhino.Mocks for .Net. There are other frameworks for Python that work really well, but after some time using them, we were not really happy with the syntax and the readability of the tests. Fragile tests were also a problem. Some well-known frameworks available for Python are: mocker, mockito-python, mock, pymox. pyDoubles is open source and free software, released under the Apache License Version 2.0 Take a look at the project's blog doublex-1.7.2/pydoubles-site/downloads0000644000175000017500000000132412236777524017143 0ustar piotrpiotrGet latest release from here
gunzip doublex-X.X.tar.gz
tar xvf doublex-X.X.tar
cd doublex-X.X/
sudo python setup.py install
Or use pip:
$ sudo pip install doubles-X.X.tar.gz
Pydoubles is also available on Pypi:
$ sudo pip install doublex
You can also get the latest source code from the mercurial repository. Check out the project:
$ hg clone https://bitbucket.org/DavidVilla/python-doublex
Browse the source code, get support and notify bugs in the issue tracker. doublex-1.7.2/README.rst0000644000175000017500000000173212236777524013750 0ustar piotrpiotrdoublex ======= * `documentation `_ * `release notes `_ * `slides `_ * `sources `_ * `PyPI project `_ * `pydoubles.org `_ * `buildbot job `_ * `other Python doubles libraries `_ debian ------ * package: http://packages.debian.org/source/sid/doublex * debian dir: ``svn://svn.debian.org/svn/python-modules/packages/doublex/trunk`` * amateur debian package at: ``deb http://babel.esi.uclm.es/arco/ sid main`` * official ubuntu package: https://launchpad.net/ubuntu/+source/doublex