I am learning monogoDB, I am beginner but I am facing some errors. What is my coding error and tell me the solution for that?
this is post.py file
import uuid
from database import Database
import datetime
class Post (object):
def __init__(self,blog_id,title,content,author,date=datetime.datetime.utcnow(),id=None):
self.blog_id=blog_id
self.title=title
self.content=content
self.author=author
self.created_date=date
self.id=uuid.uuid4().hex if id is None else id
def save_to_mongo(self):
Database.insert(collection='students',data=self.json())
def json(self):
return {
'id':self.id,
'blog_id':self.blog_id,
'author':self.author,
'content':self.content,
'title':self.title,
'created_date':self.created_date
}
#staticmethod
def from_mongo(id):
return Database.find_one(collection='students',query={'id':id})
#staticmethod
def from_blog(id):
return [post for post in Database.find(collection='students',query={'blog_id':id})]
database.py file
import pymongo
class Database(object):
URI="mongodb//127.0.0.1:27017"
DATABASE=None
#staticmethod
def initialize():
client=pymongo.MongoClient(Database.URI)
Database.DATABASE=client['local']
#staticmethod
def insert(collection,data):
Database.DATABASE[collection].insert(data)
#staticmethod
def insert(collection,query):
return Database.DATABASE[collection].find(data)
#staticmethod
def insert(collection,query):
return Database.DATABASE[collection].find_one(data)
this is test.py file
from database import Database
from post import Post
Database.initialize()
post=Post(blog_id="123",title="Anoother great post",content="This is some
sample content",author="rahul")
post.save_to_mongo()
i got the following error during running test.py
[Running] python "d:\myprograms\python\test.py"
Traceback (most recent call last):
File "d:\myprograms\python\test.py", line 9, in <module>
post.save_to_mongo()
File "d:\myprograms\python\post.py", line 15, in save_to_mongo
Database.insert(collection='students',data=self.json())
TypeError: insert() got an unexpected keyword argument 'data'
Related
Why it happens? is this "binding behavior”?
using staticmethod in class body
>>> class Test:
#staticmethod
def test(msg="asd"):
print(msg)
>>> test = Test()
>>> test.test()
asd
but when I using it without, got error:
>>> #staticmethod
def test(msg=""):
print(msg)
>>> test
<staticmethod object at 0x10dde9be0>
>>> test()
Traceback (most recent call last):
File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec
exec(exp, global_vars, local_vars)
File "<input>", line 1, in <module>
TypeError: 'staticmethod' object is not callable
A static method is a method that is bound to a class but does not require the class instance to function.
For example, you may have a class built around a file type to retrieve raw data from a source file and pass it to a lexer, your constructor could have you pass in the raw file however you may want another function to open the file, validate it and retrieve the data. In this case, you could use a static function within the class as the function is related to the class but doesn't require the class to function (in this case it would return the actual class).
A code example:
class PythonFile:
def __init__(self, raw_data):
self._raw_data = raw_data
self._lexer = None
#staticmethod
def open(fp):
with open(fp, "r") as rFile:
data = rFile.read()
# validate, etc...
return PythonFile(data)
def lex(self):
self._lexer = PythonLex(self._raw_data)
return self._lexer.get_master_block_array()
# etc, etc...
python_file = PythonFile.open("some\\path.py")
print(python_file.lex())
ItzTheDodo.
Use a standalone function.
def test(msg=""):
print(msg)
I'm trying to subclass the Chrome WebDriver to include some initialization and cleanup code, but then Python complains that the created object is set to None:
import glob
import selenium
import subprocess
from selenium.webdriver.common.by import By
class WebDriver(selenium.webdriver.Chrome):
def __init__(self, url, *args, **kwargs):
super().__init__(*args, **kwargs)
self.url = url
def __enter__(self):
self.get(self.url)
self.implicitly_wait(15)
def __exit__(self, type, value, traceback):
self.quit()
for path in glob.glob('/tmp/.org.chromium.Chromium.*'):
subprocess.run(['rm', '-rf', path], check=True)
with WebDriver('https://google.com') as driver:
driver.find_element(By.ID, 'lst-ib').send_keys('Search')
Running the code with Python 3:
$ python3 test.py
Traceback (most recent call last):
File "test.py", line 43, in <module>
driver.find_element(By.ID, 'lst-ib').send_keys('Search')
AttributeError: 'NoneType' object has no attribute 'find_element'
Your __enter__() magic method should return self for the driver variable to be pointed to the instance of the WebDriver class:
def __enter__(self):
self.get(self.url)
self.implicitly_wait(15)
return self
To get more information about why and how this works, please see:
Understanding Python's "with" statement
Explaining Python's '__enter__' and '__exit__'
Here i did the python class for connecting mongo and get the data from mongo database and process it i did the unit test cases for this i got following error
NameError: global name 'client' is not defined
python class :
from pymongo.errors import ConnectionFailure, AutoReconnect
import pymongo
from pymongo import MongoClient
class ConnectionError(Exception):
pass
class ChkMongo:
item_list=[]
dict1={}
def makeMongocon(self):
global client
try :
client = MongoClient("localhost", 27017)
except AutoReconnect, e:
raise ConnectionFailure(str(e))
def findRecords(self):
self.db = client.serv
for item in self.db.serv.find():
self.item_list.insert(0,item)
return self.item_list
if __name__ == '__main__':
c=ChkMongo()
c.makeMongocon()
print(c.findRecords())
my unit test case
from pymongo.errors import ConnectionFailure
import unittest;
from app.ChkMongo import *
class TestChkMongo(unittest.TestCase):
def setUp(self):
self.c=ChkMongo()
def test_makeMongocon(self):
self.assertRaises(ConnectionFailure,self.c.makeMongocon)
def test_findRecords(self):
print(self.c.findRecords())
self.assertDictContainsSubset({'name':'matthew'},self.c.findRecords())
def test_calculate_charge_with_tax(self):
self.assertAlmostEqual(290,self.c.calculate_charge_with_tax('matthew'))
if __name__ == '__main__':
unittest.main()
i got following error when run the test cases but run the python script that will work fine
Error:
Traceback (most recent call last):
File "/test/test_chkMongo.py", line 16, in test_findRecords
print(self.c.findRecords())
File "n/app/ChkMongo.py", line 29, in findRecords
self.db = client.serventer code here
NameError: global name 'client' is not defined
For me it happens when running my test with Python 3.6.x and Python 2.x.
Some exception names are not available in Python 2.x.
For example with ConnectionError:
in Python 2.x, using python interpreter, I get a NameError because it does not recognize it.
>>> raise ConnectionError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ConnectionError' is not defined
in Python 3.6.x, using python3 interpreter, I get the right ConnectionError
>>> raise ConnectionError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ConnectionError
It can be tricky when working with multiple versions of Python or different venv. Hope it helps with the debugging.
I have no idea why you are using a global variable here for client. That should be an instance variable of the ChkMongo class.
class ChkMongo:
def __init__(self):
self.item_list = []
self.dict1 = {}
def makeMongocon(self):
try:
self.client = MongoClient("localhost", 27017)
except AutoReconnect, e:
raise ConnectionFailure(str(e))
def findRecords(self):
self.db = self.client.serv
for item in self.db.serv.find():
self.item_list.insert(0,item)
return self.item_list
Note that item_list and dict1 also need to be instance properties, not class ones.
Actually I don't see what I am doing wrong here but I guess it is a very simple and basic problem:
Module 1 called Widget17_Sorter.py:
class Widget17_Sorter(object):
def get_data_from_database(self, database_name, user, password, host ):
...do stuff here...
Module 2 called Test_Widget17_Sorter.py (actually a unit test)
import Widget17_Sorter
class Test(unittest.TestCase):
...do some other stuff here...
def test_get_data_from_database(self):
sorter = Widget17_Sorter.Widget17_Sorter()
raw_data = sorter.get_data_from_database( self.database_name,
self.user, self.password, self.host )
When executing the test I get the following error message:
ERROR: test_get_data_from_database (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "TestWidget17_Sorter.py", line 50, in test_get_data_from_database
raw_data = sorter.get_data_from_database( self.database_name,
AttributeError: 'Widget17_Sorter' object has no attribute 'get_data_from_database'
Why?
Try importing this way:
from Widget17_Sorter import Widget17_Sorter
...
my_widget = Widget17_Sorter(...)
my_widget.get_data_from_database(...)
...and put both scripts in the same folder...
I am not sure why the following code is not working. I am using the Mock framework. Anyone could explain it to me?
The error I get is this:
$ python test_mock.py
Calls the mock object method. not a real one. ... ERROR
======================================================================
ERROR: Calls the mock object method. not a real one.
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_mock.py", line 37, in test_is_method_called
self.sut.do_something()
File "test_mock.py", line 21, in do_something
self.__obj.method()
File "build/bdist.linux-i686/egg/mock.py", line 365, in __getattr__
self._children[name] = self._get_child_mock(parent=self, name=name, wraps=wraps)
File "build/bdist.linux-i686/egg/mock.py", line 458, in _get_child_mock
return klass(**kw)
File "build/bdist.linux-i686/egg/mock.py", line 282, in __init__
self.reset_mock()
File "build/bdist.linux-i686/egg/mock.py", line 303, in reset_mock
self._return_value.reset_mock()
AttributeError: 'SentinelObject' object has no attribute 'reset_mock'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
The code is:
import unittest
import mock
class Fubar ():
def __init__(self):
pass
def method (self):
print "I am a Stup!d Monkey!"
class Monkey ():
def __init__(self, obj):
self.__obj = obj
def do_something (self):
if not isinstance(self.__obj, Fubar):
raise RuntimeError
self.__obj.method()
class TestMoneky (unittest.TestCase):
def setUp(self):
self.mock_obj = mock.Mock(name="Mock object", spec=["method"])
self.sut = Monkey(self.mock_obj)
def tearDown(self):
pass
def test_is_method_called (self):
"""Calls the mock object method. not a real one."""
with mock.patch("__builtin__.isinstance") as mock_inst:
mock_inst.return_value = True
self.sut.do_something()
self.assertTrue(self.mock_obj.method.called)
def main ():
"""Simple runner."""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestMoneky))
unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
main()
The problems (sadly) is trivial. I am patching isinstance() to always return True. So, somewhere in the bowels of the module, something is asking whether my mock object is a Sentinel and (since I am overriding the return value), True is returned. Thus the wrong internal behaviour is exhibited.
The solution is therefore to not patch isinstance() but instead provide the mock with a spec that matches the class it is supposed to match:
def setUp(self):
self.mock_obj = mock.Mock(name="Mock object", spec=Fubar)
self.sut = Monkey(self.mock_obj)
def test_is_method_called (self):
"""Calls the mock object method. not a real one."""
self.sut.do_something()
self.assertTrue(self.mock_obj.method.called)
Can anyone see a way to do this without coupling the mock to Fubar???...