From 191b41c47a68b1caca1e8b9517c8276d21d7ab2a Mon Sep 17 00:00:00 2001 From: Yanyan Zhu Date: Thu, 12 Nov 2026 11:07:45 -0800 Subject: [PATCH] allowed wattage and uvalue api payload updates --- CHANGELOG.md | 9 + comcheck_api/ai/skill/SKILL.md | 15 +- comcheck_api/ai/skill/reference/operations.md | 14 +- comcheck_api/ai/skill/reference/simulation.md | 2 +- comcheck_api/api/api_services.py | 27 ++- comcheck_api/client/comcheck_client.py | 94 ++++++---- docs_site/api/operations/envelope.md | 6 +- docs_site/api/operations/interior-lighting.md | 24 +-- docs_site/api/simulation.md | 6 +- examples/README.md | 4 +- examples/client/allowed_wattage.py | 41 ++-- tests/test_comcheck_client.py | 56 +++--- tests/test_wattage_uvalues_api.py | 175 ++++++++++++++++++ 13 files changed, 357 insertions(+), 116 deletions(-) create mode 100644 tests/test_wattage_uvalues_api.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 861f54b..e437579 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ All notable changes to this project are documented in this file. ## [Unreleased] +### Changed (breaking) +- `COMcheckClient.calculate_interior_space_allowed_wattage(project, area_description, energy_code=None)` now takes the whole project and the `areaDescription` of the interior space, instead of an `InteriorSpace` and an energy code. It sends the project to `POST /{energyCode}/activity-use/allowed-wattage?areaDescription=...`. The energy code defaults to `project.control.code` +- `COMcheckClient.calculate_interior_spaces_allowed_wattage(project, energy_code=None)` now takes the whole project instead of a list of `InteriorSpace` objects and returns allowed wattage for every interior space in it. The energy code defaults to `project.control.code` +- `COMCheckApiService.interior_space_allowed_wattage(project_data, energy_code, area_description)` and `COMCheckApiService.interior_spaces_allowed_wattage(project_data, energy_code)` send the whole project +- `COMcheckClient.update_uvalues` now also sends `project.location` with the envelope; the u-value endpoint requires it because the required u-values depend on the climate zone + +### Fixed +- `update_uvalues` no longer raises when the API returns `null` for `propUValue` or `effectiveUFactor`; the existing value is kept + ### Added - Docs and AI skill note that mechanical requirements (`requirementAnswer`) are not supported and must be filled out on COMcheck Web - Renewable energy operations module (`project_renewable_operations`) for managing on-site renewable systems and off-site procurement diff --git a/comcheck_api/ai/skill/SKILL.md b/comcheck_api/ai/skill/SKILL.md index 6612ae9..0165159 100644 --- a/comcheck_api/ai/skill/SKILL.md +++ b/comcheck_api/ai/skill/SKILL.md @@ -60,18 +60,21 @@ Triggers: for known lifecycle values (the catalog isn't exhaustive — only the terminal pair is guaranteed stable). - **U-values are calculated server-side**: `update_uvalues(project)` - fetches the proposed/effective u-values for the envelope and writes + sends the envelope plus `project.location` (required — the climate zone + drives the required u-values), fetches the proposed/effective u-values, and + writes them back onto the matching `agWall`, `bgWall`, `roof`, and `floor` assemblies (only these get calculated u-values; `effectiveUFactor` is `agWall`-only). `start_run_simulation` calls this automatically, so you rarely call it directly — use it only when you need refreshed u-values on a project outside the simulation flow. - **Interior lighting allowed wattage is also calculated server-side**: - `calculate_interior_space_allowed_wattage(interior_space, energy_code)` and - `calculate_interior_spaces_allowed_wattage(interior_spaces, energy_code)` - take an `InteriorSpace` (or a list of them) plus the energy code as an - explicit string — `InteriorSpace` has no `control.code` of its own. Neither - method mutates the input or writes to `allowedWattage`; both return the + `calculate_interior_space_allowed_wattage(project, area_description)` and + `calculate_interior_spaces_allowed_wattage(project)` send the whole + project; the single form picks the interior space by its + `areaDescription`, which must already exist in the project. The energy code + defaults to `project.control.code` (override with `energy_code=`). Neither + method mutates the project or writes to `allowedWattage`; both return the raw calculation payload (`{"spaceAllowedWattage": ...}` for the single form, `{areaDescription: wattage, ...}` for the list form). - **Renewable areas and capacity are calculated server-side**: diff --git a/comcheck_api/ai/skill/reference/operations.md b/comcheck_api/ai/skill/reference/operations.md index a54cc50..e6c180e 100644 --- a/comcheck_api/ai/skill/reference/operations.md +++ b/comcheck_api/ai/skill/reference/operations.md @@ -135,19 +135,17 @@ Allowed wattage is calculated server-side via two `COMcheckClient` methods, not an `il_ops` function: ```python -energy_code = str(project.control.code) # InteriorSpace alone has no control.code - -result = client.calculate_interior_space_allowed_wattage(interior_space, energy_code) +# Both send the whole project; energy code defaults to project.control.code +result = client.calculate_interior_space_allowed_wattage(project, "Open Office") # {"spaceAllowedWattage": 560} -results = client.calculate_interior_spaces_allowed_wattage( - [interior_space, second_interior_space], energy_code -) +results = client.calculate_interior_spaces_allowed_wattage(project) # {"Open Office": 560, "Conference Room": 610} — keyed by areaDescription ``` -Neither call mutates the `InteriorSpace` objects or writes onto -`allowedWattage` — they return the raw calculation payload. +The interior space must already be in the project (add it with +`il_ops.add_interior_space_to_project`). Neither call mutates the project or +writes onto `allowedWattage` — they return the raw calculation payload. ## Exterior lighting operations diff --git a/comcheck_api/ai/skill/reference/simulation.md b/comcheck_api/ai/skill/reference/simulation.md index 26c790f..3ac75f6 100644 --- a/comcheck_api/ai/skill/reference/simulation.md +++ b/comcheck_api/ai/skill/reference/simulation.md @@ -44,7 +44,7 @@ client = COMcheckClient(api_key="...") | Method | Returns | Purpose | |---|---|---| | `client.start_run_simulation(project, project_id=None)` | `str` (session ID) | Kick off the simulation. Always refreshes the envelope u-values first (via `update_uvalues`). If `project_id` is provided, the project is also saved/updated. | -| `client.update_uvalues(project)` | `ComBuilding` | Calculate assembly u-values and write them back onto the project's `agWall`, `bgWall`, `roof`, and `floor` assemblies (matched by `assemblyType`). Mutates and returns the same project. Called automatically by `start_run_simulation`. | +| `client.update_uvalues(project)` | `ComBuilding` | Send the envelope and `project.location` (required), calculate assembly u-values, and write them back onto the project's `agWall`, `bgWall`, `roof`, and `floor` assemblies (matched by `assemblyType`). Mutates and returns the same project. Called automatically by `start_run_simulation`. | | `client.get_simulation_status(session_id)` | `dict` | Current status. Fields: `sessionId`, `status` (see the Status values table above), optional `message`. | | `client.get_simulation_result(session_id)` | `dict` | Final result. Fields: `sessionId`, `performanceRating`, `energyCreditPerformanceRating`, `proposedBpf`, `baselineBpf`. | diff --git a/comcheck_api/api/api_services.py b/comcheck_api/api/api_services.py index 4af1e3d..976095b 100644 --- a/comcheck_api/api/api_services.py +++ b/comcheck_api/api/api_services.py @@ -199,14 +199,17 @@ def update_project( def assemblies_uvalue( self, envelope_data: Dict[str, Any], energy_code: str ) -> Dict[str, Any]: - """get assemblies u values + """Calculate assembly u-values. Args: - envelope_data: The envelope data to send in the request body + envelope_data: The request body: the envelope assembly arrays + (``roof``, ``agWall``, ``bgWall``, ``floor``) plus the + project ``location``, which is required because the + required u-values depend on the climate zone. energy_code: The energy code for the api end point path Returns: - RunSimulationResponse with session information + API response data as dictionary Raises: COMCheckHTTPError: If the API returns an error status @@ -224,13 +227,15 @@ def assemblies_uvalue( self._handle_api_error(error) def interior_space_allowed_wattage( - self, interior_space_data: Dict[str, Any], energy_code: str + self, project_data: Dict[str, Any], energy_code: str, area_description: str ) -> Dict[str, Any]: """Calculate allowed wattage for a single interior lighting space. Args: - interior_space_data: The interior space data to send in the request body + project_data: The whole project to send in the request body energy_code: The energy code for the api end point path + area_description: The ``areaDescription`` of the interior space + (``activityUse``) in the project to calculate Returns: API response data as dictionary @@ -242,7 +247,9 @@ def interior_space_allowed_wattage( try: client = self._get_client() response = client.post( - f"/{energy_code}/activity-use/allowed-wattage", json=interior_space_data + f"/{energy_code}/activity-use/allowed-wattage", + params={"areaDescription": area_description}, + json=project_data, ) response.raise_for_status() return response.json() @@ -250,12 +257,12 @@ def interior_space_allowed_wattage( self._handle_api_error(error) def interior_spaces_allowed_wattage( - self, interior_spaces_data: list[Dict[str, Any]], energy_code: str + self, project_data: Dict[str, Any], energy_code: str ) -> Dict[str, Any]: - """Calculate allowed wattage for a list of interior lighting spaces. + """Calculate allowed wattage for every interior lighting space in a project. Args: - interior_spaces_data: The list of interior space data to send in the request body + project_data: The whole project to send in the request body energy_code: The energy code for the api end point path Returns: @@ -269,7 +276,7 @@ def interior_spaces_allowed_wattage( client = self._get_client() response = client.post( f"/{energy_code}/activity-uses/allowed-wattage", - json=interior_spaces_data, + json=project_data, ) response.raise_for_status() return response.json() diff --git a/comcheck_api/client/comcheck_client.py b/comcheck_api/client/comcheck_client.py index 826839c..a73c453 100644 --- a/comcheck_api/client/comcheck_client.py +++ b/comcheck_api/client/comcheck_client.py @@ -30,7 +30,6 @@ PlantEfficiency, FanSystemComplianceResult, ) -from comcheck_api.types.common_types import InteriorSpace from comcheck_api.types.core_types import ( MISSING, ComBuilding, @@ -283,11 +282,13 @@ def _parse_data(self, data, mode): def update_uvalues(self, project: ComBuilding) -> ComBuilding: """Calculate assembly u-values and update the project in place. - Sends the full envelope to the u-value endpoint and writes the returned - values back onto the matching ``agWall``, ``bgWall``, ``roof``, and - ``floor`` components (matched by ``assemblyType``). Only these assembly - types receive calculated u-values; ``effectiveUFactor`` applies to - ``agWall`` only. + Sends the envelope and the project ``location`` to the u-value + endpoint and writes the returned values back onto the matching + ``agWall``, ``bgWall``, ``roof``, and ``floor`` components (matched by + ``assemblyType``). Only these assembly types receive calculated + u-values; ``effectiveUFactor`` applies to ``agWall`` only. The + location is required because the required u-values depend on the + climate zone. Args: project: The project whose envelope u-values should be refreshed. @@ -296,70 +297,87 @@ def update_uvalues(self, project: ComBuilding) -> ComBuilding: The same ``project`` instance, with u-values updated. """ energy_code = str(project.control.code) - envelope_data = project.envelope.model_dump(mode="json") + request_data = project.envelope.model_dump(mode="json") + request_data["location"] = project.location.model_dump(mode="json") updated_assembly_uvalues = self._service.assemblies_uvalue( - envelope_data, energy_code + request_data, energy_code )["data"] - for wall in project.envelope.agWall: - for uvalue in updated_assembly_uvalues.get("agWall", []): - if wall.assemblyType == uvalue["assemblyType"]: - wall.effectiveUFactor = float(uvalue["effectiveUFactor"]) - wall.propUValue = float(uvalue["propUValue"]) - for wall in project.envelope.bgWall: - for uvalue in updated_assembly_uvalues.get("bgWall", []): - if wall.assemblyType == uvalue["assemblyType"]: - wall.propUValue = float(uvalue["propUValue"]) - for roof in project.envelope.roof: - for uvalue in updated_assembly_uvalues.get("roof", []): - if roof.assemblyType == uvalue["assemblyType"]: - roof.propUValue = float(uvalue["propUValue"]) - for floor in project.envelope.floor: - for uvalue in updated_assembly_uvalues.get("floor", []): - if floor.assemblyType == uvalue["assemblyType"]: - floor.propUValue = float(uvalue["propUValue"]) + def _apply(components, key: str, effective: bool = False) -> None: + results = { + uvalue["assemblyType"]: uvalue + for uvalue in updated_assembly_uvalues.get(key, []) + } + for component in components: + uvalue = results.get(component.assemblyType) + if uvalue is None: + continue + prop_uvalue = _optional_float(uvalue.get("propUValue")) + if prop_uvalue is not None: + component.propUValue = prop_uvalue + if effective: + effective_ufactor = _optional_float(uvalue.get("effectiveUFactor")) + if effective_ufactor is not None: + component.effectiveUFactor = effective_ufactor + + _apply(project.envelope.agWall, "agWall", effective=True) + _apply(project.envelope.bgWall, "bgWall") + _apply(project.envelope.roof, "roof") + _apply(project.envelope.floor, "floor") return project def calculate_interior_space_allowed_wattage( - self, interior_space: InteriorSpace, energy_code: str + self, + project: ComBuilding, + area_description: str, + energy_code: Optional[str] = None, ) -> Any: """Calculate allowed wattage for a single interior lighting space. + Sends the whole project; the space is selected by its + ``areaDescription`` and must exist in + ``project.lighting.wholeBldgUse[].activityUse[]``. + Args: - interior_space: The interior space (``InteriorSpace``) to - calculate allowed wattage for. + project: The project containing the interior space. + area_description: The ``areaDescription`` of the interior space + (``InteriorSpace``) to calculate allowed wattage for. energy_code: The energy code for the api end point path. + Defaults to ``project.control.code``. Returns: A dict with the calculated wattage, e.g. ``{"spaceAllowedWattage": 560}``. """ - interior_space_data = interior_space.model_dump(mode="json") + project_data = project.model_dump(mode="json") response = self._service.interior_space_allowed_wattage( - interior_space_data, energy_code + project_data, + energy_code or str(project.control.code), + area_description, ) return response.get("data") def calculate_interior_spaces_allowed_wattage( - self, interior_spaces: List[InteriorSpace], energy_code: str + self, project: ComBuilding, energy_code: Optional[str] = None ) -> Any: - """Calculate allowed wattage for a list of interior lighting spaces. + """Calculate allowed wattage for every interior lighting space in a project. + + Sends the whole project; allowed wattage is returned for every + interior space in ``project.lighting.wholeBldgUse[].activityUse[]``. Args: - interior_spaces: The interior spaces (``InteriorSpace`` objects) - to calculate allowed wattage for. + project: The project containing the interior spaces. energy_code: The energy code for the api end point path. + Defaults to ``project.control.code``. Returns: A dict keyed by each interior space's ``areaDescription``, e.g. ``{"Test Space": 610}``. """ - interior_spaces_data = [ - interior_space.model_dump(mode="json") for interior_space in interior_spaces - ] + project_data = project.model_dump(mode="json") response = self._service.interior_spaces_allowed_wattage( - interior_spaces_data, energy_code + project_data, energy_code or str(project.control.code) ) return response.get("data") diff --git a/docs_site/api/operations/envelope.md b/docs_site/api/operations/envelope.md index 3f00520..130b568 100644 --- a/docs_site/api/operations/envelope.md +++ b/docs_site/api/operations/envelope.md @@ -173,8 +173,10 @@ thermal bridges on it. ## Calculating U-values (API) -`COMcheckClient.update_uvalues` sends the envelope to the COMcheck Web API. -It writes the calculated U-values back onto the matching `agWall`, `bgWall`, +`COMcheckClient.update_uvalues` sends the envelope and the project +`location` to the COMcheck Web API. The location is required because the +required U-values depend on the climate zone, so set `project.location` +(`state`, `city`, `climateZone`) first. It writes the calculated U-values back onto the matching `agWall`, `bgWall`, `roof`, and `floor` components (matched by `assemblyType`). It updates the project in place and returns it: diff --git a/docs_site/api/operations/interior-lighting.md b/docs_site/api/operations/interior-lighting.md index 8416140..de39ad6 100644 --- a/docs_site/api/operations/interior-lighting.md +++ b/docs_site/api/operations/interior-lighting.md @@ -164,27 +164,23 @@ keys = il_ops.get_interior_space_keys_from_project(project, area_key) ## Calculating allowed wattage (API) Allowed wattage is calculated server-side via two `COMcheckClient` methods, -not the `il_ops` free functions above. Both take the energy code as an -explicit string (there's no project to pull `control.code` from) — an -`InteriorSpace` alone doesn't carry an energy code: +not the `il_ops` free functions above. Both send the whole project, so add +the interior spaces to the project first. The energy code defaults to +`project.control.code`; pass `energy_code=` to override it: ```python -energy_code = str(project.control.code) - -# Single InteriorSpace -result = client.calculate_interior_space_allowed_wattage(interior_space, energy_code) +# One InteriorSpace, selected by its areaDescription +result = client.calculate_interior_space_allowed_wattage(project, "Open Office") # {"spaceAllowedWattage": 560} -# A list of InteriorSpace objects -results = client.calculate_interior_spaces_allowed_wattage( - [interior_space, second_interior_space], energy_code -) +# Every InteriorSpace in the project +results = client.calculate_interior_spaces_allowed_wattage(project) # {"Open Office": 560, "Conference Room": 610} — keyed by areaDescription ``` -These calls don't mutate the `InteriorSpace` objects passed in or write the -result onto `allowedWattage` — they return the raw calculation payload for -the caller to use as needed. +These calls don't mutate the project or write the result onto +`allowedWattage` — they return the raw calculation payload for the caller to +use as needed. See `examples/project_operations/interior_lighting_operations.py` and `examples/client/allowed_wattage.py` for full walkthroughs. diff --git a/docs_site/api/simulation.md b/docs_site/api/simulation.md index 6a524ad..1615197 100644 --- a/docs_site/api/simulation.md +++ b/docs_site/api/simulation.md @@ -66,8 +66,10 @@ session_id = client.start_run_simulation(project, project_id="your-project-id") ## Envelope u-values `start_run_simulation` always refreshes the calculated envelope u-values -before submitting, by calling `update_uvalues(project)`. This fetches the -proposed/effective u-values for the envelope assemblies and writes them +before submitting, by calling `update_uvalues(project)`. This sends the +envelope assemblies and the project `location` (required — the climate zone +drives the required u-values), fetches the proposed/effective u-values, and +writes them back onto the matching `agWall`, `bgWall`, `roof`, and `floor` components (matched by `assemblyType`). Only these assembly types receive calculated u-values, and `effectiveUFactor` applies to `agWall` only. diff --git a/examples/README.md b/examples/README.md index a3fc7c1..a69bae9 100644 --- a/examples/README.md +++ b/examples/README.md @@ -61,8 +61,8 @@ python examples/client/compliance_and_report.py Demonstrates interior lighting allowed-wattage calculation. **What it demonstrates:** -- `calculate_interior_space_allowed_wattage()` - Calculating allowed wattage for a single InteriorSpace -- `calculate_interior_spaces_allowed_wattage()` - Calculating allowed wattage for a list of InteriorSpace objects +- `calculate_interior_space_allowed_wattage()` - Calculating allowed wattage for one InteriorSpace in a project, selected by `areaDescription` +- `calculate_interior_spaces_allowed_wattage()` - Calculating allowed wattage for every InteriorSpace in a project **Usage:** ```bash diff --git a/examples/client/allowed_wattage.py b/examples/client/allowed_wattage.py index a7dbc09..1a827d4 100644 --- a/examples/client/allowed_wattage.py +++ b/examples/client/allowed_wattage.py @@ -1,9 +1,22 @@ -"""Example of using COMcheck API client interior lighting allowed-wattage calculation.""" +"""Example of using COMcheck API client interior lighting allowed-wattage calculation. + +Both allowed-wattage calls send the whole project, so the interior spaces +must be added to the project first. The energy code defaults to +``project.control.code``. +""" import os from dotenv import load_dotenv +from comcheck_api import ( + project_building_area_operations as ba_ops, + project_interior_lighting_operations as il_ops, +) from comcheck_api.client import COMcheckClient -from comcheck_api.defaults import get_default_interior_space_template +from comcheck_api.defaults import ( + get_default_building_area_template, + get_default_interior_space_template, + get_default_project_template, +) from comcheck_api.types.core_types import ActivityTypeOptions, EnergyCodeOptions # Initialize client @@ -12,26 +25,32 @@ api_key = os.getenv("COM_API_KEY") or "your-api-key-here" client.set_api_key(api_key) -energy_code = str(EnergyCodeOptions.CEZ_90_1_2022) +# Build a project with one building area and two interior spaces. +project = get_default_project_template() +project.control.code = EnergyCodeOptions.CEZ_90_1_2022 + +area = get_default_building_area_template() +area.areaDescription = "Office Area" +project = ba_ops.add_building_area_to_project(project, area) -# Example 1: Calculate allowed wattage for a single InteriorSpace. interior_space = get_default_interior_space_template() interior_space.areaDescription = "Open Office" interior_space.activityType = ActivityTypeOptions.ACTIVITY_COMMON_OFFICE_OPEN interior_space.floorArea = 2000.0 +project = il_ops.add_interior_space_to_project(project, area.key, interior_space) -result = client.calculate_interior_space_allowed_wattage(interior_space, energy_code) -print(f"Allowed wattage: {result}") # e.g. {"spaceAllowedWattage": 560} - -# Example 2: Calculate allowed wattage for a list of InteriorSpace objects. second_interior_space = get_default_interior_space_template() second_interior_space.areaDescription = "Conference Room" second_interior_space.activityType = ActivityTypeOptions.ACTIVITY_COMMON_CONFERENCE_HALL second_interior_space.floorArea = 500.0 +project = il_ops.add_interior_space_to_project(project, area.key, second_interior_space) -results = client.calculate_interior_spaces_allowed_wattage( - [interior_space, second_interior_space], energy_code -) +# Example 1: Calculate allowed wattage for one InteriorSpace, selected by areaDescription. +result = client.calculate_interior_space_allowed_wattage(project, "Open Office") +print(f"Allowed wattage: {result}") # e.g. {"spaceAllowedWattage": 560} + +# Example 2: Calculate allowed wattage for every InteriorSpace in the project. +results = client.calculate_interior_spaces_allowed_wattage(project) print( f"Allowed wattages: {results}" ) # e.g. {"Open Office": 560, "Conference Room": 610} diff --git a/tests/test_comcheck_client.py b/tests/test_comcheck_client.py index e8e4446..c05f2f3 100644 --- a/tests/test_comcheck_client.py +++ b/tests/test_comcheck_client.py @@ -10,8 +10,13 @@ import pytest from dotenv import load_dotenv +from comcheck_api import ( + project_building_area_operations as ba_ops, + project_interior_lighting_operations as il_ops, +) from comcheck_api.client import COMcheckClient from comcheck_api.defaults import ( + get_default_building_area_template, get_default_interior_space_template, get_default_project_template, ) @@ -66,17 +71,36 @@ def test_fetch_single_project(client: COMcheckClient): assert True +def _project_with_interior_spaces(): + """Default project with one building area holding two interior spaces.""" + project = get_default_project_template() + project.control.code = EnergyCodeOptions.CEZ_90_1_2022 + + area = get_default_building_area_template() + area.areaDescription = "Office Area" + project = ba_ops.add_building_area_to_project(project, area) + + first = get_default_interior_space_template() + first.areaDescription = "Open Office" + first.activityType = ActivityTypeOptions.ACTIVITY_COMMON_OFFICE_OPEN + first.floorArea = 2000.0 + project = il_ops.add_interior_space_to_project(project, area.key, first) + + second = get_default_interior_space_template() + second.areaDescription = "Conference Room" + second.activityType = ActivityTypeOptions.ACTIVITY_COMMON_CONFERENCE_HALL + second.floorArea = 500.0 + project = il_ops.add_interior_space_to_project(project, area.key, second) + return project + + def test_calculate_interior_space_allowed_wattage(client: COMcheckClient): - """Test calculating allowed wattage for a single InteriorSpace.""" - interior_space = get_default_interior_space_template() - interior_space.areaDescription = "Open Office" - interior_space.activityType = ActivityTypeOptions.ACTIVITY_COMMON_OFFICE_OPEN - interior_space.floorArea = 2000.0 - energy_code = str(EnergyCodeOptions.CEZ_90_1_2022) + """Test calculating allowed wattage for a single InteriorSpace in a project.""" + project = _project_with_interior_spaces() try: result = client.calculate_interior_space_allowed_wattage( - interior_space, energy_code + project, "Open Office" ) except COMCheckHTTPError as exc: if exc.status_code in (401, 403): @@ -89,23 +113,11 @@ def test_calculate_interior_space_allowed_wattage(client: COMcheckClient): def test_calculate_interior_spaces_allowed_wattage(client: COMcheckClient): - """Test calculating allowed wattage for a list of InteriorSpace objects.""" - first = get_default_interior_space_template() - first.areaDescription = "Open Office" - first.activityType = ActivityTypeOptions.ACTIVITY_COMMON_OFFICE_OPEN - first.floorArea = 2000.0 - - second = get_default_interior_space_template() - second.areaDescription = "Conference Room" - second.activityType = ActivityTypeOptions.ACTIVITY_COMMON_CONFERENCE_HALL - second.floorArea = 500.0 - - energy_code = str(EnergyCodeOptions.CEZ_90_1_2022) + """Test calculating allowed wattage for every InteriorSpace in a project.""" + project = _project_with_interior_spaces() try: - result = client.calculate_interior_spaces_allowed_wattage( - [first, second], energy_code - ) + result = client.calculate_interior_spaces_allowed_wattage(project) except COMCheckHTTPError as exc: if exc.status_code in (401, 403): pytest.skip( diff --git a/tests/test_wattage_uvalues_api.py b/tests/test_wattage_uvalues_api.py new file mode 100644 index 0000000..67a81f8 --- /dev/null +++ b/tests/test_wattage_uvalues_api.py @@ -0,0 +1,175 @@ +"""Offline tests for the allowed-wattage and u-value service and client methods. + +Requests are served by an ``httpx.MockTransport``, so no API key or network +access is needed. +""" + +import json + +import httpx +import pytest + +from comcheck_api import ( + COMcheckClient, + project_building_area_operations as ba_ops, + project_envelope_operations as env_ops, + project_interior_lighting_operations as il_ops, +) +from comcheck_api.api.api_services import COMCheckApiService +from comcheck_api.defaults import ( + get_default_ag_wall_template, + get_default_building_area_template, + get_default_interior_space_template, + get_default_project_template, +) +from comcheck_api.types.core_types import ActivityTypeOptions, EnergyCodeOptions + + +def _make_service(handler) -> COMCheckApiService: + """Build a service whose HTTP client is backed by *handler*.""" + service = COMCheckApiService(api_key="test") + service._client = httpx.Client( + base_url=service.base_url, + headers=service._prepare_headers(), + transport=httpx.MockTransport(handler), + ) + return service + + +def _make_client(handler) -> COMcheckClient: + client = COMcheckClient(api_key="test") + client._api_service = _make_service(handler) + return client + + +def _ok(requests, data): + def handler(request: httpx.Request) -> httpx.Response: + requests.append(request) + return httpx.Response(200, json={"message": "ok", "data": data}) + + return handler + + +@pytest.fixture +def requests(): + return [] + + +@pytest.fixture +def project(): + project = get_default_project_template() + project.control.code = EnergyCodeOptions.CEZ_IECC2021 + + area = get_default_building_area_template() + area.areaDescription = "Office Area" + project = ba_ops.add_building_area_to_project(project, area) + + space = get_default_interior_space_template() + space.areaDescription = "Open Office" + space.activityType = ActivityTypeOptions.ACTIVITY_COMMON_OFFICE_OPEN + space.floorArea = 2000.0 + project = il_ops.add_interior_space_to_project(project, area.key, space) + return project + + +# ── Interior allowed wattage ──────────────────────────────────────────────── + + +def test_single_space_wattage_sends_whole_project_and_area_description( + requests, project +): + client = _make_client(_ok(requests, {"spaceAllowedWattage": 560})) + + result = client.calculate_interior_space_allowed_wattage(project, "Open Office") + + assert result == {"spaceAllowedWattage": 560} + (request,) = requests + assert request.method == "POST" + assert request.url.path.endswith("/CEZ_IECC2021/activity-use/allowed-wattage") + assert request.url.params["areaDescription"] == "Open Office" + assert json.loads(request.content) == project.model_dump(mode="json") + + +def test_single_space_wattage_energy_code_override(requests, project): + client = _make_client(_ok(requests, {"spaceAllowedWattage": 560})) + + client.calculate_interior_space_allowed_wattage( + project, "Open Office", energy_code="CEZ_90_1_2022" + ) + + (request,) = requests + assert request.url.path.endswith("/CEZ_90_1_2022/activity-use/allowed-wattage") + + +def test_multiple_spaces_wattage_sends_whole_project(requests, project): + client = _make_client(_ok(requests, {"Open Office": 560})) + + result = client.calculate_interior_spaces_allowed_wattage(project) + + assert result == {"Open Office": 560} + (request,) = requests + assert request.method == "POST" + assert request.url.path.endswith("/CEZ_IECC2021/activity-uses/allowed-wattage") + assert "areaDescription" not in request.url.params + assert json.loads(request.content) == project.model_dump(mode="json") + + +# ── U-values ──────────────────────────────────────────────────────────────── + + +@pytest.fixture +def project_with_wall(project): + wall = get_default_ag_wall_template() + area_key = project.lighting.wholeBldgUse[-1].key + project = env_ops.add_ag_wall_to_project(project, area_key, wall) + return project + + +def test_update_uvalues_sends_location(requests, project_with_wall): + project = project_with_wall + wall = project.envelope.agWall[0] + data = { + "agWall": [ + { + "assemblyType": wall.assemblyType, + "propUValue": 0.055, + "reqUValue": 0.064, + "effectiveUFactor": 0.06, + } + ] + } + client = _make_client(_ok(requests, data)) + sent_ag_walls = project.envelope.model_dump(mode="json")["agWall"] + + client.update_uvalues(project) + + (request,) = requests + assert request.url.path.endswith("/CEZ_IECC2021/assemblies/uvalues") + body = json.loads(request.content) + assert body["location"] == project.location.model_dump(mode="json") + assert body["agWall"] == sent_ag_walls + assert wall.propUValue == pytest.approx(0.055) + assert wall.effectiveUFactor == pytest.approx(0.06) + + +def test_update_uvalues_keeps_values_when_response_is_null(requests, project_with_wall): + project = project_with_wall + wall = project.envelope.agWall[0] + wall.propUValue = 0.1 + wall.effectiveUFactor = 0.2 + data = { + "agWall": [ + { + "assemblyType": wall.assemblyType, + "propUValue": None, + "reqUValue": None, + "effectiveUFactor": None, + } + ] + } + client = _make_client(_ok(requests, data)) + + client.update_uvalues(project) + + assert wall.propUValue == pytest.approx(0.1) + assert wall.effectiveUFactor == pytest.approx(0.2)