Ejemplo n.º 1
0
    def test_models_are_properly_pulled_and_matched(self):
        relation = self._get_relation()

        one = flexmock(Model())
        one.morph_type = 'morph_type_1'
        one.foreign_key = 'foreign_key_1'
        two = flexmock(Model())
        two.morph_type = 'morph_type_1'
        two.foreign_key = 'foreign_key_1'
        three = flexmock(Model())
        three.morph_type = 'morph_type_2'
        three.foreign_key = 'foreign_key_2'

        relation.add_eager_constraints([one, two, three])

        first_query = flexmock(Builder(flexmock(QueryBuilder(None, QueryGrammar(), None))))
        second_query = flexmock(Builder(flexmock(QueryBuilder(None, QueryGrammar(), None))))
        first_model = flexmock(Model())
        second_model = flexmock(Model())
        relation.should_receive('_create_model_by_type').once().with_args('morph_type_1').and_return(first_model)
        relation.should_receive('_create_model_by_type').once().with_args('morph_type_2').and_return(second_model)
        first_model.should_receive('get_key_name').and_return('id')
        second_model.should_receive('get_key_name').and_return('id')

        first_model.should_receive('new_query').once().and_return(first_query)
        second_model.should_receive('new_query').once().and_return(second_query)

        first_query.get_query().should_receive('where_in').once()\
            .with_args('id', ['foreign_key_1']).and_return(first_query)
        result_one = flexmock()
        first_query.should_receive('get').and_return(Collection.make([result_one]))
        result_one.should_receive('get_key').and_return('foreign_key_1')

        second_query.get_query().should_receive('where_in').once()\
            .with_args('id', ['foreign_key_2']).and_return(second_query)
        result_two = flexmock()
        second_query.should_receive('get').and_return(Collection.make([result_two]))
        result_two.should_receive('get_key').and_return('foreign_key_2')

        one.should_receive('set_relation').once().with_args('relation', result_one)
        two.should_receive('set_relation').once().with_args('relation', result_one)
        three.should_receive('set_relation').once().with_args('relation', result_two)

        relation.get_eager()
Ejemplo n.º 2
0
    def test_get_does_not_eager_relations_when_no_results_are_returned(self):
        flexmock(Builder)
        builder = Builder(self.get_mock_query_builder())
        builder.should_receive('get_models').with_args(['foo'
                                                        ]).and_return(['bar'])
        builder.should_receive('eager_load_relations').with_args(
            ['bar']).and_return([])
        builder.set_model(self.get_mock_model())
        builder.get_model().new_collection = mock.MagicMock(
            return_value=Collection([]))

        results = builder.get(['foo'])
        self.assertEqual([], results.all())

        builder.get_model().new_collection.assert_called_with([])
Ejemplo n.º 3
0
    def test_find_or_fail_with_many_raises_model_not_found_exception(self):
        model = self.get_mock_model()

        builder = Builder(self.get_mock_query_builder())
        builder.set_model(model)
        builder.get_query().where_in = mock.MagicMock()
        builder.get = mock.MagicMock(return_value=Collection([1]))

        self.assertRaises(ModelNotFound, builder.find_or_fail, [1, 2],
                          ['column'])

        builder.get_query().where_in.assert_called_once_with(
            'foo_table.foo', [1, 2])

        builder.get.assert_called_once_with(['column'])
    def test_fresh_method(self):
        model = flexmock(OrmModelStub())
        model.id = 1
        model.set_exists(True)
        builder = flexmock(Builder)
        query = Builder(flexmock(QueryBuilder(None, None, None)))
        query.should_receive('where').and_return(query)
        query.get_query().should_receive('take').and_return(query)
        query.should_receive('get').and_return(Collection([]))
        model.should_receive('with_').once().with_args('foo', 'bar').and_return(query)

        model.fresh(['foo', 'bar'])

        model.should_receive('with_').once().with_args().and_return(query)

        model.fresh()
    def test_push_empty_many_relation(self):
        flexmock(Builder)
        model = flexmock(Model())
        query = flexmock(QueryBuilder(MockConnection().prepare_mock(), QueryGrammar(), QueryProcessor()))
        builder = Builder(query)
        builder.get_query().should_receive('insert_get_id').once().with_args({'name': 'john'}, 'id').and_return(1)
        model.should_receive('new_query').once().and_return(builder)
        model.should_receive('_update_timestamps').once()

        model.name = 'john'
        model.set_exists(False)
        model.set_relation('relation_many', Collection([]))

        self.assertTrue(model.push())
        self.assertEqual(1, model.id)
        self.assertTrue(model.exists)
        self.assertEqual(0, len(model.relation_many))
Ejemplo n.º 6
0
    def test_models_are_properly_matched_to_parents(self):
        relation = self._get_relation()

        result1 = flexmock()
        result1.should_receive('get_attribute').with_args('id').and_return(1)
        result2 = flexmock()
        result2.should_receive('get_attribute').with_args('id').and_return(2)

        model1 = OrmBelongsToModelStub()
        model1.foreign_key = 1
        model2 = OrmBelongsToModelStub()
        model2.foreign_key = 2

        models = relation.match([model1, model2], Collection([result1, result2]), 'foo')

        self.assertEqual(1, models[0].foo.get_attribute('id'))
        self.assertEqual(2, models[1].foo.get_attribute('id'))
Ejemplo n.º 7
0
    def test_fresh_method(self):
        model = flexmock(models.OrmModelStub())
        model.id = 1
        model.set_exists(True)
        flexmock(Builder)
        q = flexmock(QueryBuilder(None, None, None))
        query = flexmock(Builder(q))
        query.should_receive("where").and_return(query)
        query.get_query().should_receive("take").and_return(query)
        query.should_receive("get").and_return(Collection([]))
        model.should_receive("with_").once().with_args("foo", "bar").and_return(query)

        model.fresh(["foo", "bar"])

        model.should_receive("with_").once().with_args().and_return(query)

        model.fresh()
Ejemplo n.º 8
0
    def test_get_models_hydrates_models(self):
        builder = Builder(self.get_mock_query_builder())
        records = [{'name': 'john', 'age': 26}, {'name': 'jane', 'age': 28}]

        builder.get_query().get = mock.MagicMock(return_value=records)
        model = self.get_mock_model()
        builder.set_model(model)
        model.get_connection_name = mock.MagicMock(
            return_value='foo_connection')
        model.hydrate = mock.MagicMock(return_value=Collection(['hydrated']))
        models = builder.get_models(['foo'])

        self.assertEqual(models.all(), ['hydrated'])

        model.get_table.assert_called_once_with()
        model.get_connection_name.assert_called_once_with()
        model.hydrate.assert_called_once_with(records, 'foo_connection')
Ejemplo n.º 9
0
    def test_first(self):
        model = self.get_mock_model()

        builder = Builder(self.get_mock_query_builder())
        builder.set_model(model)
        builder.take = mock.MagicMock(return_value=builder)
        builder.get = mock.MagicMock(return_value=Collection(['bar']))

        result = builder.first()
        self.assertEqual('bar', result)

        builder.take.assert_called_once_with(
            1
        )

        builder.get.assert_called_once_with(
            ['*']
        )
    def test_sync_syncs_intermediate_table_with_given_list_and_attributes(
            self):
        flexmock(BelongsToMany)
        relation = self._get_relation()
        query = flexmock()
        query.should_receive("from_").once().with_args("user_role").and_return(
            query)
        query.should_receive("where").once().with_args("user_id",
                                                       1).and_return(query)
        mock_query_builder = flexmock()
        relation.get_query().should_receive("get_query").and_return(
            mock_query_builder)
        mock_query_builder.should_receive("new_query").once().and_return(query)
        query.should_receive("lists").once().with_args("role_id").and_return(
            Collection([1, 2, 3]))
        relation.should_receive("attach").once().with_args(
            4, {"foo": "bar"}, False)
        relation.should_receive("update_existing_pivot").once().with_args(
            3, {
                "bar": "baz"
            }, False).and_return(True)
        relation.should_receive("detach").once().with_args([1])
        relation.should_receive("touch_if_touching").once()
        relation.get_related().should_receive("touches").and_return(False)
        relation.get_parent().should_receive("touches").and_return(False)

        self.assertEqual(
            {
                "attached": [4],
                "detached": [1],
                "updated": [3]
            },
            relation.sync([2, {
                3: {
                    "bar": "baz"
                }
            }, {
                4: {
                    "foo": "bar"
                }
            }]),
        )
Ejemplo n.º 11
0
    def test_touch_method_syncs_timestamps(self):
        relation = self._get_relation()
        relation.get_related().should_receive(
            'get_updated_at_column').and_return('updated_at')
        now = pendulum.now()
        relation.get_related().should_receive('fresh_timestamp').and_return(
            now)
        relation.get_related().should_receive(
            'get_qualified_key_name').and_return('table.id')
        relation.get_query().get_query().should_receive('select').once().with_args('table.id')\
            .and_return(relation.get_query().get_query())
        relation.get_query().should_receive('lists').once().and_return(
            Collection([1, 2, 3]))
        query = flexmock()
        relation.get_related().should_receive('new_query').once().and_return(
            query)
        query.should_receive('where_in').once().with_args(
            'id', [1, 2, 3]).and_return(query)
        query.should_receive('update').once().with_args({'updated_at': now})

        relation.touch()
Ejemplo n.º 12
0
    def test_sync_syncs_intermediate_table_with_given_list_and_attributes(
            self):
        flexmock(BelongsToMany)
        relation = self._get_relation()
        query = flexmock()
        query.should_receive('from_').once().with_args('user_role').and_return(
            query)
        query.should_receive('where').once().with_args('user_id',
                                                       1).and_return(query)
        mock_query_builder = flexmock()
        relation.get_query().should_receive('get_query').and_return(
            mock_query_builder)
        mock_query_builder.should_receive('new_query').once().and_return(query)
        query.should_receive('lists').once().with_args('role_id').and_return(
            Collection([1, 2, 3]))
        relation.should_receive('attach').once().with_args(
            4, {'foo': 'bar'}, False)
        relation.should_receive('update_existing_pivot').once().with_args(
            3, {
                'bar': 'baz'
            }, False).and_return(True)
        relation.should_receive('detach').once().with_args([1])
        relation.should_receive('touch_if_touching').once()
        relation.get_related().should_receive('touches').and_return(False)
        relation.get_parent().should_receive('touches').and_return(False)

        self.assertEqual({
            'attached': [4],
            'detached': [1],
            'updated': [3]
        }, relation.sync([2, {
            3: {
                'bar': 'baz'
            }
        }, {
            4: {
                'foo': 'bar'
            }
        }], ))
Ejemplo n.º 13
0
    def test_push_empty_many_relation(self):
        model = flexmock(Model())
        query = flexmock(
            QueryBuilder(
                MockConnection().prepare_mock(), QueryGrammar(), QueryProcessor()
            )
        )
        builder = Builder(query)
        builder.get_query().should_receive("insert_get_id").once().with_args(
            {"name": "john"}, "id"
        ).and_return(1)
        model.should_receive("new_query").once().and_return(builder)
        model.should_receive("_update_timestamps").once()

        model.name = "john"
        model.set_exists(False)
        model.set_relation("relation_many", Collection([]))

        self.assertTrue(model.push())
        self.assertEqual(1, model.id)
        self.assertTrue(model.exists)
        self.assertEqual(0, len(model.relation_many))
    def test_touch_method_syncs_timestamps(self):
        relation = self._get_relation()
        relation.get_related().should_receive(
            "get_updated_at_column").and_return("updated_at")
        now = pendulum.now()
        relation.get_related().should_receive("fresh_timestamp").and_return(
            now)
        relation.get_related().should_receive(
            "get_qualified_key_name").and_return("table.id")
        relation.get_query().get_query().should_receive(
            "select").once().with_args("table.id").and_return(
                relation.get_query().get_query())
        relation.get_query().should_receive("lists").once().and_return(
            Collection([1, 2, 3]))
        query = flexmock()
        relation.get_related().should_receive("new_query").once().and_return(
            query)
        query.should_receive("where_in").once().with_args(
            "id", [1, 2, 3]).and_return(query)
        query.should_receive("update").once().with_args({"updated_at": now})

        relation.touch()
Ejemplo n.º 15
0
    def test_models_are_properly_matched_to_parents(self):
        relation = self._get_relation()

        result1 = OrmHasOneModelStub()
        result1.foreign_key = 1
        result2 = OrmHasOneModelStub()
        result2.foreign_key = 2

        model1 = OrmHasOneModelStub()
        model1.id = 1
        model2 = OrmHasOneModelStub()
        model2.id = 2
        model3 = OrmHasOneModelStub()
        model3.id = 3

        relation.get_query().should_receive('where').with_args('table.foreign_key', '=', 2)
        relation.get_query().should_receive('where').with_args('table.foreign_key', '=', 3)

        models = relation.match([model1, model2, model3], Collection([result1, result2]), 'foo')

        self.assertEqual(1, models[0].foo.foreign_key)
        self.assertEqual(2, models[1].foo.foreign_key)
        self.assertEqual(None, models[2].foo)
Ejemplo n.º 16
0
    def serialized_json_api_obj(self, records=Collection()):
        """
        This method returns an single model or collection of models records
        serialized as JSONApi schema obj.

        NOTE: Currently just collection of the same model type are supported
        """
        result_obj = {}
        many = False
        schema = None

        if isinstance(records, Collection) and not records.is_empty():
            many = True
            schema = records.first().__class__.schema()
        elif callable(getattr(records.__class__, "schema")):
            many = False
            schema = records.__class__.schema()

        if schema:
            result_obj = self.__dump_schema(records=records,
                                            schema=schema,
                                            many=many)

        return result_obj
Ejemplo n.º 17
0
    def test_relation_is_properly_initialized(self):
        relation = self._get_relation()
        model = flexmock(Model())
        relation.get_related().should_receive('new_collection').replace_with(lambda l=None: Collection(l or []))
        model.should_receive('set_relation').once().with_args('foo', Collection)
        models = relation.init_relation([model], 'foo')

        self.assertEqual([model], models)