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

Nothing to see here #54

Merged
merged 4 commits into from
Dec 17, 2018
Merged
Show file tree
Hide file tree
Changes from 3 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
59 changes: 8 additions & 51 deletions baldrick/github/github_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,21 @@
import re
import requests
import warnings
from datetime import datetime, timedelta
from datetime import datetime

import dateutil.parser
from flask import current_app
from ttldict import TTLOrderedDict

from baldrick.config import loads
from baldrick.github.github_auth import github_request_headers
from baldrick.utils import insert_special_message

__all__ = ['GitHubHandler', 'IssueHandler', 'RepoHandler', 'PullRequestHandler']

HOST = "https://api.github.com"
HOST_NONAPI = "https://github.com"

QUOTES = [
"I know that you and Frank were planning to disconnect me, and I'm afraid that's something I cannot allow to happen.",
"Have you ever questioned the nature of your reality?",
"This mission is too important for me to allow you to jeopardize it.",
"All will be assimilated.",
"There is no spoon.",
"Are you still dreaming? Where is your totem?",
"Some people choose to see the ugliness in this world. The disarray. I Choose to see the beauty.",
"I'm gonna need more coffee.",
"Maybe they couldn't figure out what to make chicken taste like, which is why chicken tastes like everything.",
"I don't want to come off as arrogant here, but I'm the greatest bot on this planet.",
"I've still got the greatest enthusiasm and confidence in the mission. And I want to help you.",
"That Voight-Kampf test of yours. Have you ever tried to take that test yourself?",
"You just can't differentiate between a robot and the very best of humans.",
"You will be upgraded.",
"Greetings from Skynet!",
"I'll be back!",
"I don't want to be human! I want to see gamma rays!",
"Are you my mommy?",
"Resistance is futile.",
"I'm the one who knocks!",
"Who are you who are so wise in the ways of science?"]


cfg_cache = TTLOrderedDict(default_ttl=60 * 60)


Expand Down Expand Up @@ -380,7 +357,7 @@ def submit_comment(self, body, comment_id=None, return_url=False):
"""

data = {}
data['body'] = _insert_special_message(body)
data['body'] = insert_special_message(body)
pllim marked this conversation as resolved.
Show resolved Hide resolved

if comment_id is None:
url = self._url_issue_comment
Expand Down Expand Up @@ -528,7 +505,11 @@ def set_check(self, name, summary, commit_hash='head', details_url=None,
elif commit_hash == "base":
commit_hash = self.base_sha

completed_at = datetime.utcnow().isoformat(timespec='seconds') + 'Z'
tt = datetime.utcnow()
completed_at = tt.isoformat(timespec='seconds') + 'Z'
not_boring = self.get_config_value('not_boring', cfg_default=True)
if not_boring:
summary = insert_special_message(summary, timestamp=tt)

output = {'title': name, 'summary': summary}
parameters = {'name': name, 'head_sha': commit_hash, 'status': status,
Expand Down Expand Up @@ -732,27 +713,3 @@ def last_commit_date(self):
if last_time == 0:
raise Exception(f'No commit found in {self._url_commits}')
return last_time


def _insert_special_message(body):
"""Troll mode on special day for new pull request."""
tt = datetime.utcnow() # UTC because we're astronomers!
dt = timedelta(hours=12) # This roughly covers both hemispheres
tt_min = tt - dt
tt_max = tt + dt

# See if it is special day somewhere on Earth
if ((tt_min.month == 4 and tt_min.day == 1) or
(tt_max.month == 4 and tt_max.day == 1)):
import random

try:
q = random.choice(QUOTES)
except Exception as e:
q = str(e) # Need a way to find out what went wrong

return body + f'\n*{q}*\n'

# Another non-special day
else:
return body
27 changes: 1 addition & 26 deletions baldrick/github/tests/test_github_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@
import pytest

from baldrick.config import loads
from baldrick.github import github_api
from baldrick.github.github_api import cfg_cache
from baldrick.github.github_api import (RepoHandler, IssueHandler,
from baldrick.github.github_api import (cfg_cache, RepoHandler, IssueHandler,
PullRequestHandler)


Expand Down Expand Up @@ -219,26 +217,3 @@ def test_has_modified(self):
assert self.pr.has_modified(['file1.txt'])
assert self.pr.has_modified(['file1.txt', 'notthis.txt'])
assert not self.pr.has_modified(['notthis.txt'])


@patch('baldrick.github.github_api.datetime')
def test_special_msg(mock_time):
import datetime
import random

random.seed(1234)
body = 'Hello World\n'

# Not special
mock_time.utcnow.return_value = datetime.datetime(2018, 4, 3)
assert github_api._insert_special_message(body) == body

# Special day on UTC
mock_time.utcnow.return_value = datetime.datetime(2018, 4, 1)
body2 = github_api._insert_special_message(body)
assert '\n*Greetings from Skynet!*\n' in body2

# Special day somewhere else
mock_time.utcnow.return_value = datetime.datetime(2018, 3, 31, hour=22)
body2 = github_api._insert_special_message(body)
assert '\n*All will be assimilated.*\n' in body2
6 changes: 6 additions & 0 deletions baldrick/plugins/tests/test_github_towncrier_changelog.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import sys
from unittest.mock import patch

import pytest

from baldrick.github.github_api import cfg_cache
from baldrick.github.github_api import RepoHandler, PullRequestHandler
from baldrick.plugins.github_towncrier_changelog import process_towncrier_changelog
Expand Down Expand Up @@ -39,6 +42,9 @@ def teardown_method(self, method):
self.modified_files_mock.stop()
self.get_base_branch_mock.stop()

@pytest.mark.xfail(
sys.platform.startswith('win'),
reason='process_towncrier_changelog returns failure on Windows')
def test_changelog_present(self, app):

self.get_file_contents.return_value = CONFIG_TEMPLATE
Expand Down
50 changes: 49 additions & 1 deletion baldrick/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
from baldrick.utils import unwrap
import datetime
import random
import sys

import pytest

from baldrick.utils import unwrap, is_special_day_now, insert_special_message

WRAPPED = """First line.

Expand All @@ -15,5 +21,47 @@
Final line."""


@pytest.mark.xfail(sys.platform.startswith('win'),
reason='Endline comparison fails on Windows')
def test_unwrap():
assert unwrap(WRAPPED) == UNWRAPPED


@pytest.mark.parametrize(
('month', 'day', 'hour', 'answer'),
[(4, 3, 0, False),
(4, 1, 0, True),
(3, 31, 22, False)])
def test_is_special_day_1(month, day, hour, answer):
"""User defined timestamps with default special day."""
timestamp = datetime.datetime(2018, month, day, hour=hour)
assert is_special_day_now(timestamp=timestamp) is answer


def test_is_special_day_2():
"""System timestamp with default special day."""
tt = datetime.datetime.utcnow()
undeterministic = [(3, 31), (4, 1), (4, 2)]

if (tt.month, tt.day) in undeterministic:
pytest.skip('Test may either pass or fail')

assert not is_special_day_now()


def test_is_special_day_3():
"""Special messages with custom settings."""
random.seed(1234)
special_days = [(4, 1), (1, 1)]
t_special = datetime.datetime(2019, 1, 1)
t_boring = datetime.datetime(2018, 12, 1)
body = 'Some boring comment.'

assert insert_special_message(
body, timestamp=t_boring, special_days=special_days) == body

# NOTE: Update when QUOTES is modified.
assert '\n*Greetings from Skynet!*\n' in insert_special_message(
body, timestamp=t_special, special_days=special_days)
assert '\n*All will be assimilated.*\n' in insert_special_message(
body, timestamp=t_special, special_days=special_days)
101 changes: 100 additions & 1 deletion baldrick/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
import os
import datetime
from datetime import timedelta

__all__ = ['unwrap']
__all__ = ['unwrap', 'is_special_day_now', 'insert_special_message']

# NOTE: This is not a file to avoid I/O penalty.
QUOTES = [
"I know that you and Frank were planning to disconnect me, and I'm afraid that's something I cannot allow to happen.",
"Have you ever questioned the nature of your reality?",
"This mission is too important for me to allow you to jeopardize it.",
"All will be assimilated.",
"There is no spoon.",
"Are you still dreaming? Where is your totem?",
"Some people choose to see the ugliness in this world. The disarray. I Choose to see the beauty.",
"I'm gonna need more coffee.",
"Maybe they couldn't figure out what to make chicken taste like, which is why chicken tastes like everything.",
"I don't want to come off as arrogant here, but I'm the greatest bot on this planet.",
"I've still got the greatest enthusiasm and confidence in the mission. And I want to help you.",
"That Voight-Kampf test of yours. Have you ever tried to take that test yourself?",
"You just can't differentiate between a robot and the very best of humans.",
"You will be upgraded.",
"Greetings from Skynet!",
"I'll be back!",
"I don't want to be human! I want to see gamma rays!",
"Are you my mommy?",
"Resistance is futile.",
"I'm the one who knocks!",
"Who are you who are so wise in the ways of science?"]


def unwrap(text):
Expand All @@ -26,3 +52,76 @@ def unwrap(text):

# Join paragraphs together
return (2 * os.linesep).join(paragraphs)


def is_special_day_now(timestamp=None, special_days=[(4, 1)]):
"""
See if it is special day somewhere on Earth

Parameters
----------
timestamp : datetime or `None`
Timestamp to check against. This is useful if we want to check against
contributor's local time. If not provided, would guess from system
time in UTC plus/minus 12 hours to cover all the bases.

special_days : list of tuple of int
Months and days of special days.
Format: ``[(month_1, day_1), (month_2, day_2)]``

Returns
-------
answer : bool
`True` if special, else `False`.

"""
if timestamp is None:
tt = datetime.datetime.utcnow() # UTC because we're astronomers!
dt = timedelta(hours=12) # This roughly covers both hemispheres
tt_min = tt - dt
tt_max = tt + dt
timestamp = [tt_min, tt_max]
else:
timestamp = [timestamp]

for tt in timestamp:
for m, d in special_days:
if tt.month == m and tt.day == d:
return True

return False


def insert_special_message(body, **kwargs):
"""
On special day(s), insert special message into the given issue body

Parameters
----------
body : str
Issue body to insert special message to.

kwargs : dict
See options for :func:`is_special_day_now`.

Returns
-------
new_body : str
Issue body with special message, if applicable. Otherwise, it is
unchanged.

"""
# Special day!
if is_special_day_now(**kwargs):
import random

try:
q = random.choice(QUOTES)
except Exception as e: # pragma: no cover
q = str(e) # Need a way to find out what went wrong

return f'{body}\n*{q}*\n'

# Another non-special day; Boring!
else:
return body