# Path: subrosa/models/UsersModel.py
# class Users(BaseModel):
# 
#     """
#     Models and methods related to user database interaction
#     """
# 
#     username = CharField(max_length=40, unique=True, index=True)
#     hash = CharField()
#     real_name = CharField(max_length=40, null=True)
#     description = TextField(null=True)
#     about = TextField(null=True)
# 
#     @staticmethod
#     def check_any_exist():
#         """ Check if any users exist """
#         return Users.get_count() > 0
# 
#     @staticmethod
#     def check_exists(username):
# 
#         """ Check if user with given username already exists """
# 
#         return Users.select()\
#                .where(Users.username == username)\
#                .exists()
# 
#     @staticmethod
#     def get_user(id):
#         """ Get user by id """
#         return Users.get_single("id", id)
# 
#     @staticmethod
#     def get_user_by_username(username):
# 
#         """ Get user by his username , returns 0 if not exists """
# 
#         return Users.get_single("username", username)
# 
#     @staticmethod
#     @db.commit_on_success
#     def create_user(username, password, description=None, real_name=None):
# 
#         """ Create new user """
# 
#         try:
#             return Users.create(username=username,
#                                 hash=generate_password_hash(password),
#                                 description=description,
#                                 real_name=real_name).get_id()
# 
#         except:
#             handle_errors("Error creating user")
#             raise
# 
#     def check_password(self, password):
# 
#         """ Compare password against the one in db """
# 
#         return check_password_hash(self.hash, password)
# 
#     def __repr__(self):
#         return "<User: %s>" % self.username
# 
#     class Meta:
#         order_by = ("username",)
# 
# Path: subrosa/models/UserProjectsModel.py
# class UserProjects(BaseModel):
# 
#     """
#     Models and methods related to projects
#     """
# 
#     title = CharField(unique=True)
#     body = TextField()
#     date_created = DateTimeField(default=datetime.now())
#     date_updated = DateTimeField(default=datetime.now())
#     author = ForeignKeyField(Users, related_name="projects")
# 
#     @staticmethod
#     def get_project(id):
#         """ Get project by id """
#         return UserProjects.get_single("id", id)
# 
#     @staticmethod
#     def get_all_projects():
#         """ Returns all projects or 0 if none exist"""
#         q = UserProjects.select()
#         if q.count():
#             return q
#         return 0
# 
#     @staticmethod
#     def check_exists(title, id=False):
#         """ Check if project with given title exists """
#         try:
#             q = UserProjects.select().where((UserProjects.title == title))
#             if not id:
#                 return q.get()
#             return q.where(UserProjects.id != id).get()
#         except:
#             return False
# 
#     @staticmethod
#     @db.commit_on_success
#     def create_project(title, body, author, **kwargs):
#         """
#         Create new project
#         Arguments:
#             :title (unicode) - title of the project
#             :body (unicode) - body of the project
#             :author (object) - object containing author info
# 
#         """
#         if len(title) > 255:
#             raise ValueError("Title must be at most 255 characters long")
#         try:
#             UserProjects.create(title=title,
#                                 body=body,
#                                 author=author)
#         except Exception as e:
#             handle_errors("error creating project")
#             raise
# 
#     @staticmethod
#     @db.commit_on_success
#     def delete_project(project):
#         """
#         Delete project
#         """
#         try:
#             project.delete_instance()
#             return 1
#         except Exception as e:
#             handle_errors("error deleting project")
#             raise
# 
#     @staticmethod
#     @db.commit_on_success
#     def update_project(project, title, body, **kwargs):
# 
#         """
#         Update project information
#         Arguments:
#             :project (object) - instance of project
#             :title (unicode) - new title
#             :body (unicode) - new body
#             """
# 
#         if len(title) > 255:
#             raise ValueError("Title must be at most 255 characters long")
#         try:
#             project.title = title
#             project.body = body
#             project.date_updated = datetime.now()
#             project.save()
#             return 1
#         except Exception as e:
#             handle_errors("error updating article")
#             raise
# 
#     def __repr__(self):
#         return "<Project: {0}>".format(self.title)
# 
#     class Meta:
#         order_by = ("-id",)


import unittest
from subrosa.models.UsersModel import Users
from subrosa.models.UserProjectsModel import UserProjects
from playhouse.test_utils import test_database
from peewee import *

db = SqliteDatabase(":memory:")

db._flag = "db1"


class TestProjectsMethods(unittest.TestCase):

    def test_creating_project(self):

        with test_database(db, (Users, UserProjects)):

            user1 = Users.create_user("konrad", "test")

            UserProjects.create_project(title = "test project", body = "test", author = user1)
            
            project = UserProjects.select().get()
            self.assertTrue(project)

            self.assertEquals("test project", project.title)
            self.assertEquals("konrad", project.author.username)

            UserProjects.create_project(title = "test project 2", body = "test", author = user1)
            self.assertTrue(UserProjects.check_exists("test project 2"))
            
            q = UserProjects.select()

            self.assertEquals(2, q.count())


# Path: subrosa/models/UsersModel.py
# class Users(BaseModel):
# 
#     """
#     Models and methods related to user database interaction
#     """
# 
#     username = CharField(max_length=40, unique=True, index=True)
#     hash = CharField()
#     real_name = CharField(max_length=40, null=True)
#     description = TextField(null=True)
#     about = TextField(null=True)
# 
#     @staticmethod
#     def check_any_exist():
#         """ Check if any users exist """
#         return Users.get_count() > 0
# 
#     @staticmethod
#     def check_exists(username):
# 
#         """ Check if user with given username already exists """
# 
#         return Users.select()\
#                .where(Users.username == username)\
#                .exists()
# 
#     @staticmethod
#     def get_user(id):
#         """ Get user by id """
#         return Users.get_single("id", id)
# 
#     @staticmethod
#     def get_user_by_username(username):
# 
#         """ Get user by his username , returns 0 if not exists """
# 
#         return Users.get_single("username", username)
# 
#     @staticmethod
#     @db.commit_on_success
#     def create_user(username, password, description=None, real_name=None):
# 
#         """ Create new user """
# 
#         try:
#             return Users.create(username=username,
#                                 hash=generate_password_hash(password),
#                                 description=description,
#                                 real_name=real_name).get_id()
# 
#         except:
#             handle_errors("Error creating user")
#             raise
# 
#     def check_password(self, password):
# 
#         """ Compare password against the one in db """
# 
#         return check_password_hash(self.hash, password)
# 
#     def __repr__(self):
#         return "<User: %s>" % self.username
# 
#     class Meta:
#         order_by = ("username",)
# 
# Path: subrosa/models/UserProjectsModel.py
# class UserProjects(BaseModel):
# 
#     """
#     Models and methods related to projects
#     """
# 
#     title = CharField(unique=True)
#     body = TextField()
#     date_created = DateTimeField(default=datetime.now())
#     date_updated = DateTimeField(default=datetime.now())
#     author = ForeignKeyField(Users, related_name="projects")
# 
#     @staticmethod
#     def get_project(id):
#         """ Get project by id """
#         return UserProjects.get_single("id", id)
# 
#     @staticmethod
#     def get_all_projects():
#         """ Returns all projects or 0 if none exist"""
#         q = UserProjects.select()
#         if q.count():
#             return q
#         return 0
# 
#     @staticmethod
#     def check_exists(title, id=False):
#         """ Check if project with given title exists """
#         try:
#             q = UserProjects.select().where((UserProjects.title == title))
#             if not id:
#                 return q.get()
#             return q.where(UserProjects.id != id).get()
#         except:
#             return False
# 
#     @staticmethod
#     @db.commit_on_success
#     def create_project(title, body, author, **kwargs):
#         """
#         Create new project
#         Arguments:
#             :title (unicode) - title of the project
#             :body (unicode) - body of the project
#             :author (object) - object containing author info
# 
#         """
#         if len(title) > 255:
#             raise ValueError("Title must be at most 255 characters long")
#         try:
#             UserProjects.create(title=title,
#                                 body=body,
#                                 author=author)
#         except Exception as e:
#             handle_errors("error creating project")
#             raise
# 
#     @staticmethod
#     @db.commit_on_success
#     def delete_project(project):
#         """
#         Delete project
#         """
#         try:
#             project.delete_instance()
#             return 1
#         except Exception as e:
#             handle_errors("error deleting project")
#             raise
# 
#     @staticmethod
#     @db.commit_on_success
#     def update_project(project, title, body, **kwargs):
# 
#         """
#         Update project information
#         Arguments:
#             :project (object) - instance of project
#             :title (unicode) - new title
#             :body (unicode) - new body
#             """
# 
#         if len(title) > 255:
#             raise ValueError("Title must be at most 255 characters long")
#         try:
#             project.title = title
#             project.body = body
#             project.date_updated = datetime.now()
#             project.save()
#             return 1
#         except Exception as e:
#             handle_errors("error updating article")
#             raise
# 
#     def __repr__(self):
#         return "<Project: {0}>".format(self.title)
# 
#     class Meta:
#         order_by = ("-id",)


# Path: subrosa/tests/test_projects.py
import unittest
from subrosa.models.UsersModel import Users
from subrosa.models.UserProjectsModel import UserProjects
from playhouse.test_utils import test_database
from peewee import *


db = SqliteDatabase(":memory:")

db._flag = "db1"


class TestProjectsMethods(unittest.TestCase):

    def test_creating_project(self):

        with test_database(db, (Users, UserProjects)):

            user1 = Users.create_user("konrad", "test")

            UserProjects.create_project(title = "test project", body = "test", author = user1)
            
            project = UserProjects.select().get()
            self.assertTrue(project)

            self.assertEquals("test project", project.title)
            self.assertEquals("konrad", project.author.username)

            UserProjects.create_project(title = "test project 2", body = "test", author = user1)
            self.assertTrue(UserProjects.check_exists("test project 2"))
            
            q = UserProjects.select()

            self.assertEquals(2, q.count())


            self.assertRaises(IntegrityError, lambda: UserProjects.create_project(title = "test project", body = "test", author = user1))