1

Similar to How do I mock part of a python constructor just for testing? but explicitly trying to get pymysqlpool.ConnectionPool to work/

class DbTests(TestCase):
    @mock.patch('pymysqlpool.ConnectionPool', autospec=True)
    @mock.patch.dict(
        os.environ,
        {
            "DATASOURCES_0_SERVERID": "server1",
            "DATASOURCES_0_HOST": "non-existent",
            "DATASOURCES_0_PORT": "3307",
            "DATASOURCES_0_DATABASE": "lj_ca1",
            "DATASOURCES_0_USERNAME": "sampleuser",
            "DATASOURCES_0_PASSWORD": "password1",
            "DATASOURCES_0_TIMEZONE": "Americas/Toronto",
        },
    )    
    def test_load(self, connection_pool_mock: mock.Mock):
        ConnectionPool(
            size=2, maxsize=3, pre_create_num=2, host=os.environ["DATASOURCES_0_HOST"]
        )

I'm expecting the code to simply work, but I am getting

pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'non-existent' ([Errno 11001] getaddrinfo failed)")

Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265

1 Answers1

1

I suppose that in your test file you have the following import:

from pymysqlpool import ConnectionPool

This defines the name ConnectionPool in the test module, but your instruction patch('pymysqlpool.ConnectionPool') substitutes the object points by the name pymysqlpool.ConnectionPool so it operates on an other name.

The import in your test code must change to:

import pymysqlpool

So your test code becomes:

import pymysqlpool
from unittest import TestCase, mock

class DbTests(TestCase):
    @mock.patch('pymysqlpool.ConnectionPool', autospec=True)
    @mock.patch.dict(
        os.environ,
        {
            "DATASOURCES_0_SERVERID": "server1",
            "DATASOURCES_0_HOST": "non-existent",
            "DATASOURCES_0_PORT": "3307",
            "DATASOURCES_0_DATABASE": "lj_ca1",
            "DATASOURCES_0_USERNAME": "sampleuser",
            "DATASOURCES_0_PASSWORD": "password1",
            "DATASOURCES_0_TIMEZONE": "Americas/Toronto",
        },
    )    
    def test_load(self, connection_pool_mock: mock.Mock):
        # Note here I have changed the called to ConnectionPool
        pymysqlpool.ConnectionPool(
            size=2, maxsize=3, pre_create_num=2, host=os.environ["DATASOURCES_0_HOST"]
        )

Note that in the test_load() code I have also changed the called to ConnectionPool adding the name of the module pymysqlpool.


Useful link about the same topic
This post is an other example of the use of patch().

frankfalse
  • 1,553
  • 1
  • 4
  • 17