Python Nosetest - How to mock MySQLdb - python

I'm trying to mock the MySQLdb lib from my project but I don't really understood how to do it:
Here's my test code:
import unittest
from mock import MagicMock
from core.distrib.main.CentralDistDraw import CentralDistDraw
from connector.mysql import MySQL
class CentralDistDraw(unittest.TestCase):
def test_hello(self):
draw = CentralDistDraw()
msql = MySQL()
msql.getConnection = MagicMock()
Here's my class:
from datetime import datetime
import logging
from core.distrib.config.PromoConstants import PromoConstants
from dateutil.parser import parse
from google.appengine.api import memcache
from connector.mysql import MySQL
from core.distrib.ndb.userpromo import UserPromo
from core.distrib.ndb.drawinfo import DrawInfo
import traceback
class CentralDistDraw(object):
def getNextNumber(self, idUser, amountDefault=1, amountSpecial=1):
numbersDelivered = []
# DB CONTROLL....
db = MySQL().getConnection()
db.autocommit(False)
currentUser = None
Error thrown:
ERROR: Failure: ImportError (/home/dyego/Documents/code-stuff/mod/pdbcontest2/src/lib/_mysql.so: invalid ELF header)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/nose-1.3.7-py2.7.egg/nose/loader.py", line 418, in loadTestsFromName
addr.filename, addr.module)
File "/usr/local/lib/python2.7/dist-packages/nose-1.3.7-py2.7.egg/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/usr/local/lib/python2.7/dist-packages/nose-1.3.7-py2.7.egg/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/home/dyego/Documents/code-stuff/mod/pdbcontest2/src/tests/core/test_central_dist_draw.py", line 4, in <module>
from core.distrib.main.CentralDistDraw import CentralDistDraw
File "/home/dyego/Documents/code-stuff/mod/pdbcontest2/src/core/distrib/main/CentralDistDraw.py", line 11, in <module>
from connector.mysql import MySQL
File "/home/dyego/Documents/code-stuff/mod/pdbcontest2/src/connector/mysql.py", line 8, in <module>
import MySQLdb
File "/usr/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 19, in <module>
import _mysql
ImportError: /home/dyego/Documents/code-stuff/mod/pdbcontest2/src/lib/_mysql.so: invalid ELF header
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
Anyone knows the correct way to go when comes to testing third party libraries?
Thanks!

Related

Getting multiple error while using flask-ask and ngrok with ROS

I'm trying to use flask-ask library and develope a skill that can make me able to control a robot in ROS with alexa vocal assistant. Python code named "alexa_interface.py" is here.
The skill id number is substituted with my skill id number.
While launching this command
python3 alexa_interface.py
I am getting the following code error.
Tried to install dependencies with pip but getting:
AttributeError: module 'lib' has no attribute 'ERR_load_RAND_strings'
Also notice that I am getting this error everytime I use pip to install something. Is pip broken? How can I adjust this?
Thank you.
#! /usr/bin/env python3
from flask import Flask
from ask_sdk_core.skill_builder import SkillBuilder
from flask_ask_sdk.skill_adapter import SkillAdapter
from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.utils import is_request_type, is_intent_name
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_model import Response
from ask_sdk_model.ui import SimpleCard
app = Flask(__name__)
class LaunchRequestHandler(AbstractRequestHandler):
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return is_request_type("LaunchRequest")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
speech_text = "Ciao, come posso aiutarti?"
handler_input.response_builder.speak(speech_text).set_card(
SimpleCard("Hello World", speech_text)).set_should_end_session(
False)
return handler_input.response_builder.response`
skill_builder = SkillBuilder()
# Register your intent handlers to the skill_builder object
skill_builder.add_request_handler(LaunchRequestHandler())
skill_adapter = SkillAdapter(
skill=skill_builder.create(), skill_id="my-skill-id", app=app)
skill_adapter.register(app=app, route="/")
if __name__=='__main__':
app.run()
```
```
Traceback (most recent call last):
File "alexa_interface.py", line 2, in <module>
from flask import Flask
File "/home/toti/.local/lib/python3.8/site-packages/flask/__init__.py", line 14, in <module>
from jinja2 import escape
ImportError: cannot import name 'escape' from 'jinja2' (/home/toti/.local/lib/python3.8/site-packages/jinja2/__init__.py)
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 72, in apport_excepthook
from apport.fileutils import likely_packaged, get_recent_crashes
File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
from apport.report import Report
File "/usr/lib/python3/dist-packages/apport/report.py", line 32, in <module>
import apport.fileutils
File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 12, in <module>
import os, glob, subprocess, os.path, time, pwd, sys, requests_unixsocket
File "/usr/lib/python3/dist-packages/requests_unixsocket/__init__.py", line 1, in <module>
import requests
File "/home/toti/.local/lib/python3.8/site-packages/requests/__init__.py", line 52, in <module>
from .packages.urllib3.contrib import pyopenssl
File "/home/toti/.local/lib/python3.8/site-packages/requests/packages/urllib3/contrib/pyopenssl.py", line 46, in <module>
import OpenSSL.SSL
File "/home/toti/.local/lib/python3.8/site-packages/OpenSSL/__init__.py", line 8, in <module>
from OpenSSL import rand, crypto, SSL
File "/home/toti/.local/lib/python3.8/site-packages/OpenSSL/rand.py", line 213, in <module>
_lib.ERR_load_RAND_strings()
AttributeError: module 'lib' has no attribute 'ERR_load_RAND_strings'
Original exception was:
Traceback (most recent call last):
File "alexa_interface.py", line 2, in <module>
from flask import Flask
File "/home/toti/.local/lib/python3.8/site-packages/flask/__init__.py", line 14, in <module>
from jinja2 import escape
ImportError: cannot import name 'escape' from 'jinja2' (/home/toti/.local/lib/python3.8/site-packages/jinja2/__init__.py)
```

Python request.py syntax error

I am new to Python 3.4.5 which I am learning online by watching videos with some good knowledge of C. I am trying to download an image via Python which I am unable to do because of this error.
Code:
import random
import urllib.request
def img(url):
full='name'+'.jpeg'
urllib.request.urlretrieve(url,full)
img("http://lorempixel.com/400/200")
Error:
Traceback (most recent call last):
File "image.py", line 2, in <module>
import urllib.request
File "/home/yuvi/pyth/urllib/request.py", line 88, in <module>
import http.client
File "/usr/local/lib/python3.4/http/client.py", line 69, in <module>
import email.parser
File "/usr/local/lib/python3.4/email/parser.py", line 12, in <module>
from email.feedparser import FeedParser, BytesFeedParser
File "/usr/local/lib/python3.4/email/feedparser.py", line 27, in <module>
from email import message
File "/usr/local/lib/python3.4/email/message.py", line 16, in <module>
from email import utils
File "/usr/local/lib/python3.4/email/utils.py", line 31, in <module>
import urllib.parse
File "/home/yuvi/pyth/urllib/parse.py", line 239, in <module>
_DefragResultBase.url.__doc__ = """The URL with no fragment identifier."""
AttributeError: readonly attribute
Try:
def img(url): full='name'+'.jpeg';urllib.urlretrieve(url,full)
urllib.request does not exist in Python 2.x, which seems to be your case
so don't try to import that in second line of your code
plus you made a typo (forgot semicolon) which works as a statement separator while writing inline function statements.
Similar to:
def img(url):
full='name'+'.jpeg'
urllib.urlretrieve(url,full)

Django Test unittest.loader.ModuleImportFailure

I can't import my models in my tests directory, this is my error :
======================================================================
ERROR: tests.test_views (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.test_views
Traceback (most recent call last):
File "C:\Python27\lib\unittest\loader.py", line 254, in _find_tests
module = self._get_module_from_name(name)
File "C:\Python27\lib\unittest\loader.py", line 232, in _get_module_from_name
__import__(name)
File "c:\wamp\www\km0\tests\test_views.py", line 3, in <module>
from .models import Entreprise
File "c:\wamp\www\km0\tests\models.py", line 6, in <module>
class Entreprise(models.Model):
File "C:\Python27\lib\site-packages\django-1.9.5-py2.7.egg\django\db\models\ba
se.py", line 102, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class tests.models.Entreprise doesn't declare an explicit ap
p_label and isn't in an application in INSTALLED_APPS.
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
Preserving test database for alias 'default' ('test_km0')...
I did some research and couldn't find an answer ...
test_views.py :
from django.test import TestCase
import unittest
from .models import Entreprise
class Km0ViewsTestCase(TestCase):
def test_cart(self):
resp = self.client.get('/fr/cart/')
self.assertEqual(resp.status_code, 200)
resp = self.client.get('/en/cart/')
self.assertEqual(resp.status_code, 200)
resp = self.client.get('/de/cart/')
self.assertEqual(resp.status_code, 200)
My directory :
my directory
Thanks in advance for your help !
You shouldn't normally need a models.py in your tests directory.
If you want to import your Entreprise model from the front app, then change your import from
from .models import Entreprise
to
from front.models import Entreprise

Python import statement throws exception

I have some code that looks like this
try:
import calvin.reasoning.rule_list
except:
print "rule_list exception"
And I have commented out every import statement in rule_list.py, so it looks like this
#import quantities
#import rules
#from conclusions import Conclusion
#from conclusions import Data
#from confidence import Validity
If I delete the contents of rule_list my program runs, but why would python throw an exception if there is not a circular import?
Here is the traceback
Traceback (most recent call last):
File "/home/paul/projects/branchCalvin/Calvin/src/cscience/components/c_calibration.py", line 18, in <module>
import calvin.reasoning.rule_list
File "/home/paul/projects/branchCalvin/Calvin/src/calvin/reasoning/rule_list.py", line 37, in <module>
import rules
File "/home/paul/projects/branchCalvin/Calvin/src/calvin/reasoning/rules.py", line 32, in <module>
import engine
File "/home/paul/projects/branchCalvin/Calvin/src/calvin/reasoning/engine.py", line 33, in <module>
import conclusions
File "/home/paul/projects/branchCalvin/Calvin/src/calvin/reasoning/conclusions.py", line 31, in <module>
import samples
File "/home/paul/projects/branchCalvin/Calvin/src/calvin/reasoning/samples.py", line 30, in <module>
from cscience import datastore
ImportError: cannot import name datastore
problem importing module components.c_calibration
(<type 'exceptions.ImportError'>, ImportError('cannot import name datastore',), <traceback object at 0x9ebc554>)

Python: avoiding conflict of NumPy's unittest.py with local unittest.py

Has anyone else encountered the situation where they have written unit tests for their code into a file named unittest.py, and found it to conflict with NumPy's unittest.py module? In other words, if I write this to unittest.py in a local directory:
if __name__ == "__main__":
print "pre-import"
#import numpy
print "post-import"
Then (no surprises here):
% python unittest.py
pre-import
post-import
But if I do:
if __name__ == "__main__":
print "pre-import"
import numpy
print "post-import"
I get:
% python unittest.py
pre-import
Traceback (most recent call last):
File "unittest.py", line 3, in <module>
import numpy
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/__init__.py", line 137, in <module>
import add_newdocs
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/add_newdocs.py", line 9, in <module>
from numpy.lib import add_newdoc
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/lib/__init__.py", line 4, in <module>
from type_check import *
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/lib/type_check.py", line 8, in <module>
import numpy.core.numeric as _nx
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/core/__init__.py", line 40, in <module>
from numpy.testing import Tester
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/testing/__init__.py", line 8, in <module>
from unittest import TestCase
ImportError: cannot import name TestCase
Subsequently, iPython fails to load:
% ipython
WARNING: IPython History requires SQLite, your history will not be saved
Traceback (most recent call last):
File "/home/jbbrown/local_bin/python/bin/ipython", line 7, in <module>
launch_new_instance()
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/frontend/terminal/ipapp.py", line 402, in launch_new_instance
app.initialize()
File "<string>", line 2, in initialize
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/config/application.py", line 84, in catch_config_error
return method(app, *args, **kwargs)
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/frontend/terminal/ipapp.py", line 312, in initialize
self.init_shell()
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/frontend/terminal/ipapp.py", line 332, in init_shell
ipython_dir=self.ipython_dir)
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/config/configurable.py", line 318, in instance
inst = cls(*args, **kwargs)
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/frontend/terminal/interactiveshell.py", line 183, in __init__
user_module=user_module, custom_exceptions=custom_exceptions
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 478, in __init__
self.init_reload_doctest()
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 662, in init_reload_doctest
doctest_reload()
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/IPython/utils/doctestreload.py", line 72, in doctest_reload
import doctest
File "/home/jbbrown/local_bin/python/lib/python2.7/doctest.py", line 2118, in <module>
class DocTestCase(unittest.TestCase):
AttributeError: 'module' object has no attribute 'TestCase'
If you suspect this is an IPython bug, please report it at:
https://github.com/ipython/ipython/issues
or send an email to the mailing list at ipython-dev#scipy.org
You can print a more detailed traceback right now with "%tb", or use "%debug"
to interactively debug it.
Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
c.Application.verbose_crash=True
Interestingly, if I move the import statement outside of the "if __name__" suite, e.g.,
print "pre-import"
import numpy
print "post-import"
if __name__ == "__main__":
pass
I get:
% python unittest.py
pre-import
pre-import
post-import
Traceback (most recent call last):
File "unittest.py", line 2, in <module>
import numpy
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/__init__.py", line 137, in <module>
import add_newdocs
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/add_newdocs.py", line 9, in <module>
from numpy.lib import add_newdoc
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/lib/__init__.py", line 4, in <module>
from type_check import *
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/lib/type_check.py", line 8, in <module>
import numpy.core.numeric as _nx
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/core/__init__.py", line 40, in <module>
from numpy.testing import Tester
File "/home/jbbrown/local_bin/python/lib/python2.7/site-packages/numpy/testing/__init__.py", line 8, in <module>
from unittest import TestCase
ImportError: cannot import name TestCase
Of course it is trivial to change the name of the file containing my unit tests and avoid this, but I wonder if anyone else encountered this and thought of an elegant workaround that doesn't include renaming their unit test file?
You can switch to absolute imports by default on Python versions newer than 2.7:
from __future__ import absolute_import
if __name__ == "__main__":
print "pre-import"
import numpy
print "post-import"

Categories