Skip to content

Commit

Permalink
Wrote docstrings to all functions and modules
Browse files Browse the repository at this point in the history
  • Loading branch information
vmagueta committed Jul 1, 2024
1 parent b986909 commit b9407d6
Show file tree
Hide file tree
Showing 23 changed files with 105 additions and 22 deletions.
31 changes: 28 additions & 3 deletions assets/database.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
}
},
"balance": {
"[email protected]": 810,
"[email protected]": 410,
"[email protected]": 100
"[email protected]": 653,
"[email protected]": 253,
"[email protected]": 200
},
"movement": {
"[email protected]": [
Expand Down Expand Up @@ -62,6 +62,16 @@
"date": "2024-07-01T09:47:47.852407",
"actor": "solermvictor",
"value": 5
},
{
"date": "2024-07-01T10:28:44.587618",
"actor": "solermvictor",
"value": -257
},
{
"date": "2024-07-01T10:29:00.532653",
"actor": "solermvictor",
"value": 100
}
],
"[email protected]": [
Expand Down Expand Up @@ -104,13 +114,28 @@
"date": "2024-07-01T09:47:47.852421",
"actor": "solermvictor",
"value": 5
},
{
"date": "2024-07-01T10:28:44.587632",
"actor": "solermvictor",
"value": -257
},
{
"date": "2024-07-01T10:29:00.532668",
"actor": "solermvictor",
"value": 100
}
],
"[email protected]": [
{
"date": "2024-06-30T13:17:00.086294",
"actor": "system",
"value": 100
},
{
"date": "2024-07-01T10:28:22.353956",
"actor": "solermvictor",
"value": 100
}
]
},
Expand Down
8 changes: 5 additions & 3 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Configuration of Pytest for the tests of dundie functions."""

import pytest
from unittest.mock import patch

Expand All @@ -12,22 +14,22 @@


def pytest_configure(config):
"""Configure the marker for functions."""
for line in MARKER.split("\n"):
config.addinivalue_line("markers", line)


@pytest.fixture(autouse=True)
def go_to_tmpdir(request): # injeção de dependencias
"""Configure to tests run in temporary directory."""
tmpdir = request.getfixturevalue("tmpdir")
with tmpdir.as_cwd():
yield # protocolo de generators


@pytest.fixture(autouse=True, scope="function")
def setup_testing_database(request):
"""For each test, create a database file on tmpdir
force database.py to use that filepath.
"""
"""For each test, create a db on tmpdir forcing to use that filepath."""
tmpdir = request.getfixturevalue("tmpdir")
test_db = str(tmpdir.join("database.test.json"))
with patch("dundie.database.DATABASE_PATH", test_db):
Expand Down
1 change: 1 addition & 0 deletions dundie/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Entry point of Dundie module."""
2 changes: 2 additions & 0 deletions dundie/__main__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Main of Dundie module."""

from dundie.cli import main

if __name__ == "__main__":
Expand Down
14 changes: 10 additions & 4 deletions dundie/cli.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Main commands for dundie in command line interface."""

import json
from importlib import metadata

Expand All @@ -21,13 +23,17 @@ def main():
"""Dunder Mifflin Rewards System.
This CLI application controls Dunder Mifflin Rewards.
- admins can load information to the people database and assign points.
- users can view and transfer points.
"""


@main.command()
@click.argument("filepath", type=click.Path(exists=True))
def load(filepath):
"""Loads the file to the database.
"""Load the file to the database.
## Features
Expand All @@ -53,7 +59,7 @@ def load(filepath):
@click.option("--email", required=False)
@click.option("--output", default=None)
def show(output, **query):
"""Shows information about users."""
"""Show information about users od dept."""
result = core.read(**query)
if output:
with open(output, "w") as output_file:
Expand All @@ -79,7 +85,7 @@ def show(output, **query):
@click.option("--email", required=False)
@click.pass_context
def add(ctx, value, **query):
"""Add points to the user or dept"""
"""Add points to the user or dept."""
core.add(value, **query)
ctx.invoke(show, **query)

Expand All @@ -90,6 +96,6 @@ def add(ctx, value, **query):
@click.option("--email", required=False)
@click.pass_context
def remove(ctx, value, **query):
"""Remove points to the user or dept"""
"""Remove points to the user or dept."""
core.add(-value, **query)
ctx.invoke(show, **query)
6 changes: 3 additions & 3 deletions dundie/core.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Core module of dundie"""
"""Core module of dundie."""

import os
from csv import reader
Expand All @@ -10,7 +10,7 @@


def load(filepath):
"""Loads data from filepath to the database.
"""Load data from filepath to the database.
>>> len(load('assets/people.csv'))
2
Expand Down Expand Up @@ -39,7 +39,7 @@ def load(filepath):


def read(**query):
"""Read data from db and filters using query
"""Read data from db and filters using query.
read(email="[email protected]")
"""
Expand Down
14 changes: 11 additions & 3 deletions dundie/database.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Main functions to access, commit and make alterations into the database."""

import json
from datetime import datetime

Expand All @@ -9,7 +11,7 @@


def connect() -> dict:
"""Connects to the database, returns dict data."""
"""Connect to the database, returns dict data."""
try:
with open(DATABASE_PATH, "r") as database_file:
return json.loads(database_file.read())
Expand All @@ -27,7 +29,7 @@ def commit(db):


def add_person(db, pk, data):
"""Saves person data to database.
"""Save person data to database.
- E-mail is unique (resolved by dictonary hash table)
- If exists, update, else create
Expand All @@ -51,7 +53,7 @@ def add_person(db, pk, data):


def set_initial_password(db, pk):
"""Generates and saves password."""
"""Generate and save password."""
db["users"].setdefault(pk, {})
db["users"][pk]["password"] = generate_simple_password(8)
return db["users"][pk]["password"]
Expand All @@ -64,6 +66,12 @@ def set_initial_balance(db, pk, person):


def add_movement(db, pk, value, actor="system"):
"""Add movement to user account.
Example::
add_movement(db, "[email protected]", 100, "me")
"""
movements = db["movement"].setdefault(pk, [])
movements.append(
{"date": datetime.now().isoformat(), "actor": actor, "value": value}
Expand Down
2 changes: 2 additions & 0 deletions dundie/settings.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Settings for e-mail, SMTP and paths to functions in the module Dundie."""

import os

SMTP_HOST = "Localhost"
Expand Down
1 change: 1 addition & 0 deletions dundie/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Initialization of utils module of dundie module."""
4 changes: 3 additions & 1 deletion dundie/utils/email.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Functions that check and send an email to the user."""

import re
import smtplib
from email.mime.text import MIMEText
Expand All @@ -16,7 +18,7 @@ def check_valid_email(address):


def send_email(from_, to, subject, text):
"""Sends an email to the colaborator"""
"""Send an email to the colaborator."""
if not isinstance(to, list):
to = [to]

Expand Down
4 changes: 3 additions & 1 deletion dundie/utils/log.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Configuration of the log."""

import logging
import os
from logging import handlers
Expand All @@ -11,7 +13,7 @@


def get_logger(logfile="dundie.log"):
"""Returns a configured logger."""
"""Return a configured logger."""
# ch = logging.StreamHandler() # Console/terminal/stderr
# ch.setLevel(log_level)
fh = handlers.RotatingFileHandler(
Expand Down
5 changes: 4 additions & 1 deletion dundie/utils/user.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
"""Function that generates password for the user."""

from random import sample
from string import ascii_letters, digits


def generate_simple_password(size=8):
"""Generate a simple random password
"""Generate a simple random password.
[A-Z][a-z][0-9]
"""
password = sample(ascii_letters + digits, size)
Expand Down
1 change: 1 addition & 0 deletions integration/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Entry point of integration tests module."""
2 changes: 2 additions & 0 deletions integration/constants.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Constants paths used on the dundie's integration tests."""

import os

TEST_PATH = os.path.dirname(__file__)
Expand Down
6 changes: 4 additions & 2 deletions integration/test_load.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Tests the command in terminal as user."""

import pytest
from click.testing import CliRunner

Expand All @@ -11,7 +13,7 @@
@pytest.mark.integration
@pytest.mark.medium
def test_load_positive_call_load_command():
"""Test command load"""
"""Test command load."""
out = cmd.invoke(load, PEOPLE_FILE)
assert "Dunder Mifflin Associates" in out.output

Expand All @@ -20,7 +22,7 @@ def test_load_positive_call_load_command():
@pytest.mark.medium
@pytest.mark.parametrize("wrong_command", ["loady", "carrega", "start"])
def test_load_negative_call_load_command_with_wrong_params(wrong_command):
"""Test command load"""
"""Test command load."""
out = cmd.invoke(main, wrong_command, PEOPLE_FILE)
assert out.exit_code != 0
assert f"No such command '{wrong_command}'" in out.output
3 changes: 3 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
"""Setup for dundie."""

import os
from setuptools import setup, find_packages


def read(*paths):
"""Read the contents of a text file safely.
>>> read("dundie", "VERSION")
'0.1.0'
>>> read("README.md")
Expand Down
1 change: 1 addition & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Entry point of unit tests module."""
2 changes: 2 additions & 0 deletions tests/constants.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Constants paths used on dundie's unit tests."""

import os

TEST_PATH = os.path.dirname(__file__)
Expand Down
3 changes: 3 additions & 0 deletions tests/test_add.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Tests the function add."""

import pytest

from dundie.core import add
Expand All @@ -6,6 +8,7 @@

@pytest.mark.unit
def test_add_movement():
"""Add two person into the db, and tests movements into the balance."""
db = connect()

pk = "[email protected]"
Expand Down
7 changes: 7 additions & 0 deletions tests/test_database.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
"""Tests the database."""

import pytest

from dundie.database import EMPTY_DB, add_movement, add_person, commit, connect


@pytest.mark.unit
def test_database_schema():
"""Test the schema of database."""
db = connect()
assert db.keys() == EMPTY_DB.keys()


@pytest.mark.unit
def test_commit_to_database():
"""Test the function commit to the database."""
db = connect()
data = {"name": "Joe Doe", "role": "Salesman", "dept": "Sales"}
db["people"]["[email protected]"] = data
Expand All @@ -22,6 +26,7 @@ def test_commit_to_database():

@pytest.mark.unit
def test_add_person_for_the_first_time():
"""Test the add person to the db for the first time."""
pk = "[email protected]"
data = {"role": "Salesman", "dept": "Sales", "name": "Joe Doe"}
db = connect()
Expand All @@ -38,12 +43,14 @@ def test_add_person_for_the_first_time():

@pytest.mark.unit
def test_negative_add_person_invalid_email():
"""Test if invalid email is going to raise a Value Error."""
with pytest.raises(ValueError):
add_person({}, ".@bla", {})


@pytest.mark.unit
def test_add_or_remove_points_for_person():
"""Test add two persons and add and remove points of them."""
pk = "[email protected]"
data = {"role": "Salesman", "dept": "Sales", "name": "Joe Doe"}
db = connect()
Expand Down
2 changes: 2 additions & 0 deletions tests/test_load.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Test the function load of dundie."""

import pytest

from dundie.core import load
Expand Down
Loading

0 comments on commit b9407d6

Please sign in to comment.