Python Mock Autospec vs Spec










6















Trying to wrap my head around the difference between Spec and Autospec. They seem to be about the same. Specifically, if you look at mock.patch decorator.



Can someone explain when to use which?



http://www.voidspace.org.uk/python/mock/patch.html










share|improve this question


























    6















    Trying to wrap my head around the difference between Spec and Autospec. They seem to be about the same. Specifically, if you look at mock.patch decorator.



    Can someone explain when to use which?



    http://www.voidspace.org.uk/python/mock/patch.html










    share|improve this question
























      6












      6








      6








      Trying to wrap my head around the difference between Spec and Autospec. They seem to be about the same. Specifically, if you look at mock.patch decorator.



      Can someone explain when to use which?



      http://www.voidspace.org.uk/python/mock/patch.html










      share|improve this question














      Trying to wrap my head around the difference between Spec and Autospec. They seem to be about the same. Specifically, if you look at mock.patch decorator.



      Can someone explain when to use which?



      http://www.voidspace.org.uk/python/mock/patch.html







      python-2.7 mocking python-unittest






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Sep 20 '16 at 3:35









      AllenAllen

      448415




      448415






















          2 Answers
          2






          active

          oldest

          votes


















          2














          spec is used as a template for your Mock object. In the words of the documentation:




          If you use the spec or spec_set arguments then only magic methods that exist in the spec will be created.




          This means that you cannot call methods on the mock object that do not exist on the object you are mocking. The documentation explains this like this:




          Note If you use the spec keyword argument to create a mock then attempting to set a magic method that isn’t in the spec will raise an AttributeError.




          autospec is basically a shorthand in patch for passing in the object your patching to the spec of the MagicMock being created. Documentation:




          If you set autospec=True then the mock with be created with a spec from the object being replaced.







          share|improve this answer






























            0














            spec applies only to the mock instance where it is specified. In particular, if the mocked class a has a method, e.g. method(), then calling that method in the instanciated mock of a will automatically generate and return another mock that is not restricted to any spec. This is where autospec comes in handy, as it recursively defines specs on whatever is called (within the restrictions of the specs defined up to that point).



            From the Mock Autospeccing Helper documentation:




            If you use a class or instance as the spec for a mock then you can only access attributes on the mock that exist on the real class:




            >>> import urllib2
            >>> mock = Mock(spec=urllib2.Request)
            >>> mock.assret_called_with
            Traceback (most recent call last):
            ...
            AttributeError: Mock object has no attribute 'assret_called_with'



            The spec only applies to the mock itself, so we still have the same issue with any methods on the mock:




            >>> mock.has_data()
            <mock.Mock object at 0x...>
            >>> mock.has_data.assret_called_with()



            Auto-speccing solves this problem.







            share|improve this answer






















              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f39585309%2fpython-mock-autospec-vs-spec%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              2














              spec is used as a template for your Mock object. In the words of the documentation:




              If you use the spec or spec_set arguments then only magic methods that exist in the spec will be created.




              This means that you cannot call methods on the mock object that do not exist on the object you are mocking. The documentation explains this like this:




              Note If you use the spec keyword argument to create a mock then attempting to set a magic method that isn’t in the spec will raise an AttributeError.




              autospec is basically a shorthand in patch for passing in the object your patching to the spec of the MagicMock being created. Documentation:




              If you set autospec=True then the mock with be created with a spec from the object being replaced.







              share|improve this answer



























                2














                spec is used as a template for your Mock object. In the words of the documentation:




                If you use the spec or spec_set arguments then only magic methods that exist in the spec will be created.




                This means that you cannot call methods on the mock object that do not exist on the object you are mocking. The documentation explains this like this:




                Note If you use the spec keyword argument to create a mock then attempting to set a magic method that isn’t in the spec will raise an AttributeError.




                autospec is basically a shorthand in patch for passing in the object your patching to the spec of the MagicMock being created. Documentation:




                If you set autospec=True then the mock with be created with a spec from the object being replaced.







                share|improve this answer

























                  2












                  2








                  2







                  spec is used as a template for your Mock object. In the words of the documentation:




                  If you use the spec or spec_set arguments then only magic methods that exist in the spec will be created.




                  This means that you cannot call methods on the mock object that do not exist on the object you are mocking. The documentation explains this like this:




                  Note If you use the spec keyword argument to create a mock then attempting to set a magic method that isn’t in the spec will raise an AttributeError.




                  autospec is basically a shorthand in patch for passing in the object your patching to the spec of the MagicMock being created. Documentation:




                  If you set autospec=True then the mock with be created with a spec from the object being replaced.







                  share|improve this answer













                  spec is used as a template for your Mock object. In the words of the documentation:




                  If you use the spec or spec_set arguments then only magic methods that exist in the spec will be created.




                  This means that you cannot call methods on the mock object that do not exist on the object you are mocking. The documentation explains this like this:




                  Note If you use the spec keyword argument to create a mock then attempting to set a magic method that isn’t in the spec will raise an AttributeError.




                  autospec is basically a shorthand in patch for passing in the object your patching to the spec of the MagicMock being created. Documentation:




                  If you set autospec=True then the mock with be created with a spec from the object being replaced.








                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Oct 30 '17 at 19:01









                  ParhamParham

                  1,06111536




                  1,06111536























                      0














                      spec applies only to the mock instance where it is specified. In particular, if the mocked class a has a method, e.g. method(), then calling that method in the instanciated mock of a will automatically generate and return another mock that is not restricted to any spec. This is where autospec comes in handy, as it recursively defines specs on whatever is called (within the restrictions of the specs defined up to that point).



                      From the Mock Autospeccing Helper documentation:




                      If you use a class or instance as the spec for a mock then you can only access attributes on the mock that exist on the real class:




                      >>> import urllib2
                      >>> mock = Mock(spec=urllib2.Request)
                      >>> mock.assret_called_with
                      Traceback (most recent call last):
                      ...
                      AttributeError: Mock object has no attribute 'assret_called_with'



                      The spec only applies to the mock itself, so we still have the same issue with any methods on the mock:




                      >>> mock.has_data()
                      <mock.Mock object at 0x...>
                      >>> mock.has_data.assret_called_with()



                      Auto-speccing solves this problem.







                      share|improve this answer



























                        0














                        spec applies only to the mock instance where it is specified. In particular, if the mocked class a has a method, e.g. method(), then calling that method in the instanciated mock of a will automatically generate and return another mock that is not restricted to any spec. This is where autospec comes in handy, as it recursively defines specs on whatever is called (within the restrictions of the specs defined up to that point).



                        From the Mock Autospeccing Helper documentation:




                        If you use a class or instance as the spec for a mock then you can only access attributes on the mock that exist on the real class:




                        >>> import urllib2
                        >>> mock = Mock(spec=urllib2.Request)
                        >>> mock.assret_called_with
                        Traceback (most recent call last):
                        ...
                        AttributeError: Mock object has no attribute 'assret_called_with'



                        The spec only applies to the mock itself, so we still have the same issue with any methods on the mock:




                        >>> mock.has_data()
                        <mock.Mock object at 0x...>
                        >>> mock.has_data.assret_called_with()



                        Auto-speccing solves this problem.







                        share|improve this answer

























                          0












                          0








                          0







                          spec applies only to the mock instance where it is specified. In particular, if the mocked class a has a method, e.g. method(), then calling that method in the instanciated mock of a will automatically generate and return another mock that is not restricted to any spec. This is where autospec comes in handy, as it recursively defines specs on whatever is called (within the restrictions of the specs defined up to that point).



                          From the Mock Autospeccing Helper documentation:




                          If you use a class or instance as the spec for a mock then you can only access attributes on the mock that exist on the real class:




                          >>> import urllib2
                          >>> mock = Mock(spec=urllib2.Request)
                          >>> mock.assret_called_with
                          Traceback (most recent call last):
                          ...
                          AttributeError: Mock object has no attribute 'assret_called_with'



                          The spec only applies to the mock itself, so we still have the same issue with any methods on the mock:




                          >>> mock.has_data()
                          <mock.Mock object at 0x...>
                          >>> mock.has_data.assret_called_with()



                          Auto-speccing solves this problem.







                          share|improve this answer













                          spec applies only to the mock instance where it is specified. In particular, if the mocked class a has a method, e.g. method(), then calling that method in the instanciated mock of a will automatically generate and return another mock that is not restricted to any spec. This is where autospec comes in handy, as it recursively defines specs on whatever is called (within the restrictions of the specs defined up to that point).



                          From the Mock Autospeccing Helper documentation:




                          If you use a class or instance as the spec for a mock then you can only access attributes on the mock that exist on the real class:




                          >>> import urllib2
                          >>> mock = Mock(spec=urllib2.Request)
                          >>> mock.assret_called_with
                          Traceback (most recent call last):
                          ...
                          AttributeError: Mock object has no attribute 'assret_called_with'



                          The spec only applies to the mock itself, so we still have the same issue with any methods on the mock:




                          >>> mock.has_data()
                          <mock.Mock object at 0x...>
                          >>> mock.has_data.assret_called_with()



                          Auto-speccing solves this problem.








                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 14 '18 at 14:58









                          seronseron

                          1,95332036




                          1,95332036



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f39585309%2fpython-mock-autospec-vs-spec%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              這個網誌中的熱門文章

                              How to read a connectionString WITH PROVIDER in .NET Core?

                              In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

                              Museum of Modern and Contemporary Art of Trento and Rovereto