Mock email payload on pythonCalling an external command in PythonWhat are metaclasses in Python?Is there a way to run Python on Android?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonHow can I make a time delay in Python?Does Python have a string 'contains' substring method?

How to split IPA spelling into syllables

Why does a 97 / 92 key piano exist by Bosendorfer?

A seasonal riddle

1 John in Luther’s Bibel

How to test the sharpness of a knife?

Should a narrator ever describe things based on a character's view instead of facts?

If the Dominion rule using their Jem'Hadar troops, why is their life expectancy so low?

What is the meaning of "You've never met a graph you didn't like?"

Showing mass murder in a kid's book

Friend wants my recommendation but I don't want to give it to him

What is this high flying aircraft over Pennsylvania?

Has the laser at Magurele, Romania reached a tenth of the Sun's power?

How do you say "Trust your struggle." in French?

"Marked down as someone wanting to sell shares." What does that mean?

Rendered textures different to 3D View

What properties make a magic weapon befit a Rogue more than a DEX-based Fighter?

Extract substring according to regexp with sed or grep

Pre-Employment Background Check With Consent For Future Checks

Is divisi notation needed for brass or woodwind in an orchestra?

Did I make a mistake by ccing email to boss to others?

Offset in split text content

Unfrosted light bulb

Should I be concerned about student access to a test bank?

"Oh no!" in Latin



Mock email payload on python


Calling an external command in PythonWhat are metaclasses in Python?Is there a way to run Python on Android?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonHow can I make a time delay in Python?Does Python have a string 'contains' substring method?













0















I'm writing unit tests for a function that should get all valid attachments in email message. My function has the following behaviour:



def extract_attachments(local_file):
email_file = open(local_file, "r")
msg = email.message_from_file(email_file)
attchs = [x for x in msg.get_payload() if x.get_filename() is not None]
for attch in attchs:
filename = attch.get_filename()
if filename not in VALID_ATTACHMENTS:
raise Exception('Invalid attachment', filename)
return attchs


How can I make this function return some object with a function get_filename()?



I'm trying to patch it but I'm getting an error 'list' object has no attribute 'get_payload'.



@patch("mail_extractor.process_email.email")
@patch("builtins.open")
def test_extract_attachments(open, email):
email.message_from_file.return_value = []
email.get_payload.return_value = ['1.xml']
result = process_email.extract_attachments('mock')
assert len(result) == 1









share|improve this question




























    0















    I'm writing unit tests for a function that should get all valid attachments in email message. My function has the following behaviour:



    def extract_attachments(local_file):
    email_file = open(local_file, "r")
    msg = email.message_from_file(email_file)
    attchs = [x for x in msg.get_payload() if x.get_filename() is not None]
    for attch in attchs:
    filename = attch.get_filename()
    if filename not in VALID_ATTACHMENTS:
    raise Exception('Invalid attachment', filename)
    return attchs


    How can I make this function return some object with a function get_filename()?



    I'm trying to patch it but I'm getting an error 'list' object has no attribute 'get_payload'.



    @patch("mail_extractor.process_email.email")
    @patch("builtins.open")
    def test_extract_attachments(open, email):
    email.message_from_file.return_value = []
    email.get_payload.return_value = ['1.xml']
    result = process_email.extract_attachments('mock')
    assert len(result) == 1









    share|improve this question


























      0












      0








      0


      0






      I'm writing unit tests for a function that should get all valid attachments in email message. My function has the following behaviour:



      def extract_attachments(local_file):
      email_file = open(local_file, "r")
      msg = email.message_from_file(email_file)
      attchs = [x for x in msg.get_payload() if x.get_filename() is not None]
      for attch in attchs:
      filename = attch.get_filename()
      if filename not in VALID_ATTACHMENTS:
      raise Exception('Invalid attachment', filename)
      return attchs


      How can I make this function return some object with a function get_filename()?



      I'm trying to patch it but I'm getting an error 'list' object has no attribute 'get_payload'.



      @patch("mail_extractor.process_email.email")
      @patch("builtins.open")
      def test_extract_attachments(open, email):
      email.message_from_file.return_value = []
      email.get_payload.return_value = ['1.xml']
      result = process_email.extract_attachments('mock')
      assert len(result) == 1









      share|improve this question
















      I'm writing unit tests for a function that should get all valid attachments in email message. My function has the following behaviour:



      def extract_attachments(local_file):
      email_file = open(local_file, "r")
      msg = email.message_from_file(email_file)
      attchs = [x for x in msg.get_payload() if x.get_filename() is not None]
      for attch in attchs:
      filename = attch.get_filename()
      if filename not in VALID_ATTACHMENTS:
      raise Exception('Invalid attachment', filename)
      return attchs


      How can I make this function return some object with a function get_filename()?



      I'm trying to patch it but I'm getting an error 'list' object has no attribute 'get_payload'.



      @patch("mail_extractor.process_email.email")
      @patch("builtins.open")
      def test_extract_attachments(open, email):
      email.message_from_file.return_value = []
      email.get_payload.return_value = ['1.xml']
      result = process_email.extract_attachments('mock')
      assert len(result) == 1






      python mocking python-unittest






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 7 at 1:43









      iBug

      21.4k64066




      21.4k64066










      asked Mar 7 at 1:09









      placplacboomplacplacboom

      94811634




      94811634






















          2 Answers
          2






          active

          oldest

          votes


















          0














          The notation you've described is specific to objects, and what you're trying to give it is a method. You'll need to define a class:



          class MyClass:
          def get_filename():
          # some logic


          Then you'll be able to instantiate your object:



          x = MyClass()
          x.get_filename()


          Does that answer your question?






          share|improve this answer























          • So I need to write a class to mock Email methods?

            – placplacboom
            Mar 7 at 1:16











          • I think what you actually intended to do is this: attchs = [msg for x in msg.get_payload() if msg.get_filename() is not None], that way you'll still have the msg objects, just filtered by the results of get_filename. I'm guessing that get_payload() returns a list, not an object.

            – rgk
            Mar 7 at 1:19












          • I got that. Let me try one thing

            – placplacboom
            Mar 7 at 1:21


















          0














          The way you've configured your mocks isn't quite right. The message_from_file() call needs to return a message, whereas you're returning a list - hence the error you're seeing.



          You should set up a mock message along with a mock attachment in order to satisfy the calls the code expects to make.



          For example:



          @patch("mail_extractor.process_email.email")
          @patch("builtins.open")
          def test_extract_attachments(open, email):
          # Configure the mock message and its attachment
          mock_message = Mock()
          mock_attachment = Mock()
          mock_attachment.get_filename.return_value = '1.xml'
          mock_message.get_payload.return_value = [mock_attachment]

          # Configure message_from_file to return the mock message
          email.message_from_file.return_value = mock_message

          result = process_email.extract_attachments('mock')
          assert len(result) == 1





          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%2f55034572%2fmock-email-payload-on-python%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









            0














            The notation you've described is specific to objects, and what you're trying to give it is a method. You'll need to define a class:



            class MyClass:
            def get_filename():
            # some logic


            Then you'll be able to instantiate your object:



            x = MyClass()
            x.get_filename()


            Does that answer your question?






            share|improve this answer























            • So I need to write a class to mock Email methods?

              – placplacboom
              Mar 7 at 1:16











            • I think what you actually intended to do is this: attchs = [msg for x in msg.get_payload() if msg.get_filename() is not None], that way you'll still have the msg objects, just filtered by the results of get_filename. I'm guessing that get_payload() returns a list, not an object.

              – rgk
              Mar 7 at 1:19












            • I got that. Let me try one thing

              – placplacboom
              Mar 7 at 1:21















            0














            The notation you've described is specific to objects, and what you're trying to give it is a method. You'll need to define a class:



            class MyClass:
            def get_filename():
            # some logic


            Then you'll be able to instantiate your object:



            x = MyClass()
            x.get_filename()


            Does that answer your question?






            share|improve this answer























            • So I need to write a class to mock Email methods?

              – placplacboom
              Mar 7 at 1:16











            • I think what you actually intended to do is this: attchs = [msg for x in msg.get_payload() if msg.get_filename() is not None], that way you'll still have the msg objects, just filtered by the results of get_filename. I'm guessing that get_payload() returns a list, not an object.

              – rgk
              Mar 7 at 1:19












            • I got that. Let me try one thing

              – placplacboom
              Mar 7 at 1:21













            0












            0








            0







            The notation you've described is specific to objects, and what you're trying to give it is a method. You'll need to define a class:



            class MyClass:
            def get_filename():
            # some logic


            Then you'll be able to instantiate your object:



            x = MyClass()
            x.get_filename()


            Does that answer your question?






            share|improve this answer













            The notation you've described is specific to objects, and what you're trying to give it is a method. You'll need to define a class:



            class MyClass:
            def get_filename():
            # some logic


            Then you'll be able to instantiate your object:



            x = MyClass()
            x.get_filename()


            Does that answer your question?







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 7 at 1:14









            rgkrgk

            395410




            395410












            • So I need to write a class to mock Email methods?

              – placplacboom
              Mar 7 at 1:16











            • I think what you actually intended to do is this: attchs = [msg for x in msg.get_payload() if msg.get_filename() is not None], that way you'll still have the msg objects, just filtered by the results of get_filename. I'm guessing that get_payload() returns a list, not an object.

              – rgk
              Mar 7 at 1:19












            • I got that. Let me try one thing

              – placplacboom
              Mar 7 at 1:21

















            • So I need to write a class to mock Email methods?

              – placplacboom
              Mar 7 at 1:16











            • I think what you actually intended to do is this: attchs = [msg for x in msg.get_payload() if msg.get_filename() is not None], that way you'll still have the msg objects, just filtered by the results of get_filename. I'm guessing that get_payload() returns a list, not an object.

              – rgk
              Mar 7 at 1:19












            • I got that. Let me try one thing

              – placplacboom
              Mar 7 at 1:21
















            So I need to write a class to mock Email methods?

            – placplacboom
            Mar 7 at 1:16





            So I need to write a class to mock Email methods?

            – placplacboom
            Mar 7 at 1:16













            I think what you actually intended to do is this: attchs = [msg for x in msg.get_payload() if msg.get_filename() is not None], that way you'll still have the msg objects, just filtered by the results of get_filename. I'm guessing that get_payload() returns a list, not an object.

            – rgk
            Mar 7 at 1:19






            I think what you actually intended to do is this: attchs = [msg for x in msg.get_payload() if msg.get_filename() is not None], that way you'll still have the msg objects, just filtered by the results of get_filename. I'm guessing that get_payload() returns a list, not an object.

            – rgk
            Mar 7 at 1:19














            I got that. Let me try one thing

            – placplacboom
            Mar 7 at 1:21





            I got that. Let me try one thing

            – placplacboom
            Mar 7 at 1:21













            0














            The way you've configured your mocks isn't quite right. The message_from_file() call needs to return a message, whereas you're returning a list - hence the error you're seeing.



            You should set up a mock message along with a mock attachment in order to satisfy the calls the code expects to make.



            For example:



            @patch("mail_extractor.process_email.email")
            @patch("builtins.open")
            def test_extract_attachments(open, email):
            # Configure the mock message and its attachment
            mock_message = Mock()
            mock_attachment = Mock()
            mock_attachment.get_filename.return_value = '1.xml'
            mock_message.get_payload.return_value = [mock_attachment]

            # Configure message_from_file to return the mock message
            email.message_from_file.return_value = mock_message

            result = process_email.extract_attachments('mock')
            assert len(result) == 1





            share|improve this answer



























              0














              The way you've configured your mocks isn't quite right. The message_from_file() call needs to return a message, whereas you're returning a list - hence the error you're seeing.



              You should set up a mock message along with a mock attachment in order to satisfy the calls the code expects to make.



              For example:



              @patch("mail_extractor.process_email.email")
              @patch("builtins.open")
              def test_extract_attachments(open, email):
              # Configure the mock message and its attachment
              mock_message = Mock()
              mock_attachment = Mock()
              mock_attachment.get_filename.return_value = '1.xml'
              mock_message.get_payload.return_value = [mock_attachment]

              # Configure message_from_file to return the mock message
              email.message_from_file.return_value = mock_message

              result = process_email.extract_attachments('mock')
              assert len(result) == 1





              share|improve this answer

























                0












                0








                0







                The way you've configured your mocks isn't quite right. The message_from_file() call needs to return a message, whereas you're returning a list - hence the error you're seeing.



                You should set up a mock message along with a mock attachment in order to satisfy the calls the code expects to make.



                For example:



                @patch("mail_extractor.process_email.email")
                @patch("builtins.open")
                def test_extract_attachments(open, email):
                # Configure the mock message and its attachment
                mock_message = Mock()
                mock_attachment = Mock()
                mock_attachment.get_filename.return_value = '1.xml'
                mock_message.get_payload.return_value = [mock_attachment]

                # Configure message_from_file to return the mock message
                email.message_from_file.return_value = mock_message

                result = process_email.extract_attachments('mock')
                assert len(result) == 1





                share|improve this answer













                The way you've configured your mocks isn't quite right. The message_from_file() call needs to return a message, whereas you're returning a list - hence the error you're seeing.



                You should set up a mock message along with a mock attachment in order to satisfy the calls the code expects to make.



                For example:



                @patch("mail_extractor.process_email.email")
                @patch("builtins.open")
                def test_extract_attachments(open, email):
                # Configure the mock message and its attachment
                mock_message = Mock()
                mock_attachment = Mock()
                mock_attachment.get_filename.return_value = '1.xml'
                mock_message.get_payload.return_value = [mock_attachment]

                # Configure message_from_file to return the mock message
                email.message_from_file.return_value = mock_message

                result = process_email.extract_attachments('mock')
                assert len(result) == 1






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 11 at 9:30









                Will KeelingWill Keeling

                12.2k22635




                12.2k22635



























                    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%2f55034572%2fmock-email-payload-on-python%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

                    Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                    Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                    Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved