Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

Connect to mysql when running Python unit tests using remote interpreter

I am starting a Flask project and I want to run unit tests in PyCharm using Docker remote interpreter, but I am not being able to connect to the mysql database container when running the tests. The application runs normally, so the database is reachable outside the container. In the past I managed to do that in PhpStorm, but the configurations in PyCharm are not the same and I am having some trouble setting everything up. I already managed to use the remote interpreter to run tests, but the only trouble is when I need to connect to the database.

I am getting the following error when trying to connect:

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (111 Connection refused)

So, the server is reachable, but for whatever reason it is not allowing to connect.

Here is the docker-compose.yml

version: "2"

networks:
    learning_flask:
      name: learning_flask
      driver: bridge

services:
  mysql:
    image: mysql:5.7
    container_name: mysql
    restart: unless-stopped
    tty: true
    ports:
      - "127.0.0.1:3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - ./db:/docker-entrypoint-initdb.d/:ro
    networks:
      - learning_flask

  app:
    build: ./app
    container_name: learning_flask_app
    ports:
      - "5000:5000"
    volumes:
      [ './app:/app' ]
    depends_on:
      - mysql
    networks:
      - learning_flask

and then the code I am trying to execute:

import unittest
import mysql.connector

class TestCase(unittest.TestCase):

    def test_something(self):
        config = {
            'user': 'root',
            'password': 'root',
            'host': 'localhost',
            'port': '3306'
        }
        connection = mysql.connector.connect(**config)


if __name__ == '__main__':
    unittest.main()

If I try to change the host on the connection config to mysql, I get the following error:

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'mysql:3306' (-2 Name or service not known)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...