Skip to content

Commit 2acda6a

Browse files
initial test files
1 parent 0212e01 commit 2acda6a

File tree

4 files changed

+142
-0
lines changed

4 files changed

+142
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
from os import getenv
2+
from typing import Optional
3+
4+
from attrs import define, evolve, field
5+
6+
from code_to_optimize.code_directories.circular_deps.constants import DEFAULT_API_URL, DEFAULT_APP_URL
7+
8+
9+
@define
10+
class GalileoApiClient():
11+
"""A Client which has been authenticated for use on secured endpoints
12+
13+
The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
14+
15+
``base_url``: The base URL for the API, all requests are made to a relative path to this URL
16+
This can also be set via the GALILEO_CONSOLE_URL environment variable
17+
18+
``api_key``: The API key to be sent with every request
19+
This can also be set via the GALILEO_API_KEY environment variable
20+
21+
``cookies``: A dictionary of cookies to be sent with every request
22+
23+
``headers``: A dictionary of headers to be sent with every request
24+
25+
``timeout``: The maximum amount of a time a request can take. API functions will raise
26+
httpx.TimeoutException if this is exceeded.
27+
28+
``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
29+
but can be set to False for testing purposes.
30+
31+
``follow_redirects``: Whether or not to follow redirects. Default value is False.
32+
33+
``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
34+
35+
Attributes:
36+
raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
37+
status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
38+
argument to the constructor.
39+
token: The token to use for authentication
40+
prefix: The prefix to use for the Authorization header
41+
auth_header_name: The name of the Authorization header
42+
"""
43+
44+
_base_url: Optional[str] = field(factory=lambda: GalileoApiClient.get_api_url(), kw_only=True, alias="base_url")
45+
_api_key: Optional[str] = field(factory=lambda: getenv("GALILEO_API_KEY", None), kw_only=True, alias="api_key")
46+
token: Optional[str] = None
47+
48+
api_key_header_name: str = "Galileo-API-Key"
49+
client_type_header_name: str = "client-type"
50+
client_type_header_value: str = "sdk-python"
51+
52+
@staticmethod
53+
def get_console_url() -> str:
54+
console_url = getenv("GALILEO_CONSOLE_URL", DEFAULT_API_URL)
55+
if DEFAULT_API_URL == console_url:
56+
return DEFAULT_APP_URL
57+
58+
return console_url
59+
60+
def with_api_key(self, api_key: str) -> "GalileoApiClient":
61+
"""Get a new client matching this one with a new API key"""
62+
if self._client is not None:
63+
self._client.headers.update({self.api_key_header_name: api_key})
64+
if self._async_client is not None:
65+
self._async_client.headers.update({self.api_key_header_name: api_key})
66+
return evolve(self, api_key=api_key)
67+
68+
@staticmethod
69+
def get_api_url(base_url: Optional[str] = None) -> str:
70+
api_url = base_url or getenv("GALILEO_CONSOLE_URL", DEFAULT_API_URL)
71+
if api_url is None:
72+
raise ValueError("base_url or GALILEO_CONSOLE_URL must be set")
73+
if any(map(api_url.__contains__, ["localhost", "127.0.0.1"])):
74+
api_url = "http://localhost:8088"
75+
else:
76+
api_url = api_url.replace("app.galileo.ai", "api.galileo.ai").replace("console", "api")
77+
return api_url
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
DEFAULT_API_URL = "https://api.galileo.ai/"
2+
DEFAULT_APP_URL = "https://app.galileo.ai/"
3+
4+
5+
# function_names: GalileoApiClient.get_console_url
6+
# module_abs_path : /home/mohammed/Work/galileo-python/src/galileo/api_client.py
7+
# preexisting_objects: {('GalileoApiClient', ()), ('_set_destination', ()), ('get_console_url', (FunctionParent(name='GalileoApiClient', type='ClassDef'),))}
8+
# project_root_path: /home/mohammed/Work/galileo-python/src

codeflash/code_utils/code_replacer.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,13 @@ def replace_functions_and_add_imports(
397397
preexisting_objects: set[tuple[str, tuple[FunctionParent, ...]]],
398398
project_root_path: Path,
399399
) -> str:
400+
logger.debug("start from here,...")
401+
logger.debug(f"source_code: {source_code}")
402+
logger.debug(f"function_names: {function_names}")
403+
logger.debug(f"optimized_code: {optimized_code}")
404+
logger.debug(f"module_abspath: {module_abspath}")
405+
logger.debug(f"preexisting_objects: {preexisting_objects}")
406+
logger.debug(f"project_root_path: {project_root_path}")
400407
return add_needed_imports_from_module(
401408
optimized_code,
402409
replace_functions_in_file(source_code, function_names, optimized_code, preexisting_objects),

tests/test_code_context_extractor.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2434,3 +2434,53 @@ def simple_method(self):
24342434
assert "class SimpleClass:" in code_content
24352435
assert "def simple_method(self):" in code_content
24362436
assert "return 42" in code_content
2437+
2438+
2439+
from codeflash.code_utils.code_replacer import replace_functions_and_add_imports
2440+
def test_replace_functions_and_add_imports():
2441+
path_to_root = Path(__file__).resolve().parent.parent / "code_to_optimize" / "code_directories" / "circular_deps"
2442+
optimized_code = '''from __future__ import annotations
2443+
2444+
import urllib.parse
2445+
from os import getenv
2446+
2447+
from attrs import define
2448+
from code_to_optimize.code_directories.circular_deps.constants import DEFAULT_API_URL, DEFAULT_APP_URL
2449+
2450+
# Precompute constant netlocs for set membership test
2451+
_DEFAULT_APP_NETLOC = urllib.parse.urlparse(DEFAULT_APP_URL).netloc
2452+
_DEFAULT_API_NETLOC = urllib.parse.urlparse(DEFAULT_API_URL).netloc
2453+
_NETLOC_SET = {_DEFAULT_APP_NETLOC, _DEFAULT_API_NETLOC}
2454+
2455+
@define
2456+
class GalileoApiClient():
2457+
2458+
@staticmethod
2459+
def get_console_url() -> str:
2460+
# Return DEFAULT_APP_URL if the env var is not set or set to DEFAULT_API_URL
2461+
console_url = getenv("GALILEO_CONSOLE_URL", DEFAULT_API_URL)
2462+
if console_url == DEFAULT_API_URL:
2463+
return DEFAULT_APP_URL
2464+
return console_url
2465+
2466+
def _set_destination(console_url: str) -> str:
2467+
"""
2468+
Parse the console_url and return the destination for the OpenTelemetry traces.
2469+
"""
2470+
destination = (console_url or GalileoApiClient.get_console_url()).replace("console.", "api.")
2471+
parsed_url = urllib.parse.urlparse(destination)
2472+
if parsed_url.netloc in _NETLOC_SET:
2473+
return f"{DEFAULT_APP_URL}api/galileo/otel/traces"
2474+
return f"{parsed_url.scheme}://{parsed_url.netloc}/otel/traces"'''
2475+
file_abs_path = path_to_root / "api_client.py"
2476+
content = Path(file_abs_path).read_text(encoding="utf-8")
2477+
new_code = replace_functions_and_add_imports(
2478+
source_code= content,
2479+
function_names= ["GalileoApiClient.get_console_url"],
2480+
optimized_code= optimized_code,
2481+
module_abspath= file_abs_path,
2482+
preexisting_objects= {('GalileoApiClient', ()), ('_set_destination', ()), ('get_console_url', (FunctionParent(name='GalileoApiClient', type='ClassDef'),))},
2483+
project_root_path= Path(path_to_root),
2484+
)
2485+
print(new_code)
2486+
assert 1 == 1

0 commit comments

Comments
 (0)