Я пытаюсь протестировать свой код AnimalShelter.py в Jupyter Notebook, но постоянно получаю сообщение об ошибке, что атрибута «создать» нет. Я что-то пропустил? Я определил это в коде, но независимо от того, что я меняю, он все равно говорит, что его там нет.
Код AnimalShelter.py:
import pymongo
from pymongo import MongoClient
from bson.objectid import ObjectId
class AnimalShelter(object):
""" CRUD operations for Animal collection in MongoDB """
def __init__(self, username, password):
#Initializing the MongoClient. This helps to access the MongoDB databases and collections.
self.client = MongoClient('mongodb://%s:%s@localhost:45344' % (username, password))
#where xxxx is your unique port number
self.database = self.client['AAC']
#Complete this create method to implement the C in CRUD.
def create(self, data):
if data is not None:
insert = self.database.animals.insert(data) #data should be dictionary
else:
raise Exception("Nothing to save, because data parameter is empty")
#Create method to implement the R in CRUD.
def read(self, searchData):
if searchData:
data = self.database.animals.find(searchData, {"_id": False})
else:
data = self.database.animals.find({}, {"_id": False})
return data
#Create method to implement U in CRUD.
def update(self, searchData, updateData):
if searchData is not None:
result = self.database.animals.update_many(searchData, {"$set": updateData})
else:
return "{}"
return result.raw_result
#Create method to implement D in CRUD.
def delete(self, deleteData):
if deleteData is not None:
result = self.database.animals.delete_many(deleteData)
else:
return "{}"
return result.raw_result
Тестовый код, который я пытаюсь использовать, чтобы убедиться, что CRUD работает правильно:
from AnimalShelter import AnimalShelter
data = {}
query = {}
test_class = AnimalShelter()
#test each function in the AnimalShelter class
response = test_class.create(data)
assert response
response = test_class.read(data)
assert response
response = test_class.update(data)
assert response
response = test_class.delete(data)
assert response
Я в растерянности. Я новичок в Jupyter Notebook со всем тестированием, и я решил, что это самый простой способ проверить атрибуты, прежде чем выполнять другой тест для конкретных данных из кода Python, но в любом случае я все равно получаю, что атрибут создания не существует!






Я создал слегка измененную версию вашего кода для удобства тестирования и получил сообщение об ошибке, что никакие username и password не передаются конструктору AnimalShelter.
class AnimalShelter(object):
""" CRUD operations for Animal collection in MongoDB """
def __init__(self, username, password):
print("constructor")
#Complete this create method to implement the C in CRUD.
def create(self, data):
print("create")
#Create method to implement the R in CRUD.
def read(self, searchData):
print("read")
#Create method to implement U in CRUD.
def update(self, searchData, updateData):
print("update")
#Create method to implement D in CRUD.
def delete(self, deleteData):
print("delete")
test_class = AnimalShelter("user", "pass")
data = {}
test_class.create(data)
test_class.read(data)
test_class.update(data, {})
test_class.delete(data)
Может быть, ваша ошибка связана с тем, что вы не передали эти переменные при создании объекта test_class? После прохождения "user" и "pass" я получил ожидаемый результат:
constructor
create
read
update
delete
Спасибо, я вижу, что, не помещая имя пользователя и пароль за test_class = AnimalShelter(), это выдавало мне ошибку! Я попытаюсь применить это к другим моим тестам и посмотреть, решит ли это мою проблему!
Покажите нам полную трассировку ошибок!