Solving alternative for $this->getMock and other php unit test class methods into Python's unittest.TestCase

89
August 06, 2019, at 09:40 AM

I am porting a library written in PHP, so far I managed to port the whole source code, but I stucked at the unit tests.

The following methods found through out the PHP example:

  • $this->getMockBuilder

  • $this->getMock

  • disableOriginalConstructor

and this code call:

->expects($this->once())
->method('SOME class method')
->with('')
->will($this->returnValue('encoded'));

can't think of any alternative in Python's TestCase. Mostly for the "$this->returnValue" thing.

Here you can see the excerpt of the original PHP code, and rewritten Python version which is incomplete. If there isn't close alternative can someone explain me the meaning of the test.

RequestBuilderTest.php:

    <?php
    /**
     * Test for class WebToPay_RequestBuilder
     */
    class WebToPay_RequestBuilderTest extends PHPUnit_Framework_TestCase {
        /**
         * @var WebToPay_UrlBuilder
         */
        protected $urlBuilder;
        /**
         * @var WebToPay_Util
         */
        protected $util;
        /**
         * @var WebToPay_RequestBuilder
         */
        protected $builder;
        /**
         * Sets up this test
         */
        public function setUp() {
            $this->util = $this->getMock('WebToPay_Util', array('encodeSafeUrlBase64'));
            $this->urlBuilder = $this->getMockBuilder('WebToPay_UrlBuilder')
                ->disableOriginalConstructor()
                ->getMock();
            $this->builder = new WebToPay_RequestBuilder(123, 'secret', $this->util, $this->urlBuilder);
        }
        /**
         * Test build request when no orderid is passed
         *
         * @expectedException WebToPay_Exception_Validation
         */
        public function testBuildRequestWithNoOrderId() {
            $this->builder->buildRequest(array(
                'accepturl' => 'http://local.test/',
                'cancelurl' => 'http://local.test/',
                'callbackurl' => 'http://local.test/',
            ));
        }
        /**
         * Test build request when invalid currency is passed
         *
         * @expectedException WebToPay_Exception_Validation
         */
        public function testBuildRequestWithInvalidCurrency() {
            $this->builder->buildRequest(array(
                'orderid' => 123,
                'accepturl' => 'http://local.test/',
                'cancelurl' => 'http://local.test/',
                'callbackurl' => 'http://local.test/',
                'currency' => 'litai',
            ));
        }
        /**
         * Tests buildRequest method
         */
        public function testBuildRequest() {
            $this->util
                ->expects($this->once())
                ->method('encodeSafeUrlBase64')
                ->with(
                    'orderid=123&accepturl=http%3A%2F%2Flocal.test%2F&cancelurl=http%3A%2F%2Flocal.test%2F'
                        . '&callbackurl=http%3A%2F%2Flocal.test%2F&amount=100&some-other-parameter=abc'
                        . '&version=1.6&projectid=123'
                )
                ->will($this->returnValue('encoded'));
            $this->assertEquals(
                array('data' => 'encoded', 'sign' => md5('encodedsecret')),
                $this->builder->buildRequest(array(
                    'orderid' => 123,
                    'accepturl' => 'http://local.test/',
                    'cancelurl' => 'http://local.test/',
                    'callbackurl' => 'http://local.test/',
                    'amount' => 100,
                    'some-other-parameter' => 'abc',
                ))
            );
        }
        /**
         * Tests buildRepeatRequest method
         */
        public function testBuildRepeatRequest() {
            $this->util
                ->expects($this->once())
                ->method('encodeSafeUrlBase64')
                ->with('orderid=123&version=1.6&projectid=123&repeat_request=1')
                ->will($this->returnValue('encoded'));
            $this->assertEquals(
                array('data' => 'encoded', 'sign' => md5('encodedsecret')),
                $this->builder->buildRepeatRequest(123)
            );
        }
    }

request_builder_test.py:


    import hashlib
    import unittest
    from typing import Union
    from mock import patch

    class WebToPay_RequestBuilderTest(unittest.TestCase):
        """
        Test for class WebToPay_UrlBuilder
        """
        urlBuilder: WebToPay_UrlBuilder
        util: WebToPay_Util
        builder: WebToPay_RequestBuilder
        def setUp(self) -> None:
            super().setUp()
            self.util = WebToPay_Util()
            with patch.object(WebToPay_UrlBuilder, '__init__', lambda *args: None) as urlBuilder:
                self.urlBuilder = WebToPay_UrlBuilder()
            self.builder = WebToPay_RequestBuilder(
                projectId=123,
                projectPassword='secret',
                util=self.util,
                urlBuilder=self.urlBuilder
            )

       def testBuildRequest(self):
            """
            Tests buildRequest method
            """
            txt = 'orderid=123&accepturl=http%3A%2F%2Flocal.test%2F&cancelurl=http%3A%2F%2Flocal.test%2F' \
                  + '&callbackurl=http%3A%2F%2Flocal.test%2F&amount=100&some-other-parameter=abc' \
                  + '&version=1.6&projectid=123'
            text_res = self.util.encodeSafeUrlBase64(text=txt)
            a = 0
            self.assertEqual(
                {
                    'data': 'encoded', 'sign': hashlib.md5('encodedsecret'.encode()).hexdigest(),
                },
                self.builder.buildRequest({
                    'orderid': '123',
                    'accepturl': 'http://local.test/',
                    'cancelurl': 'http://local.test/',
                    'callbackurl': 'http://local.test/',
                    'amount': 100,
                    'some-other-parameter': 'abc',
                })
            )

I mostly was using the site http://www.php2python.com/wiki/ to aid me with the porting, if we can find together a solution, then we can enrich their database with the unit testing methods :).

READ ALSO
Form auto calculate answer to php

Form auto calculate answer to php

I have an autocalc running on a form and the total is shown through a div IDI need to be able to somehow render the div ID answer into a php form mailer

57
RuntimeError: dictionary changed size during iteration while deleting the key from the dictionary

RuntimeError: dictionary changed size during iteration while deleting the key from the dictionary

I am trying to delete a key from the dictionaryWhile doing I got RuntimeError: dictionary changed size during iteration

121
How to get index position from a string in python without repetitive results

How to get index position from a string in python without repetitive results

While in a for-loop of a string, I want to get the index position of that specific letter in that string, but if there are the same letters in that word, it doesn't work

79
How to fix unsafe implementation of HostnameVerifier

How to fix unsafe implementation of HostnameVerifier

I have received this warning from Playstore because my code bellow is accepting all hosts

79