在Python中模拟MySQL数据库 [英] Mock a MySQL database in Python

查看:411
本文介绍了在Python中模拟MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Anaconda发行版中的Python 3.4.在此发行版中,我发现pymysql库可连接到位于另一台计算机上的现有MySQL数据库.

I use Python 3.4 from the Anaconda distribution. Within this distribution, I found the pymysql library to connect to an existing MySQL database, which is located on another computer.

import pymysql
config = {
      'user': 'my_user',
      'passwd': 'my_passwd',
      'host': 'my_host',
      'port': my_port
    }

    try:
        cnx = pymysql.connect(**config)
    except pymysql.err.OperationalError : 
        sys.exit("Invalid Input: Wrong username/database or password")

我现在想为我的应用程序编写测试代码,在其中我想在每个测试用例的setUp处(最好是在内存中)创建一个非常小的数据库.但是,当我用pymysql突然尝试时,它无法建立连接.

I now want to write test code for my application, in which I want to create a very small database at the setUp of every test case, preferably in memory. However, when I try this out of the blue with pymysql, it cannot make a connection.

def setUp(self):
    config = {
      'user': 'test_user',
      'passwd': 'test_passwd',
      'host': 'localhost'
    }
    cnx = pymysql.connect(**config)

pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 61] Connection refused)")

我一直在四处搜寻,发现了有关SQLiteMySQLdb的一些信息.我有以下问题:

I have been googling around, and found some things about SQLite and MySQLdb. I have the following questions:

  1. sqlite3MySQLdb是否适合在内存中快速创建数据库?
  2. 如何在Anaconda软件包中安装MySQLdb?
  3. 是否有在setUp中创建的测试数据库的示例?这是个好主意吗?
  1. Is sqlite3 or MySQLdb suitable for creating quickly a database in memory?
  2. How do I install MySQLdb within the Anaconda package?
  3. Is there an example of a test database, created in the setUp? Is this even a good idea?

我的计算机上没有本地运行的MySQL服务器.

I do not have a MySQL server running locally on my computer.

推荐答案

pymysql,MySQLdb和sqlite都希望一个真实的数据库也可以连接. 如果只想测试代码,则应在要测试的模块上模拟pymysql模块,并相应地使用它 (在您的测试代码中:您可以设置模拟对象以将硬编码的结果返回到预定义的SQL语句)

Both pymysql, MySQLdb, and sqlite will want a real database to connect too. If you want just to test your code, you should just mock the pymysql module on the module you want to test, and use it accordingly (in your test code: you can setup the mock object to return hardcoded results to predefined SQL statements)

在以下位置查看有关本机Python模拟库的文档: https://docs.python.org/3/library/unittest.mock.html

Check the documentation on native Python mocking library at: https://docs.python.org/3/library/unittest.mock.html

或者,对于Python 2: https://pypi.python.org/pypi/mock

Or, for Python 2: https://pypi.python.org/pypi/mock

这篇关于在Python中模拟MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆