Skip to content

Commit

Permalink
test: remove test code related to creating/updating labels in repos
Browse files Browse the repository at this point in the history
  • Loading branch information
Ned Batchelder authored and nedbat committed Jul 25, 2023
1 parent d11d9bd commit 8e5f2b8
Show file tree
Hide file tree
Showing 5 changed files with 10 additions and 205 deletions.
2 changes: 0 additions & 2 deletions openedx_webhooks/tasks/github_work.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from typing import Any, Dict

from openedx_webhooks.auth import get_github_session
from openedx_webhooks.tasks import logger
from openedx_webhooks.utils import paginated_get


Expand All @@ -14,4 +13,3 @@ def get_repo_labels(repo: str) -> Dict[str, Dict[str, Any]]:
url = f"/repos/{repo}/labels"
repo_labels = {lbl["name"]: lbl for lbl in paginated_get(url, session=get_github_session())}
return repo_labels

1 change: 0 additions & 1 deletion openedx_webhooks/tasks/pr_tracking.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@
from openedx_webhooks.auth import get_github_session, get_jira_session
from openedx_webhooks.lib.github.models import PrId
from openedx_webhooks.tasks import logger
from openedx_webhooks.tasks import github_work
from openedx_webhooks.tasks.jira_work import (
delete_jira_issue,
transition_jira_issue,
Expand Down
72 changes: 2 additions & 70 deletions tests/fake_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@
import datetime
import itertools
import random
import re
from dataclasses import dataclass, field
from typing import Any, Dict, Iterable, List, Optional, Set
from urllib.parse import unquote

from openedx_webhooks.cla_check import CLA_CONTEXT
from openedx_webhooks.types import GhProject
Expand All @@ -22,26 +20,14 @@


class FakeGitHubException(faker.FakerException):
def __init__(self, message, errors=None):
super().__init__(message)
self.errors = errors

def as_json(self) -> Dict:
j = {"message": str(self)}
if self.errors:
j["errors"] = self.errors
return j

class DoesNotExist(FakeGitHubException):
"""A requested object does not exist."""
status_code = 404

class ValidationError(FakeGitHubException):
status_code = 422

def __init__(self, message="Validation Failed", **kwargs):
super().__init__(message=message, errors=[kwargs])

def fake_sha():
"""A realistic stand-in for a commit sha."""
return "".join(random.choice("0123456789abcdef") for c in range(32))
Expand Down Expand Up @@ -72,10 +58,6 @@ class Label:
color: Optional[str] = "ededed"
description: Optional[str] = None

def __post_init__(self):
if self.color is not None and not re.fullmatch(r"[0-9a-fA-F]{6}", self.color):
raise ValidationError(resource="Label", code="invalid", field="color")

def as_json(self):
return dataclasses.asdict(self)

Expand Down Expand Up @@ -272,33 +254,16 @@ def get_label(self, name: str) -> Label:
def has_label(self, name: str) -> bool:
return name in self.labels

def set_labels(self, data: List[Dict]) -> None:
def _set_labels(self, data: List[Dict]) -> None:
self.labels = {}
for kwargs in data:
self.add_label(**kwargs)

def get_labels(self) -> List[Label]:
return sorted(self.labels.values(), key=lambda l: l.name)

def add_label(self, **kwargs) -> Label:
label = Label(**kwargs)
if label.name in self.labels:
raise ValidationError(resource="Label", code="already_exists", field="name")
self.labels[label.name] = label
return label

def update_label(self, name: str, **kwargs) -> Label:
label = self.get_label(name)
new_label = dataclasses.replace(label, **kwargs)
self.labels[name] = new_label
return new_label

def delete_label(self, name: str) -> None:
try:
del self.labels[name]
except KeyError:
raise DoesNotExist(f"Label {self.full_name} {name!r} does not exist")


class Flaky404:
"""
Expand Down Expand Up @@ -361,7 +326,7 @@ def get_user(self, login: str, create: bool = False) -> User:

def make_repo(self, owner: str, repo: str, private: bool=False) -> Repo:
r = Repo(self, owner, repo, private)
r.set_labels(DEFAULT_LABELS)
r._set_labels(DEFAULT_LABELS)
self.repos[f"{owner}/{repo}"] = r
return r

Expand Down Expand Up @@ -446,39 +411,6 @@ def _post_pr_status_update(self, match, request, _context) -> List[Dict[str, Any
self.cla_statuses[match['sha']] = data
return [data]

# Repo labels

@faker.route(r"/repos/(?P<owner>[^/]+)/(?P<repo>[^/]+)/labels")
def _get_labels(self, match, _request, _context) -> List[Dict]:
# https://developer.github.com/v3/issues/labels/#list-labels-for-a-repository
r = self.get_repo(match["owner"], match["repo"])
return [label.as_json() for label in r.labels.values()]

@faker.route(r"/repos/(?P<owner>[^/]+)/(?P<repo>[^/]+)/labels", "POST")
def _post_labels(self, match, request, context) -> Dict:
# https://developer.github.com/v3/issues/labels/#create-a-label
r = self.get_repo(match["owner"], match["repo"])
label = r.add_label(**request.json())
context.status_code = 201
return label.as_json()

@faker.route(r"/repos/(?P<owner>[^/]+)/(?P<repo>[^/]+)/labels/(?P<name>.*)", "PATCH")
def _patch_labels(self, match, request, _context) -> Dict:
# https://developer.github.com/v3/issues/labels/#update-a-label
r = self.get_repo(match["owner"], match["repo"])
data = request.json()
if "name" in data:
data.pop("name")
label = r.update_label(unquote(match["name"]), **data)
return label.as_json()

@faker.route(r"/repos/(?P<owner>[^/]+)/(?P<repo>[^/]+)/labels/(?P<name>.*)", "DELETE")
def _delete_labels(self, match, _request, context) -> None:
# https://developer.github.com/v3/issues/labels/#delete-a-label
r = self.get_repo(match["owner"], match["repo"])
r.delete_label(unquote(match["name"]))
context.status_code = 204

# Comments

@faker.route(r"/repos/(?P<owner>[^/]+)/(?P<repo>[^/]+)/issues/(?P<number>\d+)/comments(\?.*)?")
Expand Down
6 changes: 1 addition & 5 deletions tests/test_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,11 @@

import pathlib

from repo_tools_data_schema import validate_labels, validate_orgs, validate_people
from repo_tools_data_schema import validate_orgs, validate_people

TEST_DATA_DIR = pathlib.Path(__file__).parent / "repo_data" / "openedx" / "openedx-webhooks-data"


def test_labels_yaml():
validate_labels(TEST_DATA_DIR / "labels.yaml")


def test_orgs_yaml():
validate_orgs(TEST_DATA_DIR / "orgs.yaml")

Expand Down
134 changes: 7 additions & 127 deletions tests/test_fake_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from freezegun import freeze_time
from glom import glom

from .fake_github import DoesNotExist, FakeGitHub
from .fake_github import FakeGitHub


# pylint: disable=missing-timeout
Expand Down Expand Up @@ -37,128 +37,6 @@ def test_make_repo(self, fake_github):
assert repo == repo2


class TestRepoLabels:
def test_get_default_labels(self, fake_github):
fake_github.make_repo("an-org", "a-repo")
resp = requests.get("https://api.github.com/repos/an-org/a-repo/labels")
assert resp.status_code == 200
labels = resp.json()
assert isinstance(labels, list)
assert len(labels) == 9
assert {"name": "invalid", "color": "e4e669", "description": "This doesn't seem right"} in labels

def test_create_label(self, fake_github):
repo = fake_github.make_repo("an-org", "a-repo")
# At first, the label doesn't exist.
with pytest.raises(DoesNotExist):
repo.get_label("nice")
# We make a label with the API.
resp = requests.post(
"https://api.github.com/repos/an-org/a-repo/labels",
json={"name": "nice", "color": "ff0000"},
)
assert resp.status_code == 201
label_json = resp.json()
assert label_json["name"] == "nice"
assert label_json["color"] == "ff0000"
assert label_json["description"] is None

# Now the label does exist.
label = repo.get_label("nice")
assert label.name == "nice"
assert label.color == "ff0000"
assert label.description is None

def test_cant_create_duplicate_label(self, fake_github):
fake_github.make_repo("an-org", "a-repo")
resp = requests.post(
"https://api.github.com/repos/an-org/a-repo/labels",
json={"name": "bug", "color": "ff0000"},
)
assert resp.status_code == 422
error_json = resp.json()
assert error_json["message"] == "Validation Failed"
assert error_json["errors"] == [
{"resource": "Label", "code": "already_exists", "field": "name"},
]

BOGUS_COLORS = ["red please", "#ff000", "f00", "12345g"]

@pytest.mark.parametrize("bogus_color", BOGUS_COLORS)
def test_cant_create_bogus_color(self, fake_github, bogus_color):
fake_github.make_repo("an-org", "a-repo")
resp = requests.post(
"https://api.github.com/repos/an-org/a-repo/labels",
json={"name": "bug", "color": bogus_color},
)
assert resp.status_code == 422
error_json = resp.json()
assert error_json["message"] == "Validation Failed"
assert error_json["errors"] == [
{"resource": "Label", "code": "invalid", "field": "color"},
]

def test_patch_label(self, fake_github):
repo = fake_github.make_repo("an-org", "a-repo")
resp = requests.patch(
"https://api.github.com/repos/an-org/a-repo/labels/help%20wanted",
json={"name": "help wanted", "color": "dedbee", "description": "Please?"},
)
assert resp.status_code == 200
label_json = resp.json()
assert label_json["name"] == "help wanted"
assert label_json["color"] == "dedbee"
assert label_json["description"] == "Please?"

label = repo.get_label("help wanted")
assert label.name == "help wanted"
assert label.color == "dedbee"
assert label.description == "Please?"

def test_cant_patch_missing_label(self, fake_github):
fake_github.make_repo("an-org", "a-repo")
resp = requests.patch(
"https://api.github.com/repos/an-org/a-repo/labels/xyzzy",
json={"name": "xyzzy", "color": "dedbee", "description": "Go away"},
)
assert resp.status_code == 404
assert resp.json()["message"] == "Label an-org/a-repo 'xyzzy' does not exist"

@pytest.mark.parametrize("bogus_color", BOGUS_COLORS)
def test_cant_patch_bogus_color(self, fake_github, bogus_color):
fake_github.make_repo("an-org", "a-repo")
resp = requests.patch(
"https://api.github.com/repos/an-org/a-repo/labels/bug",
json={"name": "bug", "color": bogus_color},
)
assert resp.status_code == 422
error_json = resp.json()
assert error_json["message"] == "Validation Failed"
assert error_json["errors"] == [
{"resource": "Label", "code": "invalid", "field": "color"},
]

def test_delete_label(self, fake_github):
repo = fake_github.make_repo("an-org", "a-repo")
# At first, the label does exist.
assert repo.get_label("help wanted").color == "008672"

# Delete the label.
resp = requests.delete("https://api.github.com/repos/an-org/a-repo/labels/help%20wanted")
assert resp.status_code == 204
assert resp.text == ""

# Now the label doesn't exist.
with pytest.raises(DoesNotExist):
repo.get_label("help wanted")

def test_cant_delete_missing_label(self, fake_github):
fake_github.make_repo("an-org", "a-repo")
# Delete the label.
resp = requests.delete("https://api.github.com/repos/an-org/a-repo/labels/xyzzy")
assert resp.status_code == 404


class TestPullRequests:
def test_make_pull_request(self, fake_github):
repo = fake_github.make_repo("an-org", "a-repo")
Expand Down Expand Up @@ -441,9 +319,11 @@ def test_get(self, flaky_github):
assert resp.status_code == 200

def test_post(self, flaky_github):
flaky_github.make_repo("an-org", "a-repo")
repo = flaky_github.make_repo("an-org", "a-repo")
pr = repo.make_pull_request()
resp = requests.post(
"https://api.github.com/repos/an-org/a-repo/labels",
json={"name": "nice", "color": "ff0000"},
f"https://api.github.com/repos/an-org/a-repo/issues/{pr.number}/comments",
json={"body": "I'm making a comment"},
)
assert resp.status_code == 201
# POSTs aren't affected by the flaky fraction.
assert resp.status_code == 200

0 comments on commit 8e5f2b8

Please sign in to comment.