Beispiel #1
0
class QueryExecutionService:
    def __init__(self, mongo_wrapper=None, exercise_service=None):
        if mongo_wrapper is None:
            self.__mongo_wrapper = MongoWrapper()
        else:
            self.__mongo_wrapper = mongo_wrapper

        if exercise_service is None:
            self.__exercise_service = ExerciseService()
        else:
            self.__exercise_service = exercise_service

    def execute_exercise_query(self, query, exercise_id):
        try:
            exercise = self.__exercise_service.get_exercise_by_id(exercise_id)
            self.__mongo_wrapper.set_collection_data(
                exercise.get_collection_name(), exercise.get_collection_data())
            return self.execute_query(query)
        except MongoWrapperException as mwe:
            raise ServiceError(str(mwe))

    def execute_query(self, query):
        try:
            result = self.__mongo_wrapper.execute_query(query)
            return QueryExecution(result)
        except MongoWrapperException as mwe:
            raise ServiceError(str(mwe))
Beispiel #2
0
    def __init__(self, mongo_wrapper=None, exercise_service=None):
        if mongo_wrapper is None:
            self.__mongo_wrapper = MongoWrapper()
        else:
            self.__mongo_wrapper = mongo_wrapper

        if exercise_service is None:
            self.__exercise_service = ExerciseService()
        else:
            self.__exercise_service = exercise_service
Beispiel #3
0
    def setUp(self):
        self.connection_uri = settings.PDB_PLAYGROUND_MONGO_CONNECTION_PROPS[
            'CONNECTION_URI']
        self.db_name = settings.PDB_PLAYGROUND_MONGO_CONNECTION_PROPS['DBNAME']

        if self.connection_uri is None:
            raise ValueError("Connection URI cannot be None")
        if self.db_name is None:
            raise ValueError("DB name cannot be None")

        client = MongoClient(self.connection_uri,
                             readPreference=settings.
                             PDB_MONGO_CONNECTION_PROPS['READ_PREFERENCE'])
        self.db = client[self.db_name]
        self.tearDown()
        super(MongoWrapperIntegrationTest, self).setUp()
        self.sut = MongoWrapper()
Beispiel #4
0
class MongoWrapperUnitTest(unittest.TestCase):
    def setUp(self):
        self.stub_operation_mapper = mock.Mock(spec=OperationMapperBase)
        self.stub_result_mapper = mock.Mock(spec=IResultMapper)
        self.stub_pymongo_executor = mock.Mock(spec=PymongoExecutor)
        self.sut = MongoWrapper()

    def test_executeQuery_calledWithInvalidFirstQueryComponent_raiseMongoWrapperException(
            self):
        self.assertRaises(MongoWrapperException,
                          self.sut.execute_query,
                          query='dx.collection.find({})')

    def test_executeQuery_calledWithInvalidSecondQueryComponent_raiseMongoWrapperException(
            self):
        pass

    def test_executeQuery_calledWithInvalidThirdQueryComponent_raiseMongoWrapperException(
            self):
        self.assertRaises(MongoWrapperException,
                          self.sut.execute_query,
                          query='db.collection.unsupportedOp({})')

    def test_executeQuery_calledWithInsertOneOperation_correctCallToInnerOperationMapperWithRightParams(
            self):
        self.__exercise_insert_one()
        self.stub_operation_mapper.format.assert_called_once_with(
            operation_params=
            "({'data':'test', '_id': ObjectId(\"5a9442ad15b81e04322f0726\")})")

    def test_executeQuery_calledWithInsertOneOperation_correctCallToInnerResultMapperWithRightParams(
            self):
        self.__exercise_insert_one()
        self.stub_result_mapper.format.assert_called_once_with(
            operation_result="test_result")

    def __exercise_insert_one(self):
        self.stub_operation_mapper.format.return_value = "test"
        self.stub_pymongo_executor.execute.return_value = "test_result"
        self.sut.execute_query(
            "db.testcollection.insertOne({'data':'test', '_id': ObjectId(\"5a9442ad15b81e04322f0726\")})",
            operation_mapper=self.stub_operation_mapper,
            result_mapper=self.stub_result_mapper,
            pymongo_executor=self.stub_pymongo_executor)
Beispiel #5
0
    def create(self, request):
        if request.pdbuser is None:
            return self._create_generic_response(
                response_type=ResponseType.authentication_error)
        try:
            exercise = Exercise.from_json(request.data)
            exercise.set_collection_data(MongoWrapper().get_collection_data(
                request.data["collection_name"]))
        except Exception as e:
            return self._create_generic_response(
                response_type=ResponseType.server_error, exception=e)

        return self._create_response_by_inner_service_call(
            self.__exercise_service.create_exercise,
            exercise,
            message='exercise created')
Beispiel #6
0
    def execute_exercise_query(self, request):
        user = request.pdbuser
        if user is None:
            return self._create_generic_response(
                response_type=ResponseType.authentication_error)
        try:
            raw_query = request.data["query"]
            exercise_id = request.data["exercise_id"]

        except Exception as e:
            return self._create_generic_response(
                response_type=ResponseType.server_error, exception=e)
        if self.__query_execution_service is None:
            self.__query_execution_service = QueryExecutionService(
                mongo_wrapper=MongoWrapper(db_name=str(user.get_id())))
        return self._create_response_by_inner_service_call(
            self.__query_execution_service.execute_exercise_query,
            raw_query,
            exercise_id,
            message='query executed')
Beispiel #7
0
class MongoWrapperIntegrationTest(unittest.TestCase):
    def setUp(self):
        self.connection_uri = settings.PDB_PLAYGROUND_MONGO_CONNECTION_PROPS[
            'CONNECTION_URI']
        self.db_name = settings.PDB_PLAYGROUND_MONGO_CONNECTION_PROPS['DBNAME']

        if self.connection_uri is None:
            raise ValueError("Connection URI cannot be None")
        if self.db_name is None:
            raise ValueError("DB name cannot be None")

        client = MongoClient(self.connection_uri,
                             readPreference=settings.
                             PDB_MONGO_CONNECTION_PROPS['READ_PREFERENCE'])
        self.db = client[self.db_name]
        self.tearDown()
        super(MongoWrapperIntegrationTest, self).setUp()
        self.sut = MongoWrapper()

    def tearDown(self):
        self.db.testcollection.delete_many({})

    def test_getCollectionData_calledWithCorrectCollectionName_returnCollectionData(
            self):
        self.db.testcollection.insert_many(self.__get_test_data())
        actual = self.sut.get_collection_data('testcollection')
        expected = self.__get_test_data()
        self.assertEqual(actual, expected)

    def test_getCollectionData_calledWithUnexistentCollectionName_returnEmptyList(
            self):
        actual = self.sut.get_collection_data('unexistentcollection')
        expected = []
        self.assertEqual(actual, expected)

    def test_setCollectionData_calledWithValidNameAndData_dataCorreclyInsertedInCollection(
            self):
        data = self.__get_test_data()
        self.sut.set_collection_data(collection_name='testcollection',
                                     data=data)
        actual = self.__from_cursor_to_doc_list(self.db.testcollection.find(
            {}))
        expected = data
        self.assertEqual(actual, expected)

    def test_setCollectionData_calledWithInvalidDataSingleDocument_raiseMongoWrapperException(
            self):
        self.assertRaises(MongoWrapperException,
                          self.sut.set_collection_data,
                          collection_name='testcollection',
                          data={"foo": 1})

    def test_setCollectionData_calledWithInvalidDataNumber_raiseMongoWrapperException(
            self):
        self.assertRaises(MongoWrapperException,
                          self.sut.set_collection_data,
                          collection_name='testcollection',
                          data=1)

    def test_setCollectionData_calledWithInvalidDataString_raiseMongoWrapperException(
            self):
        self.assertRaises(MongoWrapperException,
                          self.sut.set_collection_data,
                          collection_name='testcollection',
                          data='test')

    def __get_test_data(self):
        return [{
            "foo": 1,
            "buu": "test1",
            "_id": ObjectId("4d128b6ea794fc13a8000001")
        }, {
            "foo": 3,
            "buu": "test2",
            "_id": ObjectId("4d128b6ea794fc13a8000002")
        }]

    def __from_cursor_to_doc_list(self, cursor):
        result = []
        for elem in cursor:
            result.append(elem)
        return result
Beispiel #8
0
 def setUp(self):
     self.stub_operation_mapper = mock.Mock(spec=OperationMapperBase)
     self.stub_result_mapper = mock.Mock(spec=IResultMapper)
     self.stub_pymongo_executor = mock.Mock(spec=PymongoExecutor)
     self.sut = MongoWrapper()