Python mocking elasticsearch connection generator `with` statement












0















I would like to test a class with a function that has with statement in it:



func_to_test():
....
with self.__elastic_generator.get() as es:
print 'about to use the es connection....'


So I mocked the elstic_generator, and I mocked it get function when creating the class tested:



elastic_gen = mock.Mock()
elstic_gen.get = mock.Mock()
elastic_gen.get.side_effect = ['mocked elastic connection']
tested_class = TestedClass(elastic_gen)
tested_class.func_to_test()


But for some reason that doesn't work when using the with statement.
However, if getting the connection without using with, like this:



x = self.__elastic_generator.get()



Then it works fine, and I get x = 'mocked elastic connection'.



So I guess the problem is related to some more functions calls being made when using the with and that I don't mock these functions.



Can someone please explain what happens under the hood and what else should I mock in order to be able to test it with the with statement?



Thanks.










share|improve this question



























    0















    I would like to test a class with a function that has with statement in it:



    func_to_test():
    ....
    with self.__elastic_generator.get() as es:
    print 'about to use the es connection....'


    So I mocked the elstic_generator, and I mocked it get function when creating the class tested:



    elastic_gen = mock.Mock()
    elstic_gen.get = mock.Mock()
    elastic_gen.get.side_effect = ['mocked elastic connection']
    tested_class = TestedClass(elastic_gen)
    tested_class.func_to_test()


    But for some reason that doesn't work when using the with statement.
    However, if getting the connection without using with, like this:



    x = self.__elastic_generator.get()



    Then it works fine, and I get x = 'mocked elastic connection'.



    So I guess the problem is related to some more functions calls being made when using the with and that I don't mock these functions.



    Can someone please explain what happens under the hood and what else should I mock in order to be able to test it with the with statement?



    Thanks.










    share|improve this question

























      0












      0








      0








      I would like to test a class with a function that has with statement in it:



      func_to_test():
      ....
      with self.__elastic_generator.get() as es:
      print 'about to use the es connection....'


      So I mocked the elstic_generator, and I mocked it get function when creating the class tested:



      elastic_gen = mock.Mock()
      elstic_gen.get = mock.Mock()
      elastic_gen.get.side_effect = ['mocked elastic connection']
      tested_class = TestedClass(elastic_gen)
      tested_class.func_to_test()


      But for some reason that doesn't work when using the with statement.
      However, if getting the connection without using with, like this:



      x = self.__elastic_generator.get()



      Then it works fine, and I get x = 'mocked elastic connection'.



      So I guess the problem is related to some more functions calls being made when using the with and that I don't mock these functions.



      Can someone please explain what happens under the hood and what else should I mock in order to be able to test it with the with statement?



      Thanks.










      share|improve this question














      I would like to test a class with a function that has with statement in it:



      func_to_test():
      ....
      with self.__elastic_generator.get() as es:
      print 'about to use the es connection....'


      So I mocked the elstic_generator, and I mocked it get function when creating the class tested:



      elastic_gen = mock.Mock()
      elstic_gen.get = mock.Mock()
      elastic_gen.get.side_effect = ['mocked elastic connection']
      tested_class = TestedClass(elastic_gen)
      tested_class.func_to_test()


      But for some reason that doesn't work when using the with statement.
      However, if getting the connection without using with, like this:



      x = self.__elastic_generator.get()



      Then it works fine, and I get x = 'mocked elastic connection'.



      So I guess the problem is related to some more functions calls being made when using the with and that I don't mock these functions.



      Can someone please explain what happens under the hood and what else should I mock in order to be able to test it with the with statement?



      Thanks.







      python python-2.7 mocking with-statement python-mock






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 15 '18 at 9:32









      NoamNoam

      469520




      469520
























          1 Answer
          1






          active

          oldest

          votes


















          1














          The with statement is a concept known as a context manager. A context manager has an __enter__ function for when you're entering the the with and an __exit__ function for when you're exiting the with (either by raising or by execution finishing inside the block).



          The __enter__ function should return the value of whatever you're expecting to be assigned to the variable after as, which in this case would be es. So, to mock that, you don't want to mock the return value of .get(), you want to mock the return value of .get().__enter__(). That should look like this:



          elastic_gen = mock.Mock()
          elastic_gen.return_value.__enter__.return_value = 'mocked elastic connection'





          share|improve this answer
























          • Yep. I did something like this, along side with mocking the exit function. Now it's working, thx for explaining

            – Noam
            Nov 15 '18 at 12:12











          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%2f53316287%2fpython-mocking-elasticsearch-connection-generator-with-statement%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          The with statement is a concept known as a context manager. A context manager has an __enter__ function for when you're entering the the with and an __exit__ function for when you're exiting the with (either by raising or by execution finishing inside the block).



          The __enter__ function should return the value of whatever you're expecting to be assigned to the variable after as, which in this case would be es. So, to mock that, you don't want to mock the return value of .get(), you want to mock the return value of .get().__enter__(). That should look like this:



          elastic_gen = mock.Mock()
          elastic_gen.return_value.__enter__.return_value = 'mocked elastic connection'





          share|improve this answer
























          • Yep. I did something like this, along side with mocking the exit function. Now it's working, thx for explaining

            – Noam
            Nov 15 '18 at 12:12
















          1














          The with statement is a concept known as a context manager. A context manager has an __enter__ function for when you're entering the the with and an __exit__ function for when you're exiting the with (either by raising or by execution finishing inside the block).



          The __enter__ function should return the value of whatever you're expecting to be assigned to the variable after as, which in this case would be es. So, to mock that, you don't want to mock the return value of .get(), you want to mock the return value of .get().__enter__(). That should look like this:



          elastic_gen = mock.Mock()
          elastic_gen.return_value.__enter__.return_value = 'mocked elastic connection'





          share|improve this answer
























          • Yep. I did something like this, along side with mocking the exit function. Now it's working, thx for explaining

            – Noam
            Nov 15 '18 at 12:12














          1












          1








          1







          The with statement is a concept known as a context manager. A context manager has an __enter__ function for when you're entering the the with and an __exit__ function for when you're exiting the with (either by raising or by execution finishing inside the block).



          The __enter__ function should return the value of whatever you're expecting to be assigned to the variable after as, which in this case would be es. So, to mock that, you don't want to mock the return value of .get(), you want to mock the return value of .get().__enter__(). That should look like this:



          elastic_gen = mock.Mock()
          elastic_gen.return_value.__enter__.return_value = 'mocked elastic connection'





          share|improve this answer













          The with statement is a concept known as a context manager. A context manager has an __enter__ function for when you're entering the the with and an __exit__ function for when you're exiting the with (either by raising or by execution finishing inside the block).



          The __enter__ function should return the value of whatever you're expecting to be assigned to the variable after as, which in this case would be es. So, to mock that, you don't want to mock the return value of .get(), you want to mock the return value of .get().__enter__(). That should look like this:



          elastic_gen = mock.Mock()
          elastic_gen.return_value.__enter__.return_value = 'mocked elastic connection'






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 15 '18 at 12:01









          wholevinskiwholevinski

          2,228815




          2,228815













          • Yep. I did something like this, along side with mocking the exit function. Now it's working, thx for explaining

            – Noam
            Nov 15 '18 at 12:12



















          • Yep. I did something like this, along side with mocking the exit function. Now it's working, thx for explaining

            – Noam
            Nov 15 '18 at 12:12

















          Yep. I did something like this, along side with mocking the exit function. Now it's working, thx for explaining

          – Noam
          Nov 15 '18 at 12:12





          Yep. I did something like this, along side with mocking the exit function. Now it's working, thx for explaining

          – Noam
          Nov 15 '18 at 12:12




















          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%2f53316287%2fpython-mocking-elasticsearch-connection-generator-with-statement%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







          Popular posts from this blog

          List item for chat from Array inside array React Native

          Thiostrepton

          Caerphilly