Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add group syntax logging for CI #228

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions lockable/lockable.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ def invariant(true, message):
raise ResourceNotFound(message)


def log_with_group(logger, title, message):
""" Log message with group syntax if running in GitHub Actions """
if os.getenv('CI') == 'true' and os.getenv('GITHUB_ACTIONS') == 'true':
print(f"::group::{title}")
logger.info(message)
print("::endgroup::")
else:
logger.info(message)


class Lockable:
"""
Base class for Lockable. It handle low-level functionality.
Expand Down
8 changes: 4 additions & 4 deletions lockable/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from typing import List

from pydash import filter_, count_by
from lockable.lockable import log_with_group

MODULE_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -36,9 +37,8 @@ def set_resources_list(self, resources_list: list):
assert isinstance(resources_list, list), 'resources_list is not an list'
Provider._validate_json(resources_list)
self._resources = resources_list
MODULE_LOGGER.debug('Resources loaded: ')
for resource in self._resources:
MODULE_LOGGER.debug(json.dumps(resource))

log_with_group(MODULE_LOGGER, 'Resources loaded:', json.dumps(self._resources, indent=2))

@staticmethod
def _validate_json(data: List[dict]):
Expand All @@ -50,5 +50,5 @@ def _validate_json(data: List[dict]):

duplicates = filter_(counts.keys(), lambda key: counts[key] > 1)
if duplicates:
MODULE_LOGGER.warning('Duplicates: %s', duplicates)
log_with_group(MODULE_LOGGER, f'Duplicates: {duplicates}')
raise ValueError(f"Invalid json, duplicate ids in {duplicates}")
35 changes: 34 additions & 1 deletion tests/test_Lockable.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
from contextlib import contextmanager
from tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import patch
from io import StringIO

from lockable.lockable import Lockable, ResourceNotFound, Allocation
from lockable.lockable import Lockable, ResourceNotFound, Allocation, log_with_group


@contextmanager
Expand Down Expand Up @@ -280,3 +282,34 @@ def test_lock_many_existing_allocation(self):
self.assertTrue(end - start < 2 and end - start > 1)
self.assertTrue(os.path.exists(os.path.join(tmpdirname, 'a.pid')))
self.assertFalse(os.path.exists(os.path.join(tmpdirname, 'b.pid')))

def test_log_with_group(self):
logger = logging.getLogger('test_logger')
logger.setLevel(logging.INFO)
log_output = []

def mock_info(message):
log_output.append(message)

logger.info = mock_info

os.environ['CI'] = 'true'
os.environ['GITHUB_ACTIONS'] = 'true'

with patch('sys.stdout', new=StringIO()) as fake_out:
log_with_group(logger, "Test Group", "Test message")
self.assertIn("::group::Test Group", fake_out.getvalue())
self.assertIn("::endgroup::", fake_out.getvalue())

self.assertEqual(log_output, ["Test message"])

os.environ['CI'] = 'false'
os.environ['GITHUB_ACTIONS'] = 'false'

log_output.clear()
with patch('sys.stdout', new=StringIO()) as fake_out:
log_with_group(logger, "Test Group", "Test message")
self.assertNotIn("::group::Test Group", fake_out.getvalue())
self.assertNotIn("::endgroup::", fake_out.getvalue())

self.assertEqual(log_output, ["Test message"])