|
4 | 4 |
|
5 | 5 | import gc
|
6 | 6 | import os
|
| 7 | +import sys |
7 | 8 | import json
|
8 | 9 | import asyncio
|
9 | 10 | import inspect
|
| 11 | +import subprocess |
10 | 12 | import tracemalloc
|
11 | 13 | from typing import Any, Union, cast
|
| 14 | +from textwrap import dedent |
12 | 15 | from unittest import mock
|
13 | 16 | from typing_extensions import Literal
|
14 | 17 |
|
@@ -1766,3 +1769,43 @@ def retry_handler(_request: httpx.Request) -> httpx.Response:
|
1766 | 1769 | ) as response:
|
1767 | 1770 | assert response.retries_taken == failures_before_success
|
1768 | 1771 | assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success
|
| 1772 | + |
| 1773 | + def test_get_platform(self) -> None: |
| 1774 | + # Issue https://github.com/openai/openai-python/issues/1827 was caused |
| 1775 | + # asyncify leaving threads unterminated when used with nest_asyncio. |
| 1776 | + # Since nest_asyncio.apply() is global and cannot be un-applied, this |
| 1777 | + # test is run in a separate process to avoid affecting other tests. |
| 1778 | + test_code = dedent("""\ |
| 1779 | + import asyncio |
| 1780 | + import nest_asyncio |
| 1781 | +
|
| 1782 | + import threading |
| 1783 | +
|
| 1784 | + from openai._base_client import get_platform |
| 1785 | + from openai._utils import asyncify |
| 1786 | +
|
| 1787 | + async def test_main() -> None: |
| 1788 | + result = await asyncify(get_platform)() |
| 1789 | + print(result) |
| 1790 | + for thread in threading.enumerate(): |
| 1791 | + print(thread.name) |
| 1792 | +
|
| 1793 | + nest_asyncio.apply() |
| 1794 | + asyncio.run(test_main()) |
| 1795 | + """) |
| 1796 | + with subprocess.Popen( |
| 1797 | + [sys.executable, "-c", test_code], |
| 1798 | + stdout=subprocess.PIPE, |
| 1799 | + stderr=subprocess.PIPE, |
| 1800 | + text=True, |
| 1801 | + ) as process: |
| 1802 | + try: |
| 1803 | + process.wait(2) |
| 1804 | + if process.returncode: |
| 1805 | + print(process.stdout) |
| 1806 | + print(process.stderr) |
| 1807 | + raise AssertionError("calling get_platform using asyncify resulted in a non-zero exit code") |
| 1808 | + except subprocess.TimeoutExpired as e: |
| 1809 | + process.kill() |
| 1810 | + raise AssertionError("calling get_platform using asyncify resulted in a hung process") from e |
| 1811 | + |
0 commit comments