Skip to content

Commit

Permalink
Convert FBCODE to use the Ruff Formatter
Browse files Browse the repository at this point in the history
Summary:
Converts the directory specified to use the Ruff formatter. This is the last big diff to convert all of Fbcode to Ruff.

pomsky_fix_bugs

drop-conflicts
bypass-github-export-checks
allow-large-files

Reviewed By: amyreese

Differential Revision: D66886610

fbshipit-source-id: 8276a7f6164efec189ca0b87e535543ed5bc3615
  • Loading branch information
Thomas Polasek authored and facebook-github-bot committed Dec 6, 2024
1 parent 4e42f5c commit 7ed53c2
Show file tree
Hide file tree
Showing 15 changed files with 104 additions and 70 deletions.
16 changes: 4 additions & 12 deletions tests/accept_any_arg_unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,15 @@ def test_for_partial_call_accepts_all_other_args_and_kwargs(self):
self.mock_callable(
sample_module,
"test_function",
).for_partial_call(
"firstarg", kwarg1="a"
).to_return_value(["blah"])
).for_partial_call("firstarg", kwarg1="a").to_return_value(["blah"])
sample_module.test_function("firstarg", "xx", kwarg1="a", kwarg2="x")

def test_for_partial_call_fails_if_no_required_args_are_present(self):
with self.assertRaises(mock_callable.UnexpectedCallArguments):
self.mock_callable(
sample_module,
"test_function",
).for_partial_call(
"firstarg", kwarg1="a"
).to_return_value(["blah"])
).for_partial_call("firstarg", kwarg1="a").to_return_value(["blah"])
sample_module.test_function(
"differentarg", "alsodifferent", kwarg1="a", kwarg2="x"
)
Expand All @@ -47,16 +43,12 @@ def test_for_partial_call_fails_if_no_required_kwargs_are_present(self):
self.mock_callable(
sample_module,
"test_function",
).for_partial_call(
"firstarg", kwarg1="x"
).to_return_value(["blah"])
).for_partial_call("firstarg", kwarg1="x").to_return_value(["blah"])
sample_module.test_function("firstarg", "secondarg", kwarg1="a", kwarg2="x")

def test_matchers_work_with_for_partial_call(self):
self.mock_callable(
sample_module,
"test_function",
).for_partial_call(
matchers.Any(), "secondarg"
).to_return_value(["blah"])
).for_partial_call(matchers.Any(), "secondarg").to_return_value(["blah"])
sample_module.test_function("asdasdeas", "secondarg", kwarg1="a", kwarg2="x")
3 changes: 1 addition & 2 deletions tests/cli_unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,8 +460,7 @@ def test_focus(self):
self.argv.append("--focus")
self.run_testslide(
expected_stdout_startswith=(
"top context\n"
" *focused example: PASS\n"
"top context\n" " *focused example: PASS\n"
# TODO add remaining bits of the output (using regexes)
)
)
Expand Down
6 changes: 5 additions & 1 deletion tests/matchers_unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,11 @@ def testBitwiseInverse(self):

def testCannotChainMoreThanTwo(self):
with self.assertRaises(testslide.matchers.AlreadyChainedException):
testslide.matchers.Any() | testslide.matchers.AnyStr() | testslide.matchers.AnyInt()
(
testslide.matchers.Any()
| testslide.matchers.AnyStr()
| testslide.matchers.AnyInt()
)
with self.assertRaises(testslide.matchers.AlreadyChainedException):
(
testslide.matchers.Any()
Expand Down
3 changes: 1 addition & 2 deletions tests/mock_async_callable_testslide.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ def assertRaisesWithMessage(self, exception, msg):
self.assertEqual(
ex_msg,
msg,
"Expected exception {}.{} message "
"to be\n{}\nbut got\n{}.".format(
"Expected exception {}.{} message " "to be\n{}\nbut got\n{}.".format(
exception.__module__, exception.__name__, repr(msg), repr(ex_msg)
),
)
Expand Down
3 changes: 1 addition & 2 deletions tests/mock_callable_testslide.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,7 @@ def assertRaisesWithMessage(self, exception, msg):
self.assertEqual(
ex_msg,
msg,
"Expected exception {}.{} message "
"to be\n{}\nbut got\n{}.".format(
"Expected exception {}.{} message " "to be\n{}\nbut got\n{}.".format(
exception.__module__, exception.__name__, repr(msg), repr(ex_msg)
),
)
Expand Down
3 changes: 1 addition & 2 deletions tests/mock_constructor_testslide.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,7 @@ def assertRaisesWithMessageInException(self, exception, msg):
self.assertIn(
msg,
ex_msg,
"Expected exception {}.{} message "
"to be\n{}\nbut got\n{}.".format(
"Expected exception {}.{} message " "to be\n{}\nbut got\n{}.".format(
exception.__module__, exception.__name__, repr(msg), repr(ex_msg)
),
)
Expand Down
11 changes: 6 additions & 5 deletions tests/strict_mock_testslide.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,7 @@ def assertRaisesWithMessage(self, exception, msg):
self.assertEqual(
ex_msg,
msg,
"Expected exception {}.{} message "
"to be\n{}\nbut got\n{}.".format(
"Expected exception {}.{} message " "to be\n{}\nbut got\n{}.".format(
exception.__module__, exception.__name__, repr(msg), repr(ex_msg)
),
)
Expand Down Expand Up @@ -901,9 +900,11 @@ def mock(msg):

setattr(self.strict_mock, self.method_name, mock)
with self.assertRaises(NonAwaitableReturn):
await getattr(
self.strict_mock, self.method_name
)("hello"),
(
await getattr(
self.strict_mock, self.method_name
)("hello"),
)

@context.example
async def fails_on_wrong_type_call(self):
Expand Down
5 changes: 4 additions & 1 deletion testslide/bdd/dsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,10 @@ def nest_context(self, name: str, *args: Any, **kwargs: Any) -> None:
if name not in self.current_context.all_shared_contexts: # type:ignore
raise TypeError('Shared context "{}" does not exist'.format(name))
self._create_context(
name, self.current_context.all_shared_contexts[name], *args, **kwargs # type: ignore
name,
self.current_context.all_shared_contexts[name],
*args,
**kwargs, # type: ignore
)

# Helper function
Expand Down
14 changes: 12 additions & 2 deletions testslide/bdd/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,16 @@ def addUnexpectedSuccess(self, test: "TestCase") -> None: # type: ignore
super(_TestSlideTestResult, self).addUnexpectedSuccess(test)
self._add_exception((type(UnexpectedSuccess), UnexpectedSuccess(), None)) # type: ignore

def addSubTest(self, test: "TestCase", subtest: "TestCase", err: Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[types.TracebackType]]) -> None: # type: ignore
def addSubTest(
self,
test: "TestCase",
subtest: "TestCase",
err: Tuple[
Optional[Type[BaseException]],
Optional[BaseException],
Optional[types.TracebackType],
],
) -> None: # type: ignore
"""Called at the end of a subtest.
'err' is None if the subtest ended successfully, otherwise it's a
tuple of values as returned by sys.exc_info().
Expand Down Expand Up @@ -816,7 +825,8 @@ def exec_body(ns: Dict[str, Callable]) -> None:

# This suite will only contain TestSlide's example test.
test_suite = unittest.TestLoader().loadTestsFromName(
"test_test_slide", test_slide_test_case # type: ignore
"test_test_slide",
test_slide_test_case, # type: ignore
)
setattr(self, attr_name, list(test_suite)[0])
result = _TestSlideTestResult()
Expand Down
2 changes: 1 addition & 1 deletion testslide/core/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def _extract_NonCallableMock_template(mock_obj: Mock) -> Optional[Any]:


def _extract_mock_template(
mock: Union[Mock, "StrictMock"]
mock: Union[Mock, "StrictMock"],
) -> Optional[Union[Type[str], Type[dict], Type[int]]]:
template = None
for mock_class, extract_mock_template in MOCK_TEMPLATE_EXTRACTORS.items():
Expand Down
32 changes: 25 additions & 7 deletions testslide/core/mock_callable.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,12 @@ def unpatch_all_callable_mocks() -> None:
This method must be called after every test unconditionally to remove all
active mock_callable() patches.
"""
global register_assertion, _default_register_assertion, _call_order_assertion_registered, _received_ordered_calls, _expected_ordered_calls
global \
register_assertion, \
_default_register_assertion, \
_call_order_assertion_registered, \
_received_ordered_calls, \
_expected_ordered_calls

register_assertion = _default_register_assertion
_call_order_assertion_registered = False
Expand Down Expand Up @@ -162,7 +167,9 @@ def _is_coroutine(obj: Any) -> bool:
3,
11,
]:
return inspect.iscoroutine(obj) or isinstance(obj, asyncio.coroutines.CoroWrapper) # type: ignore
return inspect.iscoroutine(obj) or isinstance(
obj, asyncio.coroutines.CoroWrapper
) # type: ignore
else:
return inspect.iscoroutine(obj)

Expand Down Expand Up @@ -371,7 +378,10 @@ def assertion() -> None:
register_assertion(assertion)

def add_call_order_assertion(self) -> None:
global _call_order_assertion_registered, _received_ordered_calls, _expected_ordered_calls
global \
_call_order_assertion_registered, \
_received_ordered_calls, \
_expected_ordered_calls

if not _call_order_assertion_registered:

Expand Down Expand Up @@ -553,7 +563,6 @@ def __init__(
self.new_implementation = new_implementation

async def run(self, *args: Any, **kwargs: Any) -> Optional[Any]:

await super().run(*args, **kwargs)
coro = self.new_implementation(*args, **kwargs)
if not _is_coroutine(coro):
Expand Down Expand Up @@ -1001,13 +1010,19 @@ def to_raise(
if isinstance(ex, BaseException):
self._add_runner(
_RaiseRunner(
self._original_target, self._method, self._original_callable, ex # type: ignore
self._original_target,
self._method,
self._original_callable,
ex, # type: ignore
)
)
elif isinstance(ex(), BaseException):
self._add_runner(
_RaiseRunner(
self._original_target, self._method, self._original_callable, ex() # type: ignore
self._original_target,
self._method,
self._original_callable,
ex(), # type: ignore
)
)
else:
Expand Down Expand Up @@ -1227,7 +1242,10 @@ def with_implementation(self, func: Callable) -> "_MockAsyncCallableDSL":
raise ValueError("{} must be callable.".format(func))
self._add_runner(
_AsyncImplementationRunner(
self._original_target, self._method, self._original_callable, func # type: ignore
self._original_target,
self._method,
self._original_callable,
func, # type: ignore
)
)
return self
Expand Down
4 changes: 3 additions & 1 deletion testslide/core/mock_constructor.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,9 @@ def mock_constructor(
prev_frame = caller_frame.f_back
if prev_frame:
caller_frame_info = inspect.getframeinfo(prev_frame, context=0)
callable_mock = _CallableMock(original_class, "__new__", caller_frame_info) # type: ignore[assignment]
callable_mock = _CallableMock(
original_class, "__new__", caller_frame_info
) # type: ignore[assignment]
mocked_class = _patch_and_return_mocked_class(
target,
class_name,
Expand Down
54 changes: 30 additions & 24 deletions testslide/core/strict_mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -742,18 +742,21 @@ async def awaitable_return_validation_wrapper(
raise NonAwaitableReturn(self, name)

return_value = await result_awaitable
if not lib._is_wrapped_for_signature_and_type_validation(
# The original value was already wrapped for type
# validation. Skipping additional validation to
# allow, for example, mock_callable to disable
# validation for a very specific mock call rather
# for the whole StrictMock instance
value
) and not isinstance(
# If the return value is a _BaseRunner then type
# validation, if needed, has already been performed
return_value,
mock_callable._BaseRunner,
if (
not lib._is_wrapped_for_signature_and_type_validation(
# The original value was already wrapped for type
# validation. Skipping additional validation to
# allow, for example, mock_callable to disable
# validation for a very specific mock call rather
# for the whole StrictMock instance
value
)
and not isinstance(
# If the return value is a _BaseRunner then type
# validation, if needed, has already been performed
return_value,
mock_callable._BaseRunner,
)
):
lib._validate_return_type(
template_value,
Expand All @@ -769,18 +772,21 @@ def return_validation_wrapper(*args, **kwargs):
return_value = signature_validation_wrapper(
*args, **kwargs
)
if not lib._is_wrapped_for_signature_and_type_validation(
# The original value was already wrapped for type
# validation. Skipping additional validation to
# allow, for example, mock_callable to disable
# validation for a very specific mock call rather
# for the whole StrictMock instance
value
) and not isinstance(
# If the return value is a _BaseRunner then type
# validation, if needed, has already been performed
return_value,
mock_callable._BaseRunner,
if (
not lib._is_wrapped_for_signature_and_type_validation(
# The original value was already wrapped for type
# validation. Skipping additional validation to
# allow, for example, mock_callable to disable
# validation for a very specific mock call rather
# for the whole StrictMock instance
value
)
and not isinstance(
# If the return value is a _BaseRunner then type
# validation, if needed, has already been performed
return_value,
mock_callable._BaseRunner,
)
):
lib._validate_return_type(
template_value,
Expand Down
4 changes: 3 additions & 1 deletion testslide/executor/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,9 @@ def example_code(self: Any) -> None:

return context_code

testslide.bdd.dsl.context("{}.{}".format(test_case.__module__, test_case.__name__))( # type: ignore
testslide.bdd.dsl.context(
"{}.{}".format(test_case.__module__, test_case.__name__)
)( # type: ignore
get_context_code(test_case)
)

Expand Down
14 changes: 7 additions & 7 deletions testslide/executor/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,11 +365,7 @@ def _get_ascii_logo_lines(self) -> List[str]:
{self._red_bright_attr("| |")}{self._yellow_bright_attr("| |")}{self._green_bright_attr("|")} {self._bright_attr(f"| {backslash}|/")} {self._green_bright_attr("|")}
{self._red_bright_attr(f"|.{quote}")}{self._yellow_bright_attr("| |")}{self._green_bright_attr("|")} {self._bright_attr(f"--{quote}{quote}")} {self._bright_attr("'")}{self._green_bright_attr("__|")}
{self._yellow_bright_attr(f"--{quote}")} {self._green_bright_attr(f"|__---{quote}{quote}{quote}")}
""".split(
"\n"
)[
1:8
]
""".split("\n")[1:8]

def _get_summary_lines(
self, total: int, success: int, fail: int, skip: int, not_executed_examples: int
Expand Down Expand Up @@ -440,7 +436,9 @@ def finish(self, not_executed_examples: List[Example]) -> None:
result = cast(Dict[str, Union[Example, BaseException]], result)
print("")
self.print_failed_example( # type: ignore
number + 1, result["example"], result["exception"] # type: ignore
number + 1,
result["example"],
result["exception"], # type: ignore
)

summary_lines = self._get_summary_lines(
Expand Down Expand Up @@ -533,7 +531,9 @@ def finish(self, not_executed_examples: List[Example]) -> None:
result = cast(Dict[str, Union[Example, BaseException]], result)
print("")
self.print_failed_example(
number + 1, result["example"], result["exception"] # type: ignore
number + 1,
result["example"],
result["exception"], # type: ignore
)
print("")

Expand Down

0 comments on commit 7ed53c2

Please sign in to comment.