Skip to content

Commit c647902

Browse files
committed
fix: make outPath accept both str and Path
1 parent aaa578f commit c647902

File tree

7 files changed

+54
-49
lines changed

7 files changed

+54
-49
lines changed

src/onc/modules/_DataProductFile.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from pathlib import Path
12
from time import sleep, time
23
from warnings import warn
34

@@ -41,7 +42,7 @@ def download(
4142
self,
4243
timeout: int,
4344
pollPeriod: float,
44-
outPath: str,
45+
outPath: Path,
4546
maxRetries: int,
4647
overwrite: bool,
4748
):

src/onc/modules/_OncArchive.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import time
3+
from pathlib import Path
34

45
import humanize
56
import requests
@@ -50,7 +51,7 @@ def getFile(self, filename: str = "", overwrite: bool = False):
5051

5152
if response.ok:
5253
# Save file to output path
53-
outPath = self._config("outPath")
54+
outPath: Path = self._config("outPath")
5455
saveAsFile(response, outPath, filename, overwrite)
5556

5657
else:
@@ -109,8 +110,8 @@ def getDirectFiles(
109110
downInfos = []
110111
for filename in dataRows["files"]:
111112
# only download if file doesn't exist (or overwrite is True)
112-
outPath = self._config("outPath")
113-
filePath = f"{outPath}/{filename}"
113+
outPath: Path = self._config("outPath")
114+
filePath = outPath / filename
114115
fileExists = os.path.exists(filePath)
115116

116117
if (not fileExists) or (fileExists and overwrite):

src/onc/modules/_util.py

+7-11
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,24 @@
1-
import os
21
from datetime import timedelta
2+
from pathlib import Path
33

44
import humanize
55
import requests
66

77

88
def saveAsFile(
9-
response: requests.Response, filePath: str, fileName: str, overwrite: bool
9+
response: requests.Response, outPath: Path, fileName: str, overwrite: bool
1010
) -> None:
1111
"""
1212
Saves the file downloaded in the response object, in the outPath, with filename
1313
If overwrite, will overwrite files with the same name
1414
"""
15-
fullPath = fileName
16-
if len(filePath) > 0:
17-
fullPath = filePath + "/" + fileName
18-
# Create outPath directory if not exists
19-
if not os.path.exists(filePath):
20-
os.makedirs(filePath)
15+
filePath = outPath / fileName
16+
outPath.mkdir(parents=True, exist_ok=True)
2117

2218
# Save file in outPath if it doesn't exist yet
23-
if os.path.exists(fullPath) and not overwrite:
24-
raise FileExistsError(str(fullPath))
25-
with open(fullPath, "wb+") as file:
19+
if Path.exists(filePath) and not overwrite:
20+
raise FileExistsError(str(filePath))
21+
with open(filePath, "wb+") as file:
2622
file.write(response.content)
2723

2824

src/onc/onc.py

+8-11
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,7 @@ def __init__(
3030
self.showInfo = showInfo
3131
self.timeout = timeout
3232
self.baseUrl = "https://data.oceannetworks.ca/"
33-
self.outPath = ""
34-
35-
outPath = str(outPath)
36-
# sanitize outPath
37-
if len(outPath) > 0:
38-
outPath = outPath.replace("\\", "/")
39-
if outPath[-1] == "/":
40-
outPath = outPath[:-1]
41-
self.outPath = outPath
33+
self.outPath = Path(outPath)
4234

4335
# switch to qa if needed
4436
if not production:
@@ -53,13 +45,18 @@ def __init__(
5345
def print(self, obj, filename: str = ""):
5446
"""
5547
Helper for printing a JSON dictionary to the console or to a file
56-
@filename: if present, creates the file and writes the output in it
48+
@filename: if present, creates a file with a ".json" extension
49+
in "self.outPath" directory, and writes the output to the file.
50+
if not present, prints the output to the console.
5751
"""
5852
text = json.dumps(obj, indent=4)
5953
if filename == "":
6054
print(text)
6155
else:
62-
with open(filename, "w+") as file:
56+
filePath = self.outPath / filename
57+
filePath = filePath.with_suffix(".json")
58+
59+
with open(filePath, "w+") as file:
6360
file.write(text)
6461

6562
def formatUtc(self, dateString: str = "now"):

tests/README.md

+29-21
Original file line numberDiff line numberDiff line change
@@ -1,84 +1,94 @@
11
# Testing Documentation
22

3-
This directory contains an automated test suite written for the Python API client using
3+
This directory contains an automated test suite written for the Python API client using
44
the [Robot Framework](http://robotframework.org) (RF from now on) as well as pytest.
55

66
Directory structure is as follows:
77

8-
* libraries: Python 3 library files used in the tests
9-
* output: Default output directory for methods that download files (i.e. orderDataProduct())
10-
* pytests: Tests converted from RF to pytest format
11-
* resources: Robot generic scripts to be reused by tests
12-
* suites: Test suites
8+
- libraries: Python 3 library files used in the tests
9+
- output: Default output directory for methods that download files (i.e. orderDataProduct())
10+
- pytests: Tests converted from RF to pytest format
11+
- resources: Robot generic scripts to be reused by tests
12+
- suites: Test suites
1313

1414
Read the test suites (.robot files) in "suites" to understand what exactly is being tested.
1515
Test suites contain the test cases in the "Test Cases" section, and are written in a language similar to english.
1616

17-
1817
## Testing Requirements
1918

2019
1. Make sure Python 3 and pip are installed properly. It is highly suggested to use a virtual environment.
2120
2. Install [Robot Framework](https://robotframework.org/) and [python-dotenv](https://saurabh-kumar.com/python-dotenv/)
21+
2222
```shell
2323
pip install robotframework python-dotenv
2424
```
25+
2526
(or use "pip3" depending on your system configuration)
2627

2728
3. Optional: install [pabot](https://pabot.org/) for test parallelization:
29+
2830
```shell
2931
pip install -U robotframework-pabot
3032
```
33+
3134
4. Install this project in editable mode (assume the current directory is the root)
35+
3236
```shell
3337
pip install -e .
3438
```
3539

36-
3740
## Running the Tests
3841

39-
In the terminal, run all tests from the root directory.
42+
In the terminal, run all tests from the root directory.
4043
Tests can also be run from a different folder. Just change the relative path of the test suites.
4144

4245
Create a `.env` file under tests folder and put TOKEN variable in the file.
4346
If you are on Windows, make sure the encoding of `.env` file is UTF-8 after using the command below.
47+
4448
```shell
4549
echo TOKEN=${YOUR_TOKEN} > .env
4650
```
4751

48-
The default testing environment is PROD. If you are an internal developer, add the following line to .env so that the tests are running against QA.
52+
The default testing environment is PROD. If you are an internal developer, add the following line to .env so that the tests are running against QA.
4953

5054
```shell
5155
echo ONC_ENV=QA >> .env
5256
```
57+
5358
Change ONC_ENV value from QA to PROD if testing in PROD is needed. Removing the line also does the trick.
5459

55-
*To run all the RF test suites (parallelized):*
60+
_To run all the RF test suites (parallelized):_
61+
5662
```shell
57-
pabot --testlevelsplit tests/suites
63+
pabot --testlevelsplit tests/robot/suites
5864
```
5965

60-
*To run a single RF test suite (replace 0X with the prefix of the test file name, e.g., 01):*
66+
_To run a single RF test suite (replace 0X with the prefix of the test file name, e.g., 01):_
67+
6168
```shell
6269
robot tests/suites/01* # robot tests/suites/0X*
6370
```
6471

65-
*To run a single RF test in a test suite (replace Y with the prefix of the test name, e.g., 01):*
72+
_To run a single RF test in a test suite (replace Y with the prefix of the test name, e.g., 01):_
73+
6674
```shell
6775
robot --test "01*" tests/suites/01* # robot --test "Y*" tests/suites/0X*
6876
```
6977

70-
*To run pytest*
78+
_To run pytest_
79+
7180
```shell
7281
pytest
7382
```
7483

75-
*`--variable TOKEN:${YOUR_TOKEN}` can be used if no `.env` file is present*
84+
_`--variable TOKEN:${YOUR_TOKEN}` can be used if no `.env` file is present_
85+
7686
```shell
7787
robot --variable TOKEN:${YOUR_TOKEN} tests/suites/01*
7888
```
7989

8090
Additionally, You can check the three bash files (testall, testcoverage and testsuite) for running the test suites.
81-
Robot Framework also has plugins for IDEs like VS Code and Pycharm that makes running tests easier.
91+
Robot Framework also has plugins for IDEs like VS Code and Pycharm that makes running tests easier.
8292

8393
After tests finish, review the summary and logs in the root directory.
8494

@@ -92,18 +102,16 @@ just make the required changes, no coding knowledge is required.
92102
For anything more advanced than that, please read the Robot Framework Documentation and consider keeping
93103
the directory structure relevant.
94104

95-
96105
## Code Documentation
97106

98107
Robot Framework promotes test cases written almost in plain english (if you need to document it, you're writing it wrong).
99-
Still, code documentation is welcome if ever required.
108+
Still, code documentation is welcome if ever required.
100109
If you are an internal user of Ocean Networks Canada, please refer to the [internal documentation page](https://internal.oceannetworks.ca/display/ONCData/11+-+Automated+User+Tests+for+API+Client+Libraries).
101110

102-
103111
## Acknowledgements
104112

105113
Initial author: Dany Cabrera
106114

107115
Maintainers: Kan Fu
108116

109-
Previous maintainers: Dany Cabrera
117+
Previous maintainers: Dany Cabrera

tests/robot/libraries/delivery.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# delivery services' tests
22

3+
from pathlib import Path
4+
35
from common import onc
46

57

@@ -15,7 +17,7 @@ def manualRunProduct(dpRequestId: int):
1517

1618
def manualDownloadProduct(dpRunId: int, outPath: str = "", resultsOnly: bool = False):
1719
# Manually downloads runId
18-
onc.outPath = outPath
20+
onc.outPath = Path(outPath)
1921
return onc.downloadDataProduct(dpRunId, downloadResultsOnly=resultsOnly)
2022

2123

tests/robot/suites/00__initial.robot

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,5 @@ Resource ../resources/general.robot
2020
Prepare output directory output/00/03
2121
${onc3}= Make ONC with path output/00/03
2222
${result}= Call Method ${onc3} getLocations ${F_LOCATIONCODE}
23-
Call Method ${onc3} print ${result} output/00/03/03.json
23+
Call Method ${onc3} print ${result} 03.json
2424
File Should Exist output/00/03/03.json

0 commit comments

Comments
 (0)