python2.7 mysql mock,在Python中模拟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")

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)")

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

Is sqlite3 or MySQLdb suitable for creating quickly a database in memory?

How do I install MySQLdb within the Anaconda package?

Is there an example of a test database, created in the setUp? Is this even a good idea?

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

解决方案

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)

Check the documentation on native Python mocking library at:

https://docs.python.org/3/library/unittest.mock.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值