# Path: hakoblog/db.py
# class DB:
#     def __init__(self):
#         self.conn = MySQLdb.connect(
#             db=CONFIG.DATABASE,
#             host=CONFIG.DATABASE_HOST,
#             user=CONFIG.DATABASE_USER,
#             password=CONFIG.DATABASE_PASS,
#             cursorclass=MySQLdb.cursors.DictCursor,
#             charset="utf8",
#         )
#         self.conn.autocommit(True)
# 
#     def cursor(self):
#         return self.conn.cursor()
# 
#     def close(self):
#         self.conn.close()
# 
#     def uuid_short(self):
#         with self.conn.cursor() as cursor:
#             cursor.execute("SELECT UUID_SHORT() as uuid")
#             return cursor.fetchone().get("uuid")
# 
# Path: hakoblog/action/blog.py
# class BlogAction:
#     @classmethod
#     def create(self, db, owner_id, title):
#         now = datetime.now()
#         new_id = db.uuid_short()
#         with db.cursor() as cursor:
#             cursor.execute(
#                 """
#                     INSERT INTO blog (
#                         id, owner_id, title, created, modified
#                     ) VALUES (
#                         %s, %s, %s, %s, %s
#                     )
#                 """,
#                 (new_id, owner_id, title, now, now),
#             )
#         return new_id
# 
#     @classmethod
#     def ensure_global_blog_created(cls, db):
#         global_user = UserAction.ensure_global_user_created(db)
#         blog = BlogLoader.find_by_owner_id(db, global_user.id)
# 
#         if blog is None:
#             cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
#             blog = BlogLoader.find_by_owner_id(db, global_user.id)
# 
#         return blog
# 
# Path: hakoblog/loader/entry.py
# class EntryLoader:
#     @classmethod
#     def find_by_id(cls, db, entry_id):
#         with db.cursor() as cursor:
#             cursor.execute(
#                 """
#                 SELECT id, blog_id, title, body, created, modified
#                 FROM entry
#                 WHERE id = %s
#                 LIMIT 1
#                 """,
#                 (entry_id,),
#             )
#             row = cursor.fetchone()
# 
#             if row is None:
#                 return None
# 
#         return Entry(**row)
# 
#     @classmethod
#     def find_entries(cls, db, blog_id, limit=30):
#         with db.cursor() as cursor:
#             cursor.execute(
#                 """
#                 SELECT id, blog_id, title, body, created, modified
#                 FROM entry
#                 WHERE blog_id = %s
#                 ORDER BY created DESC
#                 LIMIT %s
#                 """,
#                 (blog_id, limit),
#             )
#             rows = cursor.fetchall()
# 
#         return [Entry(**r) for r in rows]
# 
# Path: tests/util.py
# def web_client():
#     return web.test_client()
# 
# @contextmanager
# def global_user(name):
#     prev_name = CONFIG.GLOBAL_USER_NAME
#     CONFIG.GLOBAL_USER_NAME = name
#     yield name
#     CONFIG.GLOBAL_USER_NAME = prev_name
# 
# def random_string(length, seq=string.digits + string.ascii_letters):
#     sr = random.SystemRandom()
#     return ''.join([sr.choice(seq) for i in range(length)])


import tests.hakoblog  # noqa: F401
from flask import url_for
from hakoblog.db import DB
from hakoblog.action.blog import BlogAction
from hakoblog.loader.entry import EntryLoader
from tests.util import web_client, global_user, random_string





def test_post_show_form():
    with global_user(random_string(5)):
        res = web_client().get('/-/post')
        assert res.status == '200 OK'


def test_post_create_entry():
    db = DB()

    with global_user(random_string(5)), web_client() as wc:
        blog = BlogAction.ensure_global_blog_created(db)

        res = wc.post('/-/post', data=dict(
            title='はろー',
            body='こんにちは',
            blog_id=blog.id,
        ))
        assert res.status == '302 FOUND'
        assert res.headers['Location'] == url_for('index', _external=True)


# Path: hakoblog/db.py
# class DB:
#     def __init__(self):
#         self.conn = MySQLdb.connect(
#             db=CONFIG.DATABASE,
#             host=CONFIG.DATABASE_HOST,
#             user=CONFIG.DATABASE_USER,
#             password=CONFIG.DATABASE_PASS,
#             cursorclass=MySQLdb.cursors.DictCursor,
#             charset="utf8",
#         )
#         self.conn.autocommit(True)
# 
#     def cursor(self):
#         return self.conn.cursor()
# 
#     def close(self):
#         self.conn.close()
# 
#     def uuid_short(self):
#         with self.conn.cursor() as cursor:
#             cursor.execute("SELECT UUID_SHORT() as uuid")
#             return cursor.fetchone().get("uuid")
# 
# Path: hakoblog/action/blog.py
# class BlogAction:
#     @classmethod
#     def create(self, db, owner_id, title):
#         now = datetime.now()
#         new_id = db.uuid_short()
#         with db.cursor() as cursor:
#             cursor.execute(
#                 """
#                     INSERT INTO blog (
#                         id, owner_id, title, created, modified
#                     ) VALUES (
#                         %s, %s, %s, %s, %s
#                     )
#                 """,
#                 (new_id, owner_id, title, now, now),
#             )
#         return new_id
# 
#     @classmethod
#     def ensure_global_blog_created(cls, db):
#         global_user = UserAction.ensure_global_user_created(db)
#         blog = BlogLoader.find_by_owner_id(db, global_user.id)
# 
#         if blog is None:
#             cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
#             blog = BlogLoader.find_by_owner_id(db, global_user.id)
# 
#         return blog
# 
# Path: hakoblog/loader/entry.py
# class EntryLoader:
#     @classmethod
#     def find_by_id(cls, db, entry_id):
#         with db.cursor() as cursor:
#             cursor.execute(
#                 """
#                 SELECT id, blog_id, title, body, created, modified
#                 FROM entry
#                 WHERE id = %s
#                 LIMIT 1
#                 """,
#                 (entry_id,),
#             )
#             row = cursor.fetchone()
# 
#             if row is None:
#                 return None
# 
#         return Entry(**row)
# 
#     @classmethod
#     def find_entries(cls, db, blog_id, limit=30):
#         with db.cursor() as cursor:
#             cursor.execute(
#                 """
#                 SELECT id, blog_id, title, body, created, modified
#                 FROM entry
#                 WHERE blog_id = %s
#                 ORDER BY created DESC
#                 LIMIT %s
#                 """,
#                 (blog_id, limit),
#             )
#             rows = cursor.fetchall()
# 
#         return [Entry(**r) for r in rows]
# 
# Path: tests/util.py
# def web_client():
#     return web.test_client()
# 
# @contextmanager
# def global_user(name):
#     prev_name = CONFIG.GLOBAL_USER_NAME
#     CONFIG.GLOBAL_USER_NAME = name
#     yield name
#     CONFIG.GLOBAL_USER_NAME = prev_name
# 
# def random_string(length, seq=string.digits + string.ascii_letters):
#     sr = random.SystemRandom()
#     return ''.join([sr.choice(seq) for i in range(length)])


# Path: tests/web/test_post.py
import tests.hakoblog  # noqa: F401
from flask import url_for
from hakoblog.db import DB
from hakoblog.action.blog import BlogAction
from hakoblog.loader.entry import EntryLoader
from tests.util import web_client, global_user, random_string






def test_post_show_form():
    with global_user(random_string(5)):
        res = web_client().get('/-/post')
        assert res.status == '200 OK'


def test_post_create_entry():
    db = DB()

    with global_user(random_string(5)), web_client() as wc:
        blog = BlogAction.ensure_global_blog_created(db)

        res = wc.post('/-/post', data=dict(
            title='はろー',
            body='こんにちは',
            blog_id=blog.id,
        ))
        assert res.status == '302 FOUND'
        assert res.headers['Location'] == url_for('index', _external=True)


        entry = EntryLoader.find_entries(db, blog.id, limit=1)[0]