-
Notifications
You must be signed in to change notification settings - Fork 718
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add "reinstall()" method to make it easier in spawn multiprocessing (#…
- Loading branch information
Showing
2 changed files
with
106 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
import multiprocessing | ||
import os | ||
|
||
import pytest | ||
|
||
from loguru import logger | ||
|
||
|
||
@pytest.fixture | ||
def fork_context(): | ||
yield multiprocessing.get_context("fork") | ||
|
||
|
||
@pytest.fixture | ||
def spawn_context(): | ||
yield multiprocessing.get_context("spawn") | ||
|
||
|
||
class Writer: | ||
def __init__(self): | ||
self._output = "" | ||
|
||
def write(self, message): | ||
self._output += message | ||
|
||
def read(self): | ||
return self._output | ||
|
||
|
||
def subworker(logger): | ||
logger.reinstall() | ||
logger.info("Child") | ||
deeper_subworker() | ||
|
||
|
||
def deeper_subworker(): | ||
logger.info("Grandchild") | ||
|
||
|
||
@pytest.mark.skipif(os.name == "nt", reason="Windows does not support forking") | ||
def test_process_fork(fork_context): | ||
writer = Writer() | ||
|
||
logger.add(writer, context=fork_context, format="{message}", enqueue=True, catch=False) | ||
|
||
process = fork_context.Process(target=subworker, args=(logger,)) | ||
process.start() | ||
process.join() | ||
|
||
assert process.exitcode == 0 | ||
|
||
logger.info("Main") | ||
logger.remove() | ||
|
||
assert writer.read() == "Child\nGrandchild\nMain\n" | ||
|
||
|
||
def test_process_spawn(spawn_context): | ||
writer = Writer() | ||
|
||
logger.add(writer, context=spawn_context, format="{message}", enqueue=True, catch=False) | ||
|
||
process = spawn_context.Process(target=subworker, args=(logger,)) | ||
process.start() | ||
process.join() | ||
|
||
assert process.exitcode == 0 | ||
|
||
logger.info("Main") | ||
logger.remove() | ||
|
||
assert writer.read() == "Child\nGrandchild\nMain\n" |