Skip to content

Instantly share code, notes, and snippets.

@invalidusrname
Last active October 29, 2019 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save invalidusrname/ca9865c98ab7ad3a6b62d806369b5a4f to your computer and use it in GitHub Desktop.
Save invalidusrname/ca9865c98ab7ad3a6b62d806369b5a4f to your computer and use it in GitHub Desktop.
Entites and Repositories
import pytest
import json
# ---------------------------- #
# lib/entities/entity.py
# ---------------------------- #
class Entity(object):
FIELDS = []
def __init__(self, data = {}):
self.attributes = {}
for key in self.FIELDS:
self.attributes[key] = None
for key in data:
if key in self.FIELDS:
self.attributes[key] = data[key]
def __getattr__(self, name):
if name in self.attributes:
return self.attributes[name]
else:
raise AttributeError, name
# ---------------------------- #
# lib/entities/job_post_entity.py
# ---------------------------- #
from .entity import Entity
class JobPostEntity(Entity):
FIELDS = [
'description',
'job_type',
]
# ---------------------------- #
# lib/repository/repository.py
# ---------------------------- #
class Repository:
def __init__(self, database):
self.database = database
def add(self, entity):
raise NotImplementedError
def remove(self, entity):
raise NotImplementedError
def get(self, id):
raise NotImplementedError
def find(self):
raise NotImplementedError
def exists(self, id):
raise NotImplementedError
# ---------------------------- #
# lib/repository/job_post_repository.py
# ---------------------------- #
from .repository import Repository
from ..entity.job_post_entity import JobPostEntity
class JobPostRepository(Repository):
def get(self, id):
sql = "SELECT * FROM job_posts WHERE id = %s"
self.database.execute(sql, (id, ))
data = self.database.fetch_as_dict()
if data:
attributes = {}
attributes['description'] = data['description']
attributes['job_type'] = data['job_type']
return JobPostEntity(attributes)
def add(self, job_post):
if self.exists(job_post.id):
self.update_job_post(job_post)
else:
self.insert_job_post(job_post)
class TestEntity():
def test_first_name(self):
entity = Entity(data = {"first_name": "James"})
assert entity.first_name == "James"
def test_last_name(self):
entity = Entity(data = {"last_name": "Bond"})
assert entity.last_name == "Bond"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment