Ejemplo n.º 1
0
    def test_count(self):

        # the count() api should be preserved (it acts on the values).

        obj = Immutable(**{k: 'blah' for k in 'abcdefg'})
        self.assertEqual(obj.count('blah'), 7)
        self.assertEqual(obj.count('nope'), 0)
Ejemplo n.º 2
0
    def test_instantiation(self):

        # you can create via a tuple, an unpacked dict, or both.

        tup_instantiation = Immutable(('blah', 10))
        self.assertEqual(tup_instantiation.blah, 10)

        dict_instantiation = Immutable(**{'okie': 'dokie'})
        self.assertEqual(dict_instantiation.okie, 'dokie')

        both_instantiation = Immutable(('blah', 10), **{'okie': 'dokie'})
        self.assertEqual(list(both_instantiation.items()),
                         [('blah', 10), ('okie', 'dokie')])
    def test_collect_query_parameters(self):

        json = {
            "find":
            ["id", "title", "content", {
                "comments": ["id", "comment"]
            }],
            "where": {
                "id": 13
            }
        }

        initial_state = Immutable(data=None, errors=[])
        process = compose_list([
            change("json", json),
            change("type", Article), collect_query_parameters
        ])

        final_state = process(initial_state)

        qp = final_state.query_parameters

        self.assertEquals(qp["properties"], [
            Article.id, Article.title, Article.content, Comment.id,
            Comment.comment
        ])
        self.assertEquals(qp["joins"], [Article.comments])
        self.assertEquals(str(qp["conditions"][0]), str(Article.id == 13))
        self.assertEquals(qp["first_property"], Article.id)
    def get_transform_from_json(self, json):
        initial_state = Immutable(data=None, errors=[])
        process = compose_list([
            change("json", json),
            change("data", Article()),
            change("type", Article), transform_from_json
        ])

        return process(initial_state)
    def test_to_json(self, to_json):
        json = {"title": "A title", "content": "Some content"}
        initial_state = Immutable(data=None, errors=[])
        process = compose_list([change("data", json), to_json])
        final_state = process(initial_state)

        json_final = loads(final_state)

        #assert the object contains the values
        self.compareRecursively({"data": json}, json_final, [])
Ejemplo n.º 6
0
    def test_change(self):
        #given an immutable object
        initial_state = Immutable(data=None, errors=[])

        #when we channge it
        json = {"name": "Laci"}
        final_state = change("json", json)(initial_state)

        #assert it has the new value
        self.assertEquals(json, value("json")(final_state))
    def get_database_object_for(self, json, session):
        initial_state = Immutable(data=None, errors=[])
        process = compose_list([
            change("json", json),
            change("session", session),
            change("type", Article),
            get_database_object
        ])


        return process(initial_state)
    def test_transform_to_json_article(self):
        initial_state = Immutable(data=None, errors=[])
        process = compose_list([
            change("data", Article(title="title", content="content")),
            change("type", Article), transform_to_json
        ])
        final_state = process(initial_state)

        #assert the object contains the values
        json = value("data")(final_state)

        self.assertTrue(json.has_key("id"))
        self.assertEquals("title", json["title"])
        self.assertEquals("content", json["content"])
Ejemplo n.º 9
0
def save(json, session):

    initial_state = Immutable(data=None, errors=[])

    process = compose_list([
        change("json", json),
        change("session", session),
        change("type", Article), get_database_object, transform_from_json,
        save_database_object, transform_to_json, to_json
    ])

    final_state = process(initial_state)

    return final_state
    def test_run_queries(self):
        #given an article in the database

        session = Session()
        new_article = Article(title="Title",
                              content="Content",
                              comments=[
                                  Comment(comment="my first comment"),
                                  Comment(comment="my second comment")
                              ])
        session.add(new_article)
        session.commit()

        id = new_article.id
        session.close()

        session = Session()
        queries = {
            "query_ids":
            session.query(Article.id).outerjoin(Article.comments).filter(
                Article.id == id).group_by(Article.id),
            "query":
            session.query(Article.id, Article.title, Article.content,
                          Comment.id, Comment.comment).outerjoin(
                              Article.comments).group_by(
                                  Article.id, Article.title, Article.content,
                                  Comment.id, Comment.comment),
            "first_property":
            Article.id
        }

        initial_state = Immutable(data=None, errors=[])
        process = compose_list([
            change("queries", queries),
            change("type", Article),
            change("session", session), run_queries
        ])

        final_state = process(initial_state)

        results = final_state.data

        self.assertEquals(results[0][0], id)
        self.assertEquals(results[0][1], "Title")
        self.assertEquals(results[0][2], "Content")
        self.assertEquals(results[0][4], "my first comment")
        self.assertEquals(results[1][0], id)
        self.assertEquals(results[1][1], "Title")
        self.assertEquals(results[1][2], "Content")
        self.assertEquals(results[1][4], "my second comment")
Ejemplo n.º 11
0
def query(json, session):
    initial_state = Immutable(data=None, errors=[])

    process = compose_list([
        change("json", json),
        change("session", session),
        change("type", Article), collect_query_parameters, generate_queries,
        run_queries, transform_results, to_json
    ])

    # transform("data", "data"),

    final_state = process(initial_state)

    return final_state
    def test_save_database_object(self):
        initial_state = Immutable(data=None, errors=[])
        title = "Saved "+str(random())
        process = compose_list([
            change("data", Article(title=title, content="Added content")),
            change("session", Session()),
            save_database_object
        ])

        final_state =  process(initial_state)

        # assert it exists in the database
        saved_object = Session().query(Article).filter(Article.title==title).first()
        self.assertEquals(title, saved_object.title)
        self.assertEquals("Added content", saved_object.content)
    def test_transform_results(self):
        results = [(1, "my title", "my content", 10, "my first comment"),
                   (1, "my title", "my content", 11, "my second comment")]

        initial_state = Immutable(data=None, errors=[])
        process = compose_list([
            change(
                "json", {
                    "find": [
                        "id", "title", "content", {
                            "comments": ["id", "comment"]
                        }
                    ]
                }),
            change("data", results), transform_results
        ])
        final_state = process(initial_state)

        expected_json = {
            1: {
                "id": 1,
                "title": "my title",
                "content": "my content",
                "comments": {
                    10: {
                        "id": 10,
                        "comment": "my first comment"
                    },
                    11: {
                        "id": 11,
                        "comment": "my second comment"
                    }
                }
            }
        }

        self.compareRecursively(expected_json, final_state.data, [])
    def test_generate_queries(self):
        qp = {
            "properties": [
                Article.id, Article.title, Article.content, Comment.id,
                Comment.comment
            ],
            "joins": [Article.comments],
            "conditions": [Article.id == 13]
        }
        session = Session()

        initial_state = Immutable(data=None, errors=[])
        process = compose_list([
            change("query_parameters", qp),
            change("type", Article),
            change("session", session), generate_queries
        ])

        final_state = process(initial_state)

        queries = final_state.queries

        self.assertEquals(
            str(queries["query_ids"]),
            str(
                session.query(Article.id).outerjoin(Article.comments).filter(
                    Article.id == 13).group_by(Article.id)))
        self.assertEquals(
            str(queries["query"]),
            str(
                session.query(
                    Article.id, Article.title, Article.content, Comment.id,
                    Comment.comment).outerjoin(Article.comments).group_by(
                        Article.id, Article.title, Article.content, Comment.id,
                        Comment.comment)))
        self.assertEquals(queries["first_property"], Article.id)
Ejemplo n.º 15
0
 def setUp(self):
     self.unordered_immutable = Immutable(black='black', white='white',
                                          red='red', blue='blue')
     self.ordered_immutable = Immutable(
         ('zero', 0), ('one', 1), ('two', 2), ('three', 3)
     )
Ejemplo n.º 16
0
class TestImmutable(TestCase):

    def setUp(self):
        self.unordered_immutable = Immutable(black='black', white='white',
                                             red='red', blue='blue')
        self.ordered_immutable = Immutable(
            ('zero', 0), ('one', 1), ('two', 2), ('three', 3)
        )

    def test_create_empty(self):

        # should be able to instantiate without args.

        obj = Immutable()
        self.assertEqual(obj.__class__.__name__, 'Immutable')

    def test_instantiation(self):

        # you can create via a tuple, an unpacked dict, or both.

        tup_instantiation = Immutable(('blah', 10))
        self.assertEqual(tup_instantiation.blah, 10)

        dict_instantiation = Immutable(**{'okie': 'dokie'})
        self.assertEqual(dict_instantiation.okie, 'dokie')

        both_instantiation = Immutable(('blah', 10), **{'okie': 'dokie'})
        self.assertEqual(list(both_instantiation.items()),
                         [('blah', 10), ('okie', 'dokie')])

    def test_keys(self):

        # the keys() api should be preserved

        self.assertEqual(set(self.unordered_immutable.keys()),
                         {'black', 'white', 'red', 'blue'})

        # if given as a tuple, they should keep the given order
        self.assertEqual(list(self.ordered_immutable.keys()),
                         ['zero', 'one', 'two', 'three'])

    def test_values(self):

        # the values() api should be preserved

        self.assertEqual(set(self.unordered_immutable.values()),
                         {'black', 'white', 'red', 'blue'})

        # if given as a tuple, they should keep the given order
        self.assertEqual(list(self.ordered_immutable.values()), [0, 1, 2, 3])

    def test_items(self):

        # the items() api should be preserved

        self.assertEqual(set(self.unordered_immutable.items()),
                         {('black', 'black'), ('white', 'white'),
                          ('red', 'red'), ('blue', 'blue')})

        # if given as a tuple, they should keep the given order
        self.assertEqual(list(self.ordered_immutable.items()),
                         [('zero', 0), ('one', 1), ('two', 2), ('three', 3)])

    def test_index(self):

        # the index() api should be preserved (it acts on the values).

        self.assertEqual(self.ordered_immutable.index(0), 0)
        self.assertEqual(self.ordered_immutable.index(1), 1)

    def test_count(self):

        # the count() api should be preserved (it acts on the values).

        obj = Immutable(**{k: 'blah' for k in 'abcdefg'})
        self.assertEqual(obj.count('blah'), 7)
        self.assertEqual(obj.count('nope'), 0)

    def test_containment(self):

        # we don't support containment because it's ambiguous

        regex = 'Containment not implemented.'
        with self.assertRaisesRegexp(Immutable.ImmutableError, regex):
            'white' in self.unordered_immutable

    def test_reversal(self):

        # we don't support reversal because it's ambiguous

        regex = 'Reversal not implemented.'
        with self.assertRaisesRegexp(Immutable.ImmutableError, regex):
            reversed(self.unordered_immutable)

    def test_equality(self):

        # equality works by hashing two immutable instances

        self.assertFalse(self.ordered_immutable == self.unordered_immutable)

        args = [('a', 1), ('b', 2)]
        imm_0 = Immutable(*args)
        imm_1 = Immutable(*args)
        self.assertFalse(imm_0 == args)
        self.assertTrue(imm_0 == imm_1)


    def test_non_equality_comparisons(self):

        # equality works by hashing two immutable instances

        self.assertTrue(self.ordered_immutable != self.unordered_immutable)

        args = [('a', 1), ('b', 2)]
        imm_0 = Immutable(*args)
        imm_1 = Immutable(*args)
        self.assertTrue(imm_0 != args)
        self.assertFalse(imm_0 != imm_1)

    def test_attribute_access(self):

        # You should be able to access via both getitem or getattr with indices
        # or keys.

        self.assertEqual(self.ordered_immutable.zero, 0)
        self.assertEqual(self.ordered_immutable['zero'], 0)
        self.assertEqual(self.ordered_immutable[0], 0)
        self.assertEqual(self.ordered_immutable[-4], 0)

    def test_change_attribute(self):

        # you can't!

        # should not be able to change with key
        with self.assertRaisesRegexp(Immutable.ImmutableError,
                                     'Cannot set items on Immutable.'):
            self.ordered_immutable['zero'] = 10

        # should not be able to change with index
        with self.assertRaisesRegexp(Immutable.ImmutableError,
                                     'Cannot set items on Immutable.'):
            self.ordered_immutable[0] = 10

        # should not be able to change with negative index
        with self.assertRaisesRegexp(Immutable.ImmutableError,
                                     'Cannot set items on Immutable.'):
            self.ordered_immutable[-4] = 10

        # should not be able to change with '.' access
        with self.assertRaisesRegexp(Immutable.ImmutableError,
                                     'Cannot set attributes on Immutable.'):
            self.ordered_immutable.zero = 10

        # finally, show how we *can* change it! NEVER DO THIS!
        self.ordered_immutable._ordered_dict['zero'] = 10
        self.assertEqual(self.ordered_immutable['zero'], 10)

    def test___dir__(self):

        # __dir__ should return a list of the keys.

        dir_list = self.ordered_immutable.__dir__()
        expected_dir_list = ['zero', 'one', 'two', 'three']
        self.assertEqual(dir_list, expected_dir_list)