File: test_upload.py

package info (click to toggle)
pydataverse 0.3.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,168 kB
  • sloc: python: 4,862; sh: 61; makefile: 13
file content (291 lines) | stat: -rw-r--r-- 9,691 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import json
import os
import tempfile

import httpx

from pyDataverse.api import DataAccessApi, NativeApi
from pyDataverse.models import Datafile


class TestFileUpload:
    def test_file_upload(self):
        """
        Test case for uploading a file to a dataset.

        This test case performs the following steps:
        1. Creates a dataset using the provided metadata.
        2. Prepares a file for upload.
        3. Uploads the file to the dataset.
        4. Asserts that the file upload was successful.

        Raises:
            AssertionError: If the file upload fails.

        """
        # Arrange
        BASE_URL = os.getenv("BASE_URL").rstrip("/")
        API_TOKEN = os.getenv("API_TOKEN")

        # Create dataset
        metadata = json.load(open("tests/data/file_upload_ds_minimum.json"))
        pid = self._create_dataset(BASE_URL, API_TOKEN, metadata)
        api = NativeApi(BASE_URL, API_TOKEN)

        # Prepare file upload
        df = Datafile({"pid": pid, "filename": "datafile.txt"})

        # Act
        response = api.upload_datafile(
            identifier=pid,
            filename="tests/data/datafile.txt",
            json_str=df.json(),
        )

        # Assert
        assert response.status_code == 200, "File upload failed."

    def test_file_upload_without_metadata(self):
        """
        Test case for uploading a file to a dataset without metadata.

        --> json_str will be set as None

        This test case performs the following steps:
        1. Creates a dataset using the provided metadata.
        2. Prepares a file for upload.
        3. Uploads the file to the dataset.
        4. Asserts that the file upload was successful.

        Raises:
            AssertionError: If the file upload fails.

        """
        # Arrange
        BASE_URL = os.getenv("BASE_URL").rstrip("/")
        API_TOKEN = os.getenv("API_TOKEN")

        # Create dataset
        metadata = json.load(open("tests/data/file_upload_ds_minimum.json"))
        pid = self._create_dataset(BASE_URL, API_TOKEN, metadata)
        api = NativeApi(BASE_URL, API_TOKEN)

        # Act
        response = api.upload_datafile(
            identifier=pid,
            filename="tests/data/datafile.txt",
            json_str=None,
        )

        # Assert
        assert response.status_code == 200, "File upload failed."

    def test_bulk_file_upload(self, create_mock_file):
        """
        Test case for uploading bulk files to a dataset.

        This test is meant to check the performance of the file upload feature
        and that nothing breaks when uploading multiple files in line.

        This test case performs the following steps:
        0. Create 50 mock files.
        1. Creates a dataset using the provided metadata.
        2. Prepares a file for upload.
        3. Uploads the file to the dataset.
        4. Asserts that the file upload was successful.

        Raises:
            AssertionError: If the file upload fails.

        """
        # Arrange
        BASE_URL = os.getenv("BASE_URL").rstrip("/")
        API_TOKEN = os.getenv("API_TOKEN")

        # Create dataset
        metadata = json.load(open("tests/data/file_upload_ds_minimum.json"))
        pid = self._create_dataset(BASE_URL, API_TOKEN, metadata)
        api = NativeApi(BASE_URL, API_TOKEN)

        with tempfile.TemporaryDirectory() as tmp_dir:
            # Create mock files
            mock_files = [
                create_mock_file(
                    filename=f"mock_file_{i}.txt",
                    dir=tmp_dir,
                    size=1024**2,  # 1MB
                )
                for i in range(50)
            ]

            for mock_file in mock_files:
                # Prepare file upload
                df = Datafile({"pid": pid, "filename": os.path.basename(mock_file)})

                # Act
                response = api.upload_datafile(
                    identifier=pid,
                    filename=mock_file,
                    json_str=df.json(),
                )

                # Assert
                assert response.status_code == 200, "File upload failed."

    def test_file_replacement_wo_metadata(self):
        """
        Test case for replacing a file in a dataset without metadata.

        Steps:
        1. Create a dataset using the provided metadata.
        2. Upload a datafile to the dataset.
        3. Replace the uploaded datafile with a mutated version.
        4. Verify that the file replacement was successful and the content matches the expected content.
        """

        # Arrange
        BASE_URL = os.getenv("BASE_URL").rstrip("/")
        API_TOKEN = os.getenv("API_TOKEN")

        # Create dataset
        metadata = json.load(open("tests/data/file_upload_ds_minimum.json"))
        pid = self._create_dataset(BASE_URL, API_TOKEN, metadata)
        api = NativeApi(BASE_URL, API_TOKEN)
        data_api = DataAccessApi(BASE_URL, API_TOKEN)

        # Perform file upload
        df = Datafile({"pid": pid, "filename": "datafile.txt"})
        response = api.upload_datafile(
            identifier=pid,
            filename="tests/data/replace.xyz",
            json_str=df.json(),
        )

        # Retrieve file ID
        file_id = response.json()["data"]["files"][0]["dataFile"]["id"]

        # Act
        with tempfile.TemporaryDirectory() as tempdir:
            original = open("tests/data/replace.xyz").read()
            mutated = "Z" + original[1::]
            mutated_path = os.path.join(tempdir, "replace.xyz")

            with open(mutated_path, "w") as f:
                f.write(mutated)

            json_data = {}

            response = api.replace_datafile(
                identifier=file_id,
                filename=mutated_path,
                json_str=json.dumps(json_data),
                is_filepid=False,
            )

        # Assert
        file_id = response.json()["data"]["files"][0]["dataFile"]["id"]
        content = data_api.get_datafile(file_id, is_pid=False).text

        assert response.status_code == 200, "File replacement failed."
        assert content == mutated, "File content does not match the expected content."

    def test_file_replacement_w_metadata(self):
        """
        Test case for replacing a file in a dataset with metadata.

        Steps:
        1. Create a dataset using the provided metadata.
        2. Upload a datafile to the dataset.
        3. Replace the uploaded datafile with a mutated version.
        4. Verify that the file replacement was successful and the content matches the expected content.
        """

        # Arrange
        BASE_URL = os.getenv("BASE_URL").rstrip("/")
        API_TOKEN = os.getenv("API_TOKEN")

        # Create dataset
        metadata = json.load(open("tests/data/file_upload_ds_minimum.json"))
        pid = self._create_dataset(BASE_URL, API_TOKEN, metadata)
        api = NativeApi(BASE_URL, API_TOKEN)
        data_api = DataAccessApi(BASE_URL, API_TOKEN)

        # Perform file upload
        df = Datafile({"pid": pid, "filename": "datafile.txt"})
        response = api.upload_datafile(
            identifier=pid,
            filename="tests/data/replace.xyz",
            json_str=df.json(),
        )

        # Retrieve file ID
        file_id = response.json()["data"]["files"][0]["dataFile"]["id"]

        # Act
        with tempfile.TemporaryDirectory() as tempdir:
            original = open("tests/data/replace.xyz").read()
            mutated = "Z" + original[1::]
            mutated_path = os.path.join(tempdir, "replace.xyz")

            with open(mutated_path, "w") as f:
                f.write(mutated)

            json_data = {
                "description": "My description.",
                "categories": ["Data"],
                "forceReplace": False,
                "directoryLabel": "some/other",
            }

            response = api.replace_datafile(
                identifier=file_id,
                filename=mutated_path,
                json_str=json.dumps(json_data),
                is_filepid=False,
            )

        # Assert
        file_id = response.json()["data"]["files"][0]["dataFile"]["id"]
        data_file = api.get_dataset(pid).json()["data"]["latestVersion"]["files"][0]
        content = data_api.get_datafile(file_id, is_pid=False).text

        assert (
            data_file["description"] == "My description."
        ), "Description does not match."
        assert data_file["categories"] == ["Data"], "Categories do not match."
        assert (
            data_file["directoryLabel"] == "some/other"
        ), "Directory label does not match."
        assert response.status_code == 200, "File replacement failed."
        assert content == mutated, "File content does not match the expected content."

    @staticmethod
    def _create_dataset(
        BASE_URL: str,
        API_TOKEN: str,
        metadata: dict,
    ):
        """
        Create a dataset in the Dataverse.

        Args:
            BASE_URL (str): The base URL of the Dataverse instance.
            API_TOKEN (str): The API token for authentication.
            metadata (dict): The metadata for the dataset.

        Returns:
            str: The persistent identifier (PID) of the created dataset.
        """
        url = f"{BASE_URL}/api/dataverses/root/datasets"
        response = httpx.post(
            url=url,
            json=metadata,
            headers={
                "X-Dataverse-key": API_TOKEN,
                "Content-Type": "application/json",
            },
        )

        response.raise_for_status()

        return response.json()["data"]["persistentId"]