# Path: pushmanager/core/db.py
# def UnsignedInteger():
# def init_db():
# def finalize_db():
# def execute_cb(query, callback_fn):
# def execute_transaction_cb(queries, callback_fn, condition=None):
# def prefix_insert_ignore(insert_ignore, compiler, **kw):
# def prefix_insert_ignore_sqlite(insert_ignore, compiler, **kw):
# class DatabaseError(Exception):
# class PushCheckList(Base):
# class PushPlans(Base):
# class PushPushContents(Base):
# class PushPushes(Base):
# class PushRemovals(Base):
# class PushRequests(Base):
# class InsertIgnore(Insert):
# 
# Path: pushmanager/servlets/addrequest.py
# class AddRequestServlet(RequestHandler):
# 
#     def post(self):
#         if not self.current_user:
#             return self.send_error(403)
#         self.pushid = pushmanager.core.util.get_int_arg(self.request, 'push')
#         self.request_ids = self.request.arguments.get('request', [])
# 
#         insert_queries = [
#                 InsertIgnore(db.push_pushcontents, ({'request': int(i), 'push': self.pushid}))
#                 for i in self.request_ids
#         ]
#         update_query = db.push_requests.update().where(
#             db.push_requests.c.id.in_(self.request_ids)).values({'state': 'added'})
#         request_query = db.push_requests.select().where(
#             db.push_requests.c.id.in_(self.request_ids))
# 
#         db.execute_transaction_cb(insert_queries + [update_query, request_query], self.on_db_complete)
# 
#     # allow both GET and POST
#     get = post
# 
#     def on_db_complete(self, success, db_results):
#         self.check_db_results(success, db_results)
# 
#         for req in db_results[-1]:
#             if req['watchers']:
#                 user_string = '%s (%s)' % (req['user'], req['watchers'])
#                 users = [req['user']] + req['watchers'].split(',')
#             else:
#                 user_string = req['user']
#                 users = [req['user']]
#             msg = (
#                 """
#                 <p>
#                     %(pushmaster)s has accepted request for %(user)s into a push:
#                 </p>
#                 <p>
#                     <strong>%(user)s - %(title)s</strong><br />
#                     <em>%(repo)s/%(branch)s</em>
#                 </p>
#                 <p>
#                     Regards,<br />
#                     PushManager
#                 </p>"""
#                 ) % pushmanager.core.util.EscapedDict({
#                     'pushmaster': self.current_user,
#                     'user': user_string,
#                     'title': req['title'],
#                     'repo': req['repo'],
#                     'branch': req['branch'],
#                 })
#             subject = "[push] %s - %s" % (user_string, req['title'])
#             MailQueue.enqueue_user_email(users, msg, subject)
#             msg = '{0} has accepted request "{1}" for {2} into a push:\n{3}/push?id={4}'.format(
#                 self.current_user,
#                 req['title'],
#                 user_string,
#                 self.get_base_url(),
#                 self.pushid,
#             )
#             XMPPQueue.enqueue_user_xmpp(users, msg)
# 
# Path: pushmanager/testing/mocksettings.py



import types
import urllib
import mock
import testify as T
from contextlib import nested
from pushmanager.core import db
from pushmanager.core.util import get_servlet_urlspec
from pushmanager.servlets.addrequest import AddRequestServlet
from pushmanager.testing.mocksettings import MockedSettings
from pushmanager.testing.testservlet import ServletTestMixin



class AddRequestServletTest(T.TestCase, ServletTestMixin):

    @T.class_setup_teardown
    def mock_servlet_env(self):
        self.results = []
        with nested(
            mock.patch.dict(db.Settings, MockedSettings),
            mock.patch.object(
                AddRequestServlet,
                "get_current_user",
                return_value="testuser"
            )
        ):
            yield

    def record_pushcontents(self, success, db_results):
        assert success
        self.results = []
        self.results.extend(db_results.fetchall())

    def get_handlers(self):

# Path: pushmanager/core/db.py
# def UnsignedInteger():
# def init_db():
# def finalize_db():
# def execute_cb(query, callback_fn):
# def execute_transaction_cb(queries, callback_fn, condition=None):
# def prefix_insert_ignore(insert_ignore, compiler, **kw):
# def prefix_insert_ignore_sqlite(insert_ignore, compiler, **kw):
# class DatabaseError(Exception):
# class PushCheckList(Base):
# class PushPlans(Base):
# class PushPushContents(Base):
# class PushPushes(Base):
# class PushRemovals(Base):
# class PushRequests(Base):
# class InsertIgnore(Insert):
# 
# Path: pushmanager/servlets/addrequest.py
# class AddRequestServlet(RequestHandler):
# 
#     def post(self):
#         if not self.current_user:
#             return self.send_error(403)
#         self.pushid = pushmanager.core.util.get_int_arg(self.request, 'push')
#         self.request_ids = self.request.arguments.get('request', [])
# 
#         insert_queries = [
#                 InsertIgnore(db.push_pushcontents, ({'request': int(i), 'push': self.pushid}))
#                 for i in self.request_ids
#         ]
#         update_query = db.push_requests.update().where(
#             db.push_requests.c.id.in_(self.request_ids)).values({'state': 'added'})
#         request_query = db.push_requests.select().where(
#             db.push_requests.c.id.in_(self.request_ids))
# 
#         db.execute_transaction_cb(insert_queries + [update_query, request_query], self.on_db_complete)
# 
#     # allow both GET and POST
#     get = post
# 
#     def on_db_complete(self, success, db_results):
#         self.check_db_results(success, db_results)
# 
#         for req in db_results[-1]:
#             if req['watchers']:
#                 user_string = '%s (%s)' % (req['user'], req['watchers'])
#                 users = [req['user']] + req['watchers'].split(',')
#             else:
#                 user_string = req['user']
#                 users = [req['user']]
#             msg = (
#                 """
#                 <p>
#                     %(pushmaster)s has accepted request for %(user)s into a push:
#                 </p>
#                 <p>
#                     <strong>%(user)s - %(title)s</strong><br />
#                     <em>%(repo)s/%(branch)s</em>
#                 </p>
#                 <p>
#                     Regards,<br />
#                     PushManager
#                 </p>"""
#                 ) % pushmanager.core.util.EscapedDict({
#                     'pushmaster': self.current_user,
#                     'user': user_string,
#                     'title': req['title'],
#                     'repo': req['repo'],
#                     'branch': req['branch'],
#                 })
#             subject = "[push] %s - %s" % (user_string, req['title'])
#             MailQueue.enqueue_user_email(users, msg, subject)
#             msg = '{0} has accepted request "{1}" for {2} into a push:\n{3}/push?id={4}'.format(
#                 self.current_user,
#                 req['title'],
#                 user_string,
#                 self.get_base_url(),
#                 self.pushid,
#             )
#             XMPPQueue.enqueue_user_xmpp(users, msg)
# 
# Path: pushmanager/testing/mocksettings.py



# Path: pushmanager/tests/test_servlet_addrequest.py
import types
import urllib
import mock
import testify as T
from contextlib import nested
from pushmanager.core import db
from pushmanager.core.util import get_servlet_urlspec
from pushmanager.servlets.addrequest import AddRequestServlet
from pushmanager.testing.mocksettings import MockedSettings
from pushmanager.testing.testservlet import ServletTestMixin




class AddRequestServletTest(T.TestCase, ServletTestMixin):

    @T.class_setup_teardown
    def mock_servlet_env(self):
        self.results = []
        with nested(
            mock.patch.dict(db.Settings, MockedSettings),
            mock.patch.object(
                AddRequestServlet,
                "get_current_user",
                return_value="testuser"
            )
        ):
            yield

    def record_pushcontents(self, success, db_results):
        assert success
        self.results = []
        self.results.extend(db_results.fetchall())

    def get_handlers(self):

        return [get_servlet_urlspec(AddRequestServlet)]