Skip to content

Commit

Permalink
Merge pull request #2 from PabloLec/dev
Browse files Browse the repository at this point in the history
Version 0.0.3
  • Loading branch information
PabloLec authored Oct 2, 2021
2 parents 58c27e1 + 6c6d428 commit 7105125
Show file tree
Hide file tree
Showing 12 changed files with 604 additions and 18 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/linux-tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Linux

on: [push, pull_request]

jobs:
pytests:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.6, 3.7, 3.8, 3.9]

steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v1
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install --upgrade pip
pip install .
pip install pytest
pip install -r requirements.txt
- name: Run unit tests
run: |
pytest -v
28 changes: 28 additions & 0 deletions .github/workflows/macos-tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: macOS

on: [push, pull_request]

jobs:
pytests:
runs-on: macOS-latest
strategy:
matrix:
python-version: [3.6, 3.7, 3.8, 3.9]

steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v1
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install --upgrade pip
pip install .
pip install pytest
pip install -r requirements.txt
- name: Run unit tests
run: |
mkdir ~/testfolder
sudo chmod -R u-rwx ~/testfolder
pytest -v
26 changes: 26 additions & 0 deletions .github/workflows/windows-tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Windows

on: [push, pull_request]

jobs:
pytest:
runs-on: windows-latest
strategy:
matrix:
python-version: [3.6, 3.7, 3.8, 3.9]

steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v1
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install --upgrade pip
pip install .
pip install pytest
pip install -r requirements.txt
- name: Run unit tests
run: |
pytest -v
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# livelog

Work in progress
[![Linux](https://github.com/PabloLec/livelog/actions/workflows/linux-tests.yml/badge.svg)](https://github.com/PabloLec/livelog/actions/workflows/linux-tests.yml)[![macOS](https://github.com/PabloLec/livelog/actions/workflows/macos-tests.yml/badge.svg)](https://github.com/PabloLec/livelog/actions/workflows/macos-tests.yml)[![Windows](https://github.com/PabloLec/livelog/actions/workflows/windows-tests.yml/badge.svg)](https://github.com/PabloLec/livelog/actions/workflows/windows-tests.yml)
4 changes: 2 additions & 2 deletions livelog/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ def _parse_args():
args = parser.parse_args()

if args.file is not None:
file = Path(args.file)
file = Path(args.file).resolve()
else:
file = (
Path("/tmp/livelog.log")
if system() == "Darwin"
if "darwin" in system().lower()
else Path(gettempdir()) / "livelog.log"
)

Expand Down
13 changes: 8 additions & 5 deletions livelog/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def __init__(
if file is None:
self._file = Path(
"/tmp/livelog.log"
if system() == "Darwin"
if "darwin" in system().lower()
else Path(gettempdir()) / "livelog.log"
)
else:
Expand Down Expand Up @@ -95,10 +95,13 @@ def _verify_file(self):
"""

dir = self._file.parent.resolve()
if self._file.is_dir():
raise LogFileIsADirectory(path=self._file)
if not dir.is_dir():
raise LogPathDoesNotExist(path=dir)
try:
if self._file.is_dir():
raise LogFileIsADirectory(path=self._file)
if not dir.is_dir():
raise LogPathDoesNotExist(path=dir)
except PermissionError:
raise LogPathInsufficientPermissions(path=dir)
if not access(dir, X_OK):
raise LogPathInsufficientPermissions(path=dir)
self._clear_file()
Expand Down
45 changes: 35 additions & 10 deletions livelog/reader.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-

from os import system, access, name, R_OK
from os import getenv, system, access, R_OK
from sys import exit as _exit
from platform import system as system_
from time import sleep
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
Expand Down Expand Up @@ -29,7 +31,12 @@ class Reader(FileSystemEventHandler):
write to output path
"""

CLEAR_CMD = "cls" if name == "nt" else "clear"
if getenv("LIVELOG_ENV") == "TEST":
CLEAR_CMD = ""
elif "windows" in system_().lower():
CLEAR_CMD = "cls"
else:
CLEAR_CMD = "clear"
LEVEL_COLORS = {
"ERR!": Fore.RED,
"WARN": Fore.YELLOW,
Expand All @@ -38,7 +45,7 @@ class Reader(FileSystemEventHandler):
}
LONG_LEVEL_TO_SHORT = {
"ERROR": "ERR!",
"WARN": "WARNING",
"WARNING": "WARN",
"INFO": "INFO",
"DEBUG": "DBUG",
}
Expand Down Expand Up @@ -69,6 +76,9 @@ def __init__(self, file: str, level: str, nocolors: bool):
self.read_index = 0

system(self.CLEAR_CMD)
if not self.file_exists() and getenv("LIVELOG_ENV") == "TEST":
print("FILE NOT FOUND:", self.file)
_exit()
while not self.file_exists():
print("File not found, waiting for creation.")
sleep(1)
Expand All @@ -80,10 +90,13 @@ def verify_file(self):
"""Verify if provided file path is a valid log file."""

dir = self.file.parent.resolve()
if self.file.is_dir():
raise LogFileIsADirectory(path=self.file)
if not dir.is_dir():
raise LogPathDoesNotExist(path=dir)
try:
if self.file.is_dir():
raise LogFileIsADirectory(path=self.file)
if not dir.is_dir():
raise LogPathDoesNotExist(path=dir)
except PermissionError:
raise LogPathInsufficientPermissions(path=dir)
if not access(dir, R_OK):
raise LogPathInsufficientPermissions(path=dir)

Expand Down Expand Up @@ -148,10 +161,14 @@ def filter_log_level(self, lines: list):
list: Filtered lines
"""

for i, line in enumerate(lines):
level = line[:4]
i = 0
for _ in range(len(lines)):
level = lines[i][:4]
if self.LEVELS[self.level] > self.LEVELS[level]:
del lines[i]
continue
i += 1

return lines

def color_line(self, line: str):
Expand Down Expand Up @@ -180,6 +197,10 @@ def on_modified(self, *args, **kwargs):
def loop_without_event(self):
"""If inotify instance limit reached, loop without watching file."""

if getenv("LIVELOG_ENV") == "TEST":
self.print_output()
_exit()

while True:
self.print_output()
sleep(1)
Expand All @@ -199,7 +220,11 @@ def start_reader(file: str, level: str, nocolors: bool):
observer.schedule(event_handler, file, recursive=True)
try:
observer.start()
input("")
if getenv("LIVELOG_ENV") == "TEST":
sleep(2)
_exit()
else:
input("")
observer.stop()
observer.join()
except OSError:
Expand Down
3 changes: 3 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from os import environ

environ["LIVELOG_ENV"] = "TEST"
41 changes: 41 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import pytest
from os import getenv
from pathlib import Path
from livelog import Logger
from platform import system


@pytest.fixture(scope="session")
def restricted_dir():
if "darwin" in system().lower():
return getenv("HOME") + "/testfolder/"
else:
return "/root/"


@pytest.fixture(scope="session")
def system_is_windows():
return "windows" in system().lower()


@pytest.fixture(scope="session")
def log_file(tmpdir_factory):
return tmpdir_factory.mktemp("tmp").join("test.log")


@pytest.fixture(scope="function")
def default_log_file():
logger = Logger()
logger.debug("It works!")


@pytest.fixture(scope="function")
def reader_test_file(tmpdir_factory):
log_file = tmpdir_factory.mktemp("tmp").join("test.log")
logger = Logger(file=log_file)
logger.debug("debug")
logger.info("info")
logger.warn("warning")
logger.error("error")

return Path(log_file)
39 changes: 39 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from subprocess import Popen, PIPE


def test_default(default_log_file):
print("python3 -m livelog".split())
process = Popen("python3 -m livelog".split(), stdout=PIPE)
out, _ = process.communicate()
assert "It works" in str(out)


def test_custom_file(reader_test_file):
process = Popen(
f"python3 -m livelog -f {reader_test_file}".split(),
stdout=PIPE,
)
out, _ = process.communicate()
assert "debug" in str(out)


def test_nocolors(reader_test_file):
process = Popen(
f"python3 -m livelog -f {reader_test_file} --nocolors".split(),
stdout=PIPE,
)
out, _ = process.communicate()
assert "DBUG" in str(out)
assert "INFO" in str(out)
assert "WARN" in str(out)
assert "ERR!" in str(out)


def test_custom_level(reader_test_file):
process = Popen(
f"python3 -m livelog -f {reader_test_file} --level=INFO --nocolors".split(),
stdout=PIPE,
)
out, _ = process.communicate()
assert "INFO" in str(out)
assert "DBUG" not in str(out)
Loading

0 comments on commit 7105125

Please sign in to comment.