def test_prepare_qs_stmt_unregistered(self):
     """
     Given a function that generates an ORM query has not been registered with the PreparedStatementController
     When  prepare_sql_stmt is called for that function
     Then  a StatementNotRegistered error will be raised
     """
     psc = PreparedStatementController()
     with self.assertRaises(StatementNotRegistered):
         psc.prepare_qs_stmt("unregistered_qs", force=False)
    def test_prepare_qs_stmt(self):
        """
        Given a function that generates an ORM query has been registered with the PreparedStatementController
        When  prepare_qs_stmt is called
        Then  a PreparedORMStatement object should be created
        And   the PreparedORMStatement should be added to the prepared_statements dict
        And   the SQL will be preapred in the database
        """
        psc = PreparedStatementController()
        psc.register_qs("gen_qs", lambda: Species.prepare.all())

        with patch.object(PreparedORMStatement, "prepare",
                          return_value=None) as mock_prepare:
            psc.prepare_qs_stmt("gen_qs", force=False)
            self.assertTrue("gen_qs" in psc.prepared_statements)
            self.assertTrue(
                isinstance(psc.prepared_statements["gen_qs"],
                           PreparedORMStatement))
        mock_prepare.assert_called_once()
    def test_prepare_qs_stmt_force(self):
        """
        Given an ORM statement has already been prepared in the database
        When  prepare_qs_stmt is called for the same function
        And   force is False
        Then  a StatementAlreadyPreparedException error will be raised
        ---
        Given an ORM statement has already been prepared in the database
        When  prepare_qs_stmt is called for the same function
        And   force is True
        Then  the existing statement will be deallocated
        And   the statement will be re-prepared
        """
        psc = PreparedStatementController()
        psc.register_qs("gen_qs", lambda: Species.prepare.all())

        with patch.object(PreparedORMStatement, "prepare", return_value=None):
            psc.prepare_qs_stmt("gen_qs", force=False)
            self.assertTrue("gen_qs" in psc.prepared_statements)

        with self.assertRaises(StatementAlreadyPreparedException):
            psc.prepare_qs_stmt("gen_qs", force=False)

        with patch.object(PreparedORMStatement, "prepare",
                          return_value=None) as mock_prepare:
            with patch.object(PreparedORMStatement,
                              "deallocate",
                              return_value=None) as mock_deallocate:
                psc.prepare_qs_stmt("gen_qs", force=True)
        mock_deallocate.assert_called_once()
        mock_prepare.assert_called_once()