Skip to content

Commit a34675e

Browse files
authored
Remove environment variable for unit tests. (#164)
Tests will setup environment variables if needed.
2 parents 61cbba2 + ef53af2 commit a34675e

File tree

6 files changed

+158
-81
lines changed

6 files changed

+158
-81
lines changed

.github/workflows/run-unittests-default_setup.yml

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@ on:
44
pull_request:
55
branches:
66
- main
7-
- 'release/**'
7+
- "release/**"
88
- develop
99
paths:
10-
- 'ads/**'
10+
- "ads/**"
1111
- setup.py
12-
- '**requirements.txt'
12+
- "**requirements.txt"
13+
- .github/workflows/run-unittests.yml
14+
- .github/workflows/run-unittests-default_setup.yml
1315

1416
# Cancel in progress workflows on pull_requests.
1517
# https://docs.github.com/en/actions/using-jobs/using-concurrency#example-using-a-fallback-value
@@ -74,7 +76,6 @@ jobs:
7476
timeout-minutes: 15
7577
shell: bash
7678
env:
77-
NB_SESSION_COMPARTMENT_OCID: ocid1.compartment.oc1.<unique_ocid>
7879
NoDependency: True
7980
run: |
8081
set -x # print commands that are executed

.github/workflows/run-unittests.yml

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@ on:
44
pull_request:
55
branches:
66
- main
7-
- 'release/**'
7+
- "release/**"
88
- develop
99
paths:
10-
- 'ads/**'
10+
- "ads/**"
1111
- setup.py
12-
- '**requirements.txt'
12+
- "**requirements.txt"
13+
- .github/workflows/run-unittests.yml
14+
- .github/workflows/run-unittests-default_setup.yml
1315

1416
# Cancel in progress workflows on pull_requests.
1517
# https://docs.github.com/en/actions/using-jobs/using-concurrency#example-using-a-fallback-value
@@ -85,22 +87,21 @@ jobs:
8587
shell: bash
8688
run: |
8789
set -x # print commands that are executed
88-
90+
8991
sudo apt-get install libkrb5-dev graphviz
9092
$CONDA/bin/conda init
9193
source /home/runner/.bashrc
92-
94+
9395
pip install -r dev-requirements.txt
9496
9597
- name: "Run unitary tests folder with maximum ADS dependencies"
9698
timeout-minutes: 60
9799
shell: bash
98100
env:
99-
NB_SESSION_COMPARTMENT_OCID: ocid1.compartment.oc1.<unique_ocid>
100101
CONDA_PREFIX: /usr/share/miniconda
101102
run: |
102103
set -x # print commands that are executed
103-
104+
104105
# Setup project and tests folder for cov reports to not be overwritten by another parallel step
105106
if [[ ! -z "${{ matrix.cov-reports }}" ]]; then
106107
mkdir -p cov-${{ matrix.name }}
@@ -109,7 +110,7 @@ jobs:
109110
ln -s ../ads ads
110111
ln -s ../.coveragerc .coveragerc
111112
fi
112-
113+
113114
# Run tests
114115
python -m pytest -v -p no:warnings --durations=5 \
115116
-n auto --dist loadfile ${{ matrix.cov-reports }} \
@@ -145,18 +146,18 @@ jobs:
145146
- name: "Calculate overall coverage"
146147
run: |
147148
set -x # print commands that are executed
148-
149+
149150
# Prepare default cov body text
150151
COV_BODY_INTRO="📌 Overall coverage:\n\n"
151152
echo COV_BODY="$COV_BODY_INTRO No success to gather report. 😿" >> $GITHUB_ENV
152-
153+
153154
# Combine coverage files
154155
pip install coverage
155156
coverage combine cov-reports-unitary/.coverage cov-reports-model/.coverage
156-
157+
157158
# Make html report
158159
coverage html
159-
160+
160161
# Calculate overall coverage and update body message
161162
COV=$(grep -E 'pc_cov' htmlcov/index.html | cut -d'>' -f 2 | cut -d'%' -f 1)
162163
if [[ ! -z $COV ]]; then
@@ -168,18 +169,18 @@ jobs:
168169
if: always()
169170
run: |
170171
set -x # print commands that are executed
171-
172+
172173
# Prepare default diff body text
173174
DIFF_BODY_INTRO="📌 Cov diff with **${{ env.COMPARE_BRANCH }}**:\n\n"
174175
echo DIFF_BODY="$DIFF_BODY_INTRO No success to gather report. 😿" >> $GITHUB_ENV
175-
176+
176177
# Prepare file paths to coverage xml files
177178
# Filenames taken from job.test last step with name - "Save coverage files"
178179
FILE1="cov-reports-unitary/coverage.xml"; [[ ! -f $FILE1 ]] && FILE1=""
179180
FILE2="cov-reports-model/coverage.xml"; [[ ! -f $FILE2 ]] && FILE2=""
180181
echo "FILE1=$FILE1" >> $GITHUB_ENV
181182
echo "FILE2=$FILE2" >> $GITHUB_ENV
182-
183+
183184
# Calculate coverage diff and update body message
184185
pip install diff_cover
185186
diff-cover $FILE1 $FILE2 --compare-branch=origin/${{ env.COMPARE_BRANCH }}

tests/unitary/default_setup/auth/test_auth.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,8 @@ def test_get_signer_with_api_keys(
8080
mock_rp_signer.assert_called_once()
8181

8282
@mock.patch("oci.auth.signers.get_resource_principals_signer")
83+
@mock.patch.dict(os.environ, {"OCI_RESOURCE_PRINCIPAL_VERSION": "2.2"})
8384
def test_resource_principal(self, mock_rp_signer):
84-
os.environ["OCI_RESOURCE_PRINCIPAL_VERSION"] = "2.2"
8585
resource_principal()
8686
mock_rp_signer.assert_called_once()
8787

@@ -264,11 +264,11 @@ def test_api_key_create_signer(
264264
assert "test" in signer["client_kwargs"]
265265

266266
@mock.patch("oci.auth.signers.get_resource_principals_signer")
267+
@mock.patch.dict(os.environ, {"OCI_RESOURCE_PRINCIPAL_VERSION": "2.2"})
267268
def test_resource_principal_create_signer(self, mock_rp_signer):
268269
"""
269270
Testing resource principal setup with set_auth() and getting it with default_signer()
270271
"""
271-
os.environ["OCI_RESOURCE_PRINCIPAL_VERSION"] = "2.2"
272272
set_auth(AuthType.RESOURCE_PRINCIPAL)
273273
signer = default_signer(client_kwargs={"test": "test"})
274274
assert "additional_user_agent" in signer["config"]

tests/unitary/default_setup/catalog/test_catalog_notebook.py

Lines changed: 55 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,25 @@
33
# Copyright (c) 2021, 2023 Oracle and/or its affiliates.
44
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
55

6-
from ads.catalog.notebook import NotebookCatalog, NotebookSummaryList
7-
from ads.common import auth, oci_client
8-
from ads.common.utils import random_valid_ocid
9-
from ads.config import NB_SESSION_COMPARTMENT_OCID, PROJECT_OCID
6+
import os
7+
import unittest
108
from collections import namedtuple
119
from datetime import datetime, timezone, timedelta
12-
from oci.exceptions import ServiceError
10+
from importlib import reload
1311
from unittest import mock
1412
from unittest.mock import MagicMock, Mock, patch
13+
1514
import oci
16-
import os
1715
import pandas as pd
1816
import pytest
19-
import unittest
17+
from oci.exceptions import ServiceError
18+
19+
import ads.config
20+
import ads.catalog.notebook
21+
from ads.catalog.notebook import NotebookCatalog, NotebookSummaryList
22+
from ads.common import auth, oci_client
23+
from ads.common.utils import random_valid_ocid
24+
from ads.config import PROJECT_OCID
2025

2126

2227
def generate_notebook_list(
@@ -64,33 +69,57 @@ def generate_notebook_list(
6469
class NotebookCatalogTest(unittest.TestCase):
6570
"""Contains test cases for catalog.notebook"""
6671

67-
with patch.object(auth, "default_signer"):
68-
with patch.object(oci_client, "OCIClientFactory"):
69-
notebook_catalog = NotebookCatalog()
70-
notebook_catalog.ds_client = MagicMock()
71-
notebook_catalog.identity_client = MagicMock()
72+
@classmethod
73+
def setUpClass(cls) -> None:
74+
os.environ[
75+
"NB_SESSION_COMPARTMENT_OCID"
76+
] = "ocid1.compartment.oc1.<unique_ocid>"
77+
reload(ads.config)
78+
ads.catalog.notebook.NB_SESSION_COMPARTMENT_OCID = (
79+
ads.config.NB_SESSION_COMPARTMENT_OCID
80+
)
81+
# Initialize class properties after reloading
82+
with patch.object(auth, "default_signer"):
83+
with patch.object(oci_client, "OCIClientFactory"):
84+
cls.notebook_id = "ocid1.notebookcatalog.oc1.iad.<unique_ocid>"
85+
cls.comp_id = os.environ.get(
86+
"NB_SESSION_COMPARTMENT_OCID",
87+
"ocid1.compartment.oc1.iad.<unique_ocid>",
88+
)
89+
cls.date_time = datetime(
90+
2020, 7, 1, 18, 24, 42, 110000, tzinfo=timezone.utc
91+
)
92+
93+
cls.notebook_catalog = NotebookCatalog(compartment_id=cls.comp_id)
94+
cls.notebook_catalog.ds_client = MagicMock()
95+
cls.notebook_catalog.identity_client = MagicMock()
7296

73-
notebook_id = "ocid1.notebookcatalog.oc1.iad.<unique_ocid>"
74-
comp_id = os.environ.get("NB_SESSION_COMPARTMENT_OCID")
75-
date_time = datetime(2020, 7, 1, 18, 24, 42, 110000, tzinfo=timezone.utc)
97+
cls.nsl = NotebookSummaryList(generate_notebook_list())
98+
return super().setUpClass()
7699

77-
nsl = NotebookSummaryList(generate_notebook_list())
100+
@classmethod
101+
def tearDownClass(cls) -> None:
102+
os.environ.pop("NB_SESSION_COMPARTMENT_OCID", None)
103+
reload(ads.config)
104+
ads.catalog.notebook.NB_SESSION_COMPARTMENT_OCID = (
105+
ads.config.NB_SESSION_COMPARTMENT_OCID
106+
)
107+
return super().tearDownClass()
78108

79109
@staticmethod
80-
def generate_notebook_response_data(self, compartment_id=None, notebook_id=None):
110+
def generate_notebook_response_data(compartment_id=None, notebook_id=None):
81111
entity_item = {
82112
"compartment_id": compartment_id,
83113
"created_by": "mock_user",
84114
"defined_tags": {},
85115
"display_name": "my new notebook catalog",
86116
"freeform_tags": {},
87117
"id": notebook_id,
88-
"lifecycle_state": "",
89118
"lifecycle_state": "ACTIVE",
90119
"notebook_session_configuration_details": "",
91120
"notebook_session_url": "oci://notebook_session_url@test_namespace",
92121
"project_id": PROJECT_OCID,
93-
"time_created": self.date_time.isoformat(),
122+
"time_created": NotebookCatalogTest.date_time.isoformat(),
94123
}
95124
notebook_response = oci.data_science.models.NotebookSession(**entity_item)
96125
return notebook_response
@@ -107,12 +136,15 @@ def test_notebook_init_with_compartment_id(self, mock_client, mock_signer):
107136
def test_notebook_init_without_compartment_id(self, mock_client, mock_signer):
108137
"""Test notebook catalog initiation without compartment_id."""
109138
test_notebook_catalog = NotebookCatalog()
110-
assert test_notebook_catalog.compartment_id == NB_SESSION_COMPARTMENT_OCID
139+
assert (
140+
test_notebook_catalog.compartment_id
141+
== ads.config.NB_SESSION_COMPARTMENT_OCID
142+
)
111143

112144
def test_decorate_notebook_session_attributes(self):
113145
"""Test NotebookCatalog._decorate_notebook_session method."""
114146
notebook = self.generate_notebook_response_data(
115-
self, compartment_id=self.comp_id, notebook_id=self.notebook_id
147+
compartment_id=self.comp_id, notebook_id=self.notebook_id
116148
)
117149

118150
def generate_get_user_data(self, compartment_id=None):
@@ -173,7 +205,6 @@ def test_get_notebook_session_with_short_id(self):
173205
def mock_get_notebook_session(notebook_id=id):
174206
return Mock(
175207
data=self.generate_notebook_response_data(
176-
self,
177208
compartment_id=self.comp_id,
178209
notebook_id=short_id_index[short_id],
179210
)
@@ -298,7 +329,7 @@ def test_update_notebook_session_with_short_id(self):
298329
wrapper = namedtuple("wrapper", ["data"])
299330
client_update_notebook_session_response = wrapper(
300331
data=self.generate_notebook_response_data(
301-
self, compartment_id=self.comp_id, notebook_id=short_id_index[short_id]
332+
compartment_id=self.comp_id, notebook_id=short_id_index[short_id]
302333
)
303334
)
304335
self.notebook_catalog.ds_client.update_notebook_session = MagicMock(
@@ -345,5 +376,5 @@ def test_notebook_summary_list_filter_invalid_param(self):
345376
# selection is a notebook session instance
346377
with pytest.raises(ValueError):
347378
self.nsl.filter(
348-
selection=self.generate_notebook_response_data(self), instance=None
379+
selection=self.generate_notebook_response_data(), instance=None
349380
)

0 commit comments

Comments
 (0)