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

[internal] Convert unit tests to use pytest #13798

Merged
merged 1 commit into from
Dec 3, 2021
Merged
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
51 changes: 27 additions & 24 deletions src/python/pants/fs/fs_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,43 @@
# Licensed under the Apache License, Version 2.0 (see LICENSE).

import os
import unittest

import pytest

from pants.fs.fs import safe_filename


class SafeFilenameTest(unittest.TestCase):
class FixedDigest:
def __init__(self, size):
self._size = size
class FixedDigest:
def __init__(self, size):
self._size = size

def update(self, value):
pass
def update(self, value):
pass

def hexdigest(self):
return self._size * "*"
def hexdigest(self):
return self._size * "*"

def test_bad_name(self):
with pytest.raises(ValueError):
safe_filename(os.path.join("more", "than", "a", "name.game"))

def test_noop(self):
assert "jack.jill" == safe_filename("jack", ".jill", max_length=9)
assert "jack.jill" == safe_filename("jack", ".jill", max_length=100)
def test_bad_name() -> None:
with pytest.raises(ValueError):
safe_filename(os.path.join("more", "than", "a", "name.game"))

def test_shorten(self):
assert "**.jill" == safe_filename("jack", ".jill", digest=self.FixedDigest(2), max_length=8)

def test_shorten_readable(self):
assert "j.**.e.jill" == safe_filename(
"jackalope", ".jill", digest=self.FixedDigest(2), max_length=11
)
def test_noop() -> None:
assert "jack.jill" == safe_filename("jack", ".jill", max_length=9)
assert "jack.jill" == safe_filename("jack", ".jill", max_length=100)

def test_shorten_fail(self):
with pytest.raises(ValueError):
safe_filename("jack", ".beanstalk", digest=self.FixedDigest(3), max_length=12)

def test_shorten() -> None:
assert "**.jill" == safe_filename("jack", ".jill", digest=FixedDigest(2), max_length=8)


def test_shorten_readable() -> None:
assert "j.**.e.jill" == safe_filename(
"jackalope", ".jill", digest=FixedDigest(2), max_length=11
)


def test_shorten_fail() -> None:
with pytest.raises(ValueError):
safe_filename("jack", ".beanstalk", digest=FixedDigest(3), max_length=12)
9 changes: 5 additions & 4 deletions src/python/pants/option/custom_types_test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).

import unittest
from textwrap import dedent
from typing import Dict, List, Union

Expand Down Expand Up @@ -65,7 +64,7 @@ def test_flatten_shlexed_list() -> None:
]


class CustomTypesTest(unittest.TestCase):
class TestCustomTypes:
def assert_list_parsed(self, s: str, *, expected: ParsedList) -> None:
assert expected == ListValueComponent.create(s).val

Expand Down Expand Up @@ -150,8 +149,10 @@ def test_split_list_modifier_expressions(self) -> None:
self.assert_split_list("+1,2],-[3,4", expected=["+1,2]", "-[3,4"])
self.assert_split_list("+(1,2],-[3,4)", expected=["+(1,2]", "-[3,4)"])

# The heuristic list modifier expression splitter cannot handle certain very unlikely cases.
@unittest.expectedFailure
#
@pytest.mark.xfail(
reason="The heuristic list modifier expression splitter cannot handle certain very unlikely cases."
)
def test_split_unlikely_list_modifier_expression(self) -> None:
# Example of the kind of (unlikely) values that will defeat our heuristic, regex-based
# splitter of list modifier expressions.
Expand Down
102 changes: 51 additions & 51 deletions src/python/pants/testutil/_process_handler_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,62 +2,62 @@
# Licensed under the Apache License, Version 2.0 (see LICENSE).

import subprocess
import unittest
from textwrap import dedent

from pants.testutil._process_handler import SubprocessProcessHandler


class TestSubprocessProcessHandler(unittest.TestCase):
def test_exit_1(self):
process = subprocess.Popen(["/bin/sh", "-c", "exit 1"])
process_handler = SubprocessProcessHandler(process)
assert process_handler.wait() == 1
def test_exit_1() -> None:
process = subprocess.Popen(["/bin/sh", "-c", "exit 1"])
process_handler = SubprocessProcessHandler(process)
assert process_handler.wait() == 1

def test_exit_0(self):
process = subprocess.Popen(["/bin/sh", "-c", "exit 0"])
process_handler = SubprocessProcessHandler(process)
assert process_handler.wait() == 0

def test_communicate_teeing_retrieves_stdout_and_stderr(self):
process = subprocess.Popen(
[
"/bin/bash",
"-c",
def test_exit_0() -> None:
process = subprocess.Popen(["/bin/sh", "-c", "exit 0"])
process_handler = SubprocessProcessHandler(process)
assert process_handler.wait() == 0


def test_communicate_teeing_retrieves_stdout_and_stderr() -> None:
process = subprocess.Popen(
[
"/bin/bash",
"-c",
"""
echo "1out"
echo >&2 "1err"
sleep 0.05
echo >&2 "2err"
echo "2out"
sleep 0.05
echo "3out"
sleep 0.05
echo >&2 "3err"
sleep 0.05
exit 1
""",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
process_handler = SubprocessProcessHandler(process)
assert process_handler.communicate_teeing_stdout_and_stderr() == (
dedent(
"""\
1out
2out
3out
"""
).encode(),
dedent(
"""\
1err
2err
3err
"""
echo "1out"
echo >&2 "1err"
sleep 0.05
echo >&2 "2err"
echo "2out"
sleep 0.05
echo "3out"
sleep 0.05
echo >&2 "3err"
sleep 0.05
exit 1
""",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
process_handler = SubprocessProcessHandler(process)
assert process_handler.communicate_teeing_stdout_and_stderr() == (
dedent(
"""\
1out
2out
3out
"""
).encode(),
dedent(
"""\
1err
2err
3err
"""
).encode(),
)
# Sadly, this test doesn't test that sys.std{out,err} also receive the output.
# You can see it when you run it, but any way we have of spying on sys.std{out,err}
# isn't pickleable enough to write a test which works.
).encode(),
)
# Sadly, this test doesn't test that sys.std{out,err} also receive the output.
# You can see it when you run it, but any way we have of spying on sys.std{out,err}
# isn't pickleable enough to write a test which works.
141 changes: 72 additions & 69 deletions src/python/pants/util/collections_test.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).

import unittest

from __future__ import annotations

from functools import partial
from typing import List

import pytest

Expand All @@ -15,70 +16,72 @@
)


class TestCollections(unittest.TestCase):
def test_recursively_update(self) -> None:
d1 = {"a": 1, "b": {"c": 2, "o": "z"}, "z": {"y": 0}}
d2 = {"e": 3, "b": {"f": 4, "o": 9}, "g": {"h": 5}, "z": 7}
recursively_update(d1, d2)
assert d1 == {"a": 1, "b": {"c": 2, "f": 4, "o": 9}, "e": 3, "g": {"h": 5}, "z": 7}

def test_assert_single_element(self) -> None:
single_element = [1]
assert 1 == assert_single_element(single_element)

no_elements: List[int] = []
with pytest.raises(StopIteration):
assert_single_element(no_elements)

too_many_elements = [1, 2]
with pytest.raises(ValueError) as cm:
assert_single_element(too_many_elements)
expected_msg = "iterable [1, 2] has more than one element."
assert expected_msg == str(cm.value)

def test_ensure_list(self) -> None:
# Reject single values by default, even if they're the expected type.
with pytest.raises(ValueError):
ensure_list(0, expected_type=int)
with pytest.raises(ValueError):
ensure_list(False, expected_type=bool)

# Allow wrapping single values into a list.
assert ensure_list(0, expected_type=int, allow_single_scalar=True) == [0]
assert ensure_list(True, expected_type=bool, allow_single_scalar=True) == [True]
arbitrary_object = object()
assert ensure_list(arbitrary_object, expected_type=object, allow_single_scalar=True) == [
arbitrary_object
]

ensure_int_list = partial(ensure_list, expected_type=int)

# Keep lists as lists
assert ensure_int_list([]) == []
assert ensure_int_list([0]) == [0]
assert ensure_int_list([0, 1, 2]) == [0, 1, 2]

# Convert other iterable types to a list
assert ensure_int_list((0,)) == [0]
assert ensure_int_list({0}) == [0]
assert ensure_int_list({0: "hello"}) == [0]

# Perform runtime type checks
with pytest.raises(ValueError):
ensure_int_list(["bad"])
with pytest.raises(ValueError):
ensure_int_list([0.0])
with pytest.raises(ValueError):
ensure_int_list([0, 1, "sneaky", 2, 3])

def test_ensure_str_list(self) -> None:
assert ensure_str_list(("hello", "there")) == ["hello", "there"]

assert ensure_str_list("hello", allow_single_str=True) == ["hello"]
with pytest.raises(ValueError):
ensure_str_list("hello")

with pytest.raises(ValueError):
ensure_str_list(0) # type: ignore[arg-type]
with pytest.raises(ValueError):
ensure_str_list([0, 1]) # type: ignore[list-item]
def test_recursively_update() -> None:
d1 = {"a": 1, "b": {"c": 2, "o": "z"}, "z": {"y": 0}}
d2 = {"e": 3, "b": {"f": 4, "o": 9}, "g": {"h": 5}, "z": 7}
recursively_update(d1, d2)
assert d1 == {"a": 1, "b": {"c": 2, "f": 4, "o": 9}, "e": 3, "g": {"h": 5}, "z": 7}


def test_assert_single_element() -> None:
single_element = [1]
assert 1 == assert_single_element(single_element)

no_elements: list[int] = []
with pytest.raises(StopIteration):
assert_single_element(no_elements)

too_many_elements = [1, 2]
with pytest.raises(ValueError) as cm:
assert_single_element(too_many_elements)
expected_msg = "iterable [1, 2] has more than one element."
assert expected_msg == str(cm.value)


def test_ensure_list() -> None:
# Reject single values by default, even if they're the expected type.
with pytest.raises(ValueError):
ensure_list(0, expected_type=int)
with pytest.raises(ValueError):
ensure_list(False, expected_type=bool)

# Allow wrapping single values into a list.
assert ensure_list(0, expected_type=int, allow_single_scalar=True) == [0]
assert ensure_list(True, expected_type=bool, allow_single_scalar=True) == [True]
arbitrary_object = object()
assert ensure_list(arbitrary_object, expected_type=object, allow_single_scalar=True) == [
arbitrary_object
]

ensure_int_list = partial(ensure_list, expected_type=int)

# Keep lists as lists
assert ensure_int_list([]) == []
assert ensure_int_list([0]) == [0]
assert ensure_int_list([0, 1, 2]) == [0, 1, 2]

# Convert other iterable types to a list
assert ensure_int_list((0,)) == [0]
assert ensure_int_list({0}) == [0]
assert ensure_int_list({0: "hello"}) == [0]

# Perform runtime type checks
with pytest.raises(ValueError):
ensure_int_list(["bad"])
with pytest.raises(ValueError):
ensure_int_list([0.0])
with pytest.raises(ValueError):
ensure_int_list([0, 1, "sneaky", 2, 3])


def test_ensure_str_list() -> None:
assert ensure_str_list(("hello", "there")) == ["hello", "there"]

assert ensure_str_list("hello", allow_single_str=True) == ["hello"]
with pytest.raises(ValueError):
ensure_str_list("hello")

with pytest.raises(ValueError):
ensure_str_list(0) # type: ignore[arg-type]
with pytest.raises(ValueError):
ensure_str_list([0, 1]) # type: ignore[list-item]