What is a mixin, and why are they useful?

后端 未结 16 2126
無奈伤痛
無奈伤痛 2020-11-22 00:18

In \"Programming Python\", Mark Lutz mentions \"mixins\". I\'m from a C/C++/C# background and I have not heard the term before. What is a mixin?

Reading between the

16条回答
  •  孤街浪徒
    2020-11-22 01:19

    I just used a python mixin to implement unit testing for python milters. Normally, a milter talks to an MTA, making unit testing difficult. The test mixin overrides methods that talk to the MTA, and create a simulated environment driven by test cases instead.

    So, you take an unmodified milter application, like spfmilter, and mixin TestBase, like this:

    class TestMilter(TestBase,spfmilter.spfMilter):
      def __init__(self):
        TestBase.__init__(self)
        spfmilter.config = spfmilter.Config()
        spfmilter.config.access_file = 'test/access.db'
        spfmilter.spfMilter.__init__(self)
    

    Then, use TestMilter in the test cases for the milter application:

    def testPass(self):
      milter = TestMilter()
      rc = milter.connect('mail.example.com',ip='192.0.2.1')
      self.assertEqual(rc,Milter.CONTINUE)
      rc = milter.feedMsg('test1',sender='good@example.com')
      self.assertEqual(rc,Milter.CONTINUE)
      milter.close()
    

    http://pymilter.cvs.sourceforge.net/viewvc/pymilter/pymilter/Milter/test.py?revision=1.6&view=markup

提交回复
热议问题