openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
tests/Containers/ContainerTests.cs
813lines · modecode
| 1 | using Microsoft.ClientModel.TestFramework; |
| 2 | using NUnit.Framework; |
| 3 | using OpenAI.Containers; |
| 4 | using OpenAI.Tests.Utility; |
| 5 | using System; |
| 6 | using System.ClientModel; |
| 7 | using System.Text.Json; |
| 8 | using System.Threading; |
| 9 | using System.Threading.Tasks; |
| 10 | using static OpenAI.Tests.TestHelpers; |
| 11 | |
| 12 | namespace OpenAI.Tests.Containers; |
| 13 | |
| 14 | [Category("Containers")] |
| 15 | public class ContainerTests : OpenAIRecordedTestBase |
| 16 | { |
| 17 | private static string _testContainerId; |
| 18 | |
| 19 | private ContainerClient GetTestClient() => GetProxiedOpenAIClient<ContainerClient>(TestScenario.Containers); |
| 20 | |
| 21 | public ContainerTests(bool isAsync) : base(isAsync) |
| 22 | { |
| 23 | } |
| 24 | |
| 25 | [OneTimeSetUp] |
| 26 | public async Task SetUp() |
| 27 | { |
| 28 | // Skip setup if there is no API key (e.g., if we are not running live tests). |
| 29 | if (Mode == RecordedTestMode.Playback || string.IsNullOrEmpty(Environment.GetEnvironmentVariable("OPENAI_API_KEY"))) |
| 30 | { |
| 31 | return; |
| 32 | } |
| 33 | |
| 34 | ContainerClient client = GetTestClient<ContainerClient>(TestScenario.Containers); |
| 35 | |
| 36 | // Create a test container that will be used by all tests |
| 37 | ContainerResource result = await client.CreateContainerAsync(new CreateContainerBody($"test-container-{Guid.NewGuid():N}")); |
| 38 | _testContainerId = result.Id; |
| 39 | |
| 40 | Console.WriteLine($"Created test container: {_testContainerId}"); |
| 41 | await Task.Delay(10000); // Wait for the containers to be available |
| 42 | } |
| 43 | |
| 44 | [SetUp] |
| 45 | public void PerTestSetUp() |
| 46 | { |
| 47 | if (Mode == RecordedTestMode.Record) |
| 48 | { |
| 49 | Recording.SetVariable("TEST_CONTAINER_ID", _testContainerId); |
| 50 | } |
| 51 | if (Mode == RecordedTestMode.Playback) |
| 52 | { |
| 53 | _testContainerId = Recording.GetVariable("TEST_CONTAINER_ID", null); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | [OneTimeTearDown] |
| 58 | public async Task TearDown() |
| 59 | { |
| 60 | // Skip teardown if there is no API key or no container was created |
| 61 | if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("OPENAI_API_KEY")) || string.IsNullOrEmpty(_testContainerId)) |
| 62 | { |
| 63 | return; |
| 64 | } |
| 65 | |
| 66 | ContainerClient client = GetTestClient(); |
| 67 | |
| 68 | try |
| 69 | { |
| 70 | await client.DeleteContainerAsync(_testContainerId); |
| 71 | Console.WriteLine($"Deleted test container: {_testContainerId}"); |
| 72 | } |
| 73 | catch (Exception ex) |
| 74 | { |
| 75 | Console.WriteLine($"Failed to delete test container {_testContainerId}: {ex.Message}"); |
| 76 | } |
| 77 | finally |
| 78 | { |
| 79 | _testContainerId = null; |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | private static CreateContainerBody CreateContainerBodyFromName(string name) |
| 84 | { |
| 85 | // Use reflection to create the CreateContainerBody since it only has internal constructors |
| 86 | var createBodyType = typeof(CreateContainerBody); |
| 87 | var constructor = createBodyType.GetConstructors(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)[0]; |
| 88 | return (CreateContainerBody)constructor.Invoke(new object[] { name }); |
| 89 | } |
| 90 | |
| 91 | [RecordedTest] |
| 92 | public async Task CanEnumerateContainers() |
| 93 | { |
| 94 | ContainerClient client = GetTestClient(); |
| 95 | |
| 96 | if (string.IsNullOrEmpty(_testContainerId)) |
| 97 | { |
| 98 | Assert.Ignore("No test container available - likely running without API key"); |
| 99 | return; |
| 100 | } |
| 101 | |
| 102 | // Test GetContainersAsync method with various options |
| 103 | ContainerCollectionOptions options = new() |
| 104 | { |
| 105 | Order = ContainerCollectionOrder.Descending, |
| 106 | PageSizeLimit = 10 |
| 107 | }; |
| 108 | |
| 109 | int count = 0; |
| 110 | bool foundTestContainer = false; |
| 111 | |
| 112 | AsyncCollectionResult<ContainerResource> containers = client.GetContainersAsync(options); |
| 113 | await foreach (ContainerResource container in containers) |
| 114 | { |
| 115 | count++; |
| 116 | Console.WriteLine($"[{count,3}] {container.Id} {container.CreatedAt:s} {container.Name ?? "(no name)"}"); |
| 117 | Validate(container); |
| 118 | |
| 119 | if (container.Id == _testContainerId) |
| 120 | { |
| 121 | foundTestContainer = true; |
| 122 | break; |
| 123 | } |
| 124 | |
| 125 | // Limit enumeration to avoid long test runs |
| 126 | if (count >= 20) |
| 127 | { |
| 128 | break; |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | Assert.That(count, Is.GreaterThan(0), "Should have found at least one container"); |
| 133 | Assert.That(foundTestContainer, Is.True, "Should have found our test container in the enumeration"); |
| 134 | Console.WriteLine($"Found {count} containers, including our test container"); |
| 135 | } |
| 136 | |
| 137 | [RecordedTest] |
| 138 | public async Task CanEnumerateContainerFiles() |
| 139 | { |
| 140 | ContainerClient client = GetTestClient(); |
| 141 | |
| 142 | if (string.IsNullOrEmpty(_testContainerId)) |
| 143 | { |
| 144 | Assert.Ignore("No test container available - likely running without API key"); |
| 145 | return; |
| 146 | } |
| 147 | |
| 148 | // Test GetContainerFilesAsync method |
| 149 | ContainerFileCollectionOptions options = new() |
| 150 | { |
| 151 | Order = ContainerCollectionOrder.Descending, |
| 152 | PageSizeLimit = 10 |
| 153 | }; |
| 154 | |
| 155 | int count = 0; |
| 156 | |
| 157 | AsyncCollectionResult<ContainerFileResource> files = client.GetContainerFilesAsync(_testContainerId, options); |
| 158 | await foreach (ContainerFileResource file in files) |
| 159 | { |
| 160 | Console.WriteLine($"[{count,3}] {file.Id} {file.CreatedAt:s} {file.Path} ({file.Bytes} bytes)"); |
| 161 | Validate(file); |
| 162 | Assert.That(file.ContainerId, Is.EqualTo(_testContainerId), "File should belong to the correct container"); |
| 163 | count++; |
| 164 | |
| 165 | // Limit enumeration to avoid long test runs |
| 166 | if (count >= 20) |
| 167 | { |
| 168 | break; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | Console.WriteLine($"Found {count} files in test container {_testContainerId}"); |
| 173 | // Note: A new container may have no files, so count could be 0 - this is expected |
| 174 | } |
| 175 | |
| 176 | [RecordedTest] |
| 177 | public async Task CanEnumerateContainersWithDefaultOptions() |
| 178 | { |
| 179 | ContainerClient client = GetTestClient(); |
| 180 | |
| 181 | if (string.IsNullOrEmpty(_testContainerId)) |
| 182 | { |
| 183 | Assert.Ignore("No test container available - likely running without API key"); |
| 184 | return; |
| 185 | } |
| 186 | |
| 187 | // Test with default options (null) |
| 188 | int count = 0; |
| 189 | bool foundTestContainer = false; |
| 190 | |
| 191 | AsyncCollectionResult<ContainerResource> containers = client.GetContainersAsync(); |
| 192 | await foreach (ContainerResource container in containers) |
| 193 | { |
| 194 | Console.WriteLine($"[{count,3}] {container.Id} {container.CreatedAt:s} {container.Name ?? "(no name)"}"); |
| 195 | Validate(container); |
| 196 | |
| 197 | if (container.Id == _testContainerId) |
| 198 | { |
| 199 | foundTestContainer = true; |
| 200 | } |
| 201 | |
| 202 | count++; |
| 203 | |
| 204 | // Limit enumeration to avoid long test runs |
| 205 | if (count >= 10) |
| 206 | { |
| 207 | break; |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | Assert.That(count, Is.GreaterThan(0), "Enumeration should work with default options"); |
| 212 | Assert.That(foundTestContainer, Is.True, "Should have found our test container with default options"); |
| 213 | Console.WriteLine($"Found {count} containers with default options, including our test container"); |
| 214 | } |
| 215 | |
| 216 | [RecordedTest] |
| 217 | public async Task CanEnumerateContainerFilesWithDefaultOptions() |
| 218 | { |
| 219 | ContainerClient client = GetTestClient(); |
| 220 | |
| 221 | if (string.IsNullOrEmpty(_testContainerId)) |
| 222 | { |
| 223 | Assert.Ignore("No test container available - likely running without API key"); |
| 224 | return; |
| 225 | } |
| 226 | |
| 227 | // Test with default options (null) |
| 228 | int count = 0; |
| 229 | |
| 230 | AsyncCollectionResult<ContainerFileResource> files = client.GetContainerFilesAsync(_testContainerId); |
| 231 | await foreach (ContainerFileResource file in files) |
| 232 | { |
| 233 | Console.WriteLine($"[{count,3}] {file.Id} {file.CreatedAt:s} {file.Path} ({file.Bytes} bytes)"); |
| 234 | Validate(file); |
| 235 | Assert.That(file.ContainerId, Is.EqualTo(_testContainerId)); |
| 236 | count++; |
| 237 | |
| 238 | // Limit enumeration to avoid long test runs |
| 239 | if (count >= 10) |
| 240 | { |
| 241 | break; |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | Console.WriteLine($"Found {count} files in test container {_testContainerId} with default options"); |
| 246 | } |
| 247 | |
| 248 | [RecordedTest] |
| 249 | public async Task CanEnumerateContainersWithCancellation() |
| 250 | { |
| 251 | ContainerClient client = GetTestClient(); |
| 252 | |
| 253 | if (string.IsNullOrEmpty(_testContainerId)) |
| 254 | { |
| 255 | Assert.Ignore("No test container available - likely running without API key"); |
| 256 | return; |
| 257 | } |
| 258 | |
| 259 | using var cancellationTokenSource = new CancellationTokenSource(); |
| 260 | cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(30)); // Prevent infinite test runs |
| 261 | |
| 262 | ContainerCollectionOptions options = new() |
| 263 | { |
| 264 | PageSizeLimit = 5 |
| 265 | }; |
| 266 | |
| 267 | int count = 0; |
| 268 | |
| 269 | try |
| 270 | { |
| 271 | AsyncCollectionResult<ContainerResource> containers = client.GetContainersAsync(options, cancellationTokenSource.Token); |
| 272 | await foreach (ContainerResource container in containers.WithCancellation(cancellationTokenSource.Token)) |
| 273 | { |
| 274 | Validate(container); |
| 275 | count++; |
| 276 | |
| 277 | // Stop after a few items to test cancellation works |
| 278 | if (count >= 3) |
| 279 | { |
| 280 | break; |
| 281 | } |
| 282 | } |
| 283 | } |
| 284 | catch (OperationCanceledException) |
| 285 | { |
| 286 | // Expected if cancellation occurs |
| 287 | } |
| 288 | |
| 289 | Assert.That(count, Is.GreaterThanOrEqualTo(0), "Enumeration with cancellation should work"); |
| 290 | Console.WriteLine($"Enumerated {count} containers with cancellation"); |
| 291 | } |
| 292 | |
| 293 | [RecordedTest] |
| 294 | public async Task CanEnumerateContainerFilesWithCancellation() |
| 295 | { |
| 296 | ContainerClient client = GetTestClient(); |
| 297 | |
| 298 | if (string.IsNullOrEmpty(_testContainerId)) |
| 299 | { |
| 300 | Assert.Ignore("No test container available - likely running without API key"); |
| 301 | return; |
| 302 | } |
| 303 | |
| 304 | using var cancellationTokenSource = new CancellationTokenSource(); |
| 305 | cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(30)); |
| 306 | |
| 307 | ContainerFileCollectionOptions options = new() |
| 308 | { |
| 309 | PageSizeLimit = 5 |
| 310 | }; |
| 311 | |
| 312 | int count = 0; |
| 313 | |
| 314 | try |
| 315 | { |
| 316 | AsyncCollectionResult<ContainerFileResource> files = client.GetContainerFilesAsync(_testContainerId, options, cancellationTokenSource.Token); |
| 317 | await foreach (ContainerFileResource file in files.WithCancellation(cancellationTokenSource.Token)) |
| 318 | { |
| 319 | Validate(file); |
| 320 | Assert.That(file.ContainerId, Is.EqualTo(_testContainerId)); |
| 321 | count++; |
| 322 | |
| 323 | // Stop after a few items to test cancellation works |
| 324 | if (count >= 3) |
| 325 | { |
| 326 | break; |
| 327 | } |
| 328 | } |
| 329 | } |
| 330 | catch (OperationCanceledException) |
| 331 | { |
| 332 | // Expected if cancellation occurs |
| 333 | } |
| 334 | |
| 335 | Console.WriteLine($"Enumerated {count} files with cancellation token"); |
| 336 | } |
| 337 | |
| 338 | [RecordedTest] |
| 339 | public async Task ContainerCollectionOptionsCanBeConfigured() |
| 340 | { |
| 341 | ContainerClient client = GetTestClient(); |
| 342 | |
| 343 | if (string.IsNullOrEmpty(_testContainerId)) |
| 344 | { |
| 345 | Assert.Ignore("No test container available - likely running without API key"); |
| 346 | return; |
| 347 | } |
| 348 | |
| 349 | // Test different ordering options |
| 350 | var ascendingOptions = new ContainerCollectionOptions() |
| 351 | { |
| 352 | Order = ContainerCollectionOrder.Ascending, |
| 353 | PageSizeLimit = 5 |
| 354 | }; |
| 355 | |
| 356 | var descendingOptions = new ContainerCollectionOptions() |
| 357 | { |
| 358 | Order = ContainerCollectionOrder.Descending, |
| 359 | PageSizeLimit = 5 |
| 360 | }; |
| 361 | |
| 362 | int ascendingCount = 0; |
| 363 | int descendingCount = 0; |
| 364 | |
| 365 | // Test ascending order |
| 366 | AsyncCollectionResult<ContainerResource> ascendingContainers = client.GetContainersAsync(ascendingOptions); |
| 367 | await foreach (ContainerResource container in ascendingContainers) |
| 368 | { |
| 369 | Validate(container); |
| 370 | ascendingCount++; |
| 371 | if (ascendingCount >= 3) break; |
| 372 | } |
| 373 | |
| 374 | // Test descending order |
| 375 | AsyncCollectionResult<ContainerResource> descendingContainers = client.GetContainersAsync(descendingOptions); |
| 376 | await foreach (ContainerResource container in descendingContainers) |
| 377 | { |
| 378 | Validate(container); |
| 379 | descendingCount++; |
| 380 | if (descendingCount >= 3) break; |
| 381 | } |
| 382 | |
| 383 | // Both orderings should work (even if they return the same results) |
| 384 | Assert.That(ascendingCount, Is.GreaterThanOrEqualTo(0)); |
| 385 | Assert.That(descendingCount, Is.GreaterThanOrEqualTo(0)); |
| 386 | Console.WriteLine($"Ascending: {ascendingCount}, Descending: {descendingCount}"); |
| 387 | } |
| 388 | |
| 389 | [RecordedTest] |
| 390 | public async Task ContainerFileCollectionOptionsCanBeConfigured() |
| 391 | { |
| 392 | ContainerClient client = GetTestClient(); |
| 393 | |
| 394 | if (string.IsNullOrEmpty(_testContainerId)) |
| 395 | { |
| 396 | Assert.Ignore("No test container available - likely running without API key"); |
| 397 | return; |
| 398 | } |
| 399 | |
| 400 | // Test different ordering options for files |
| 401 | var ascendingOptions = new ContainerFileCollectionOptions() |
| 402 | { |
| 403 | Order = ContainerCollectionOrder.Ascending, |
| 404 | PageSizeLimit = 5 |
| 405 | }; |
| 406 | |
| 407 | var descendingOptions = new ContainerFileCollectionOptions() |
| 408 | { |
| 409 | Order = ContainerCollectionOrder.Descending, |
| 410 | PageSizeLimit = 5 |
| 411 | }; |
| 412 | |
| 413 | int ascendingCount = 0; |
| 414 | int descendingCount = 0; |
| 415 | |
| 416 | // Test ascending order |
| 417 | AsyncCollectionResult<ContainerFileResource> ascendingFiles = client.GetContainerFilesAsync(_testContainerId, ascendingOptions); |
| 418 | await foreach (ContainerFileResource file in ascendingFiles) |
| 419 | { |
| 420 | Validate(file); |
| 421 | Assert.That(file.ContainerId, Is.EqualTo(_testContainerId)); |
| 422 | ascendingCount++; |
| 423 | if (ascendingCount >= 3) break; |
| 424 | } |
| 425 | |
| 426 | // Test descending order |
| 427 | AsyncCollectionResult<ContainerFileResource> descendingFiles = client.GetContainerFilesAsync(_testContainerId, descendingOptions); |
| 428 | await foreach (ContainerFileResource file in descendingFiles) |
| 429 | { |
| 430 | Validate(file); |
| 431 | Assert.That(file.ContainerId, Is.EqualTo(_testContainerId)); |
| 432 | descendingCount++; |
| 433 | if (descendingCount >= 3) break; |
| 434 | } |
| 435 | |
| 436 | // Both orderings should work (even if they return the same results) |
| 437 | Assert.That(ascendingCount, Is.GreaterThanOrEqualTo(0)); |
| 438 | Assert.That(descendingCount, Is.GreaterThanOrEqualTo(0)); |
| 439 | Console.WriteLine($"Files - Ascending: {ascendingCount}, Descending: {descendingCount}"); |
| 440 | } |
| 441 | |
| 442 | [RecordedTest] |
| 443 | public async Task CanGetContainer() |
| 444 | { |
| 445 | ContainerClient client = GetTestClient(); |
| 446 | |
| 447 | if (string.IsNullOrEmpty(_testContainerId)) |
| 448 | { |
| 449 | Assert.Ignore("No test container available - likely running without API key"); |
| 450 | return; |
| 451 | } |
| 452 | |
| 453 | ClientResult<ContainerResource> result = await client.GetContainerAsync(_testContainerId); |
| 454 | ContainerResource container = result.Value; |
| 455 | |
| 456 | Validate(container); |
| 457 | Assert.That(container.Id, Is.EqualTo(_testContainerId), "Retrieved container should have the correct ID"); |
| 458 | Console.WriteLine($"Retrieved container: {container.Id} with status {container.Status}"); |
| 459 | } |
| 460 | |
| 461 | [RecordedTest] |
| 462 | public async Task CanGetContainerWithCancellation() |
| 463 | { |
| 464 | ContainerClient client = GetTestClient(); |
| 465 | |
| 466 | if (string.IsNullOrEmpty(_testContainerId)) |
| 467 | { |
| 468 | Assert.Ignore("No test container available - likely running without API key"); |
| 469 | return; |
| 470 | } |
| 471 | |
| 472 | using var cancellationTokenSource = new CancellationTokenSource(); |
| 473 | cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(30)); |
| 474 | |
| 475 | ClientResult<ContainerResource> result = await client.GetContainerAsync(_testContainerId, cancellationTokenSource.Token); |
| 476 | ContainerResource container = result.Value; |
| 477 | |
| 478 | Validate(container); |
| 479 | Assert.That(container.Id, Is.EqualTo(_testContainerId)); |
| 480 | Console.WriteLine($"Retrieved container with cancellation: {container.Id}"); |
| 481 | } |
| 482 | |
| 483 | [RecordedTest] |
| 484 | public async Task CanCreateAndDeleteContainerFile() |
| 485 | { |
| 486 | using (Recording.DisableRequestBodyRecording()) // Temp pending https://github.com/Azure/azure-sdk-tools/issues/11901 |
| 487 | { |
| 488 | ContainerClient client = GetTestClient(); |
| 489 | |
| 490 | if (string.IsNullOrEmpty(_testContainerId)) |
| 491 | { |
| 492 | Assert.Ignore("No test container available - likely running without API key"); |
| 493 | return; |
| 494 | } |
| 495 | |
| 496 | // Create a test file using multipart form data |
| 497 | string testContent = "This is a test file content for container testing."; |
| 498 | byte[] contentBytes = System.Text.Encoding.UTF8.GetBytes(testContent); |
| 499 | |
| 500 | // Create multipart form data using the internal helper |
| 501 | var formData = new MultiPartFormDataBinaryContent(); |
| 502 | formData.Add(contentBytes, "file", "test-file.txt", "text/plain"); |
| 503 | |
| 504 | ClientResult createResult = await client.CreateContainerFileAsync(_testContainerId, formData, formData.ContentType); |
| 505 | |
| 506 | Assert.That(createResult, Is.Not.Null); |
| 507 | Assert.That(createResult.GetRawResponse().IsError, Is.False, "File creation should succeed"); |
| 508 | |
| 509 | // Extract the file ID from the response (this might need adjustment based on the actual response format) |
| 510 | string responseContent = createResult.GetRawResponse().Content.ToString(); |
| 511 | Console.WriteLine($"Create file response: {responseContent}"); |
| 512 | |
| 513 | // Parse the response to get the file ID |
| 514 | var responseJson = JsonDocument.Parse(responseContent); |
| 515 | string fileId = responseJson.RootElement.GetProperty("id").GetString(); |
| 516 | Assert.That(fileId, Is.Not.Null.And.Not.Empty, "File ID should be returned from creation"); |
| 517 | |
| 518 | Console.WriteLine($"Created file with ID: {fileId}"); |
| 519 | |
| 520 | try |
| 521 | { |
| 522 | // Now delete the file |
| 523 | ClientResult<DeleteContainerFileResponse> deleteResult = await client.DeleteContainerFileAsync(_testContainerId, fileId); |
| 524 | |
| 525 | Assert.That(deleteResult, Is.Not.Null); |
| 526 | Assert.That(deleteResult.Value, Is.Not.Null); |
| 527 | Assert.That(deleteResult.Value.Id, Is.EqualTo(fileId), "Deleted file ID should match"); |
| 528 | Assert.That(deleteResult.Value.Object, Is.Not.Null.And.Not.Empty); |
| 529 | Assert.That(deleteResult.Value.Deleted, Is.True, "File should be marked as deleted"); |
| 530 | |
| 531 | Console.WriteLine($"Successfully deleted file: {fileId}"); |
| 532 | } |
| 533 | catch (Exception ex) |
| 534 | { |
| 535 | Console.WriteLine($"Failed to delete file {fileId}: {ex.Message}"); |
| 536 | // Don't fail the test if cleanup fails |
| 537 | } |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | [RecordedTest] |
| 542 | public async Task CanCreateGetAndDeleteContainerFile() |
| 543 | { |
| 544 | using (Recording.DisableRequestBodyRecording()) // Temp pending https://github.com/Azure/azure-sdk-tools/issues/11901 |
| 545 | { |
| 546 | ContainerClient client = GetTestClient(); |
| 547 | |
| 548 | if (string.IsNullOrEmpty(_testContainerId)) |
| 549 | { |
| 550 | Assert.Ignore("No test container available - likely running without API key"); |
| 551 | return; |
| 552 | } |
| 553 | |
| 554 | // Create a test file using multipart form data |
| 555 | string testContent = "Test file content for get/delete operations."; |
| 556 | byte[] contentBytes = System.Text.Encoding.UTF8.GetBytes(testContent); |
| 557 | |
| 558 | var formData = new MultiPartFormDataBinaryContent(); |
| 559 | formData.Add(contentBytes, "file", "test-get-file.txt", "text/plain"); |
| 560 | |
| 561 | ClientResult createResult = await client.CreateContainerFileAsync(_testContainerId, formData, formData.ContentType); |
| 562 | |
| 563 | string responseContent = createResult.GetRawResponse().Content.ToString(); |
| 564 | var responseJson = JsonDocument.Parse(responseContent); |
| 565 | string fileId = responseJson.RootElement.GetProperty("id").GetString(); |
| 566 | |
| 567 | try |
| 568 | { |
| 569 | // Get the file metadata |
| 570 | ClientResult<ContainerFileResource> getResult = await client.GetContainerFileAsync(_testContainerId, fileId); |
| 571 | ContainerFileResource fileResource = getResult.Value; |
| 572 | |
| 573 | Validate(fileResource); |
| 574 | Assert.That(fileResource.Id, Is.EqualTo(fileId)); |
| 575 | Assert.That(fileResource.ContainerId, Is.EqualTo(_testContainerId)); |
| 576 | Assert.That(fileResource.Bytes, Is.GreaterThan(0), "File size should be greater than 0"); |
| 577 | |
| 578 | Console.WriteLine($"Retrieved file metadata: {fileResource.Id}, {fileResource.Bytes} bytes"); |
| 579 | |
| 580 | // Get the file content |
| 581 | ClientResult<BinaryData> contentResult = await client.DownloadContainerFileAsync(_testContainerId, fileId); |
| 582 | BinaryData fileContent = contentResult.Value; |
| 583 | |
| 584 | Assert.That(fileContent, Is.Not.Null); |
| 585 | Assert.That(fileContent.ToArray().Length, Is.GreaterThan(0), "File content should not be empty"); |
| 586 | |
| 587 | Console.WriteLine($"Retrieved file content with {fileContent.ToArray().Length} bytes"); |
| 588 | } |
| 589 | finally |
| 590 | { |
| 591 | // Clean up - delete the file |
| 592 | try |
| 593 | { |
| 594 | await client.DeleteContainerFileAsync(_testContainerId, fileId); |
| 595 | Console.WriteLine($"Cleaned up file: {fileId}"); |
| 596 | } |
| 597 | catch (Exception ex) |
| 598 | { |
| 599 | Console.WriteLine($"Failed to clean up file {fileId}: {ex.Message}"); |
| 600 | } |
| 601 | } |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | [RecordedTest] |
| 606 | public async Task CanGetContainerFileWithCancellation() |
| 607 | { |
| 608 | using (Recording.DisableRequestBodyRecording()) // Temp pending https://github.com/Azure/azure-sdk-tools/issues/11901 |
| 609 | { |
| 610 | ContainerClient client = GetTestClient(); |
| 611 | |
| 612 | if (string.IsNullOrEmpty(_testContainerId)) |
| 613 | { |
| 614 | Assert.Ignore("No test container available - likely running without API key"); |
| 615 | return; |
| 616 | } |
| 617 | |
| 618 | // Create a test file first using multipart form data |
| 619 | string testContent = "Test content for cancellation test."; |
| 620 | byte[] contentBytes = System.Text.Encoding.UTF8.GetBytes(testContent); |
| 621 | |
| 622 | var formData = new MultiPartFormDataBinaryContent(); |
| 623 | formData.Add(contentBytes, "file", "test-cancel-file.txt", "text/plain"); |
| 624 | |
| 625 | ClientResult createResult = await client.CreateContainerFileAsync(_testContainerId, formData, formData.ContentType); |
| 626 | |
| 627 | string responseContent = createResult.GetRawResponse().Content.ToString(); |
| 628 | var responseJson = JsonDocument.Parse(responseContent); |
| 629 | string fileId = responseJson.RootElement.GetProperty("id").GetString(); |
| 630 | |
| 631 | try |
| 632 | { |
| 633 | using var cancellationTokenSource = new CancellationTokenSource(); |
| 634 | cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(30)); |
| 635 | |
| 636 | // Test GetContainerFile with cancellation |
| 637 | ClientResult<ContainerFileResource> result = await client.GetContainerFileAsync(_testContainerId, fileId, cancellationTokenSource.Token); |
| 638 | ContainerFileResource fileResource = result.Value; |
| 639 | |
| 640 | Validate(fileResource); |
| 641 | Assert.That(fileResource.Id, Is.EqualTo(fileId)); |
| 642 | |
| 643 | // Test DownloadContainerFile with cancellation |
| 644 | ClientResult<BinaryData> contentResult = await client.DownloadContainerFileAsync(_testContainerId, fileId, cancellationTokenSource.Token); |
| 645 | BinaryData fileContent = contentResult.Value; |
| 646 | |
| 647 | Assert.That(fileContent, Is.Not.Null); |
| 648 | Console.WriteLine($"Successfully retrieved file with cancellation token"); |
| 649 | } |
| 650 | finally |
| 651 | { |
| 652 | // Clean up |
| 653 | try |
| 654 | { |
| 655 | await client.DeleteContainerFileAsync(_testContainerId, fileId); |
| 656 | } |
| 657 | catch (Exception ex) |
| 658 | { |
| 659 | Console.WriteLine($"Failed to clean up file {fileId}: {ex.Message}"); |
| 660 | } |
| 661 | } |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | [RecordedTest] |
| 666 | public async Task CanDeleteContainerFileWithCancellation() |
| 667 | { |
| 668 | using (Recording.DisableRequestBodyRecording()) // Temp pending https://github.com/Azure/azure-sdk-tools/issues/11901 |
| 669 | { |
| 670 | ContainerClient client = GetTestClient(); |
| 671 | |
| 672 | if (string.IsNullOrEmpty(_testContainerId)) |
| 673 | { |
| 674 | Assert.Ignore("No test container available - likely running without API key"); |
| 675 | return; |
| 676 | } |
| 677 | |
| 678 | // Create a test file first using multipart form data |
| 679 | string testContent = "Test content for deletion with cancellation."; |
| 680 | byte[] contentBytes = System.Text.Encoding.UTF8.GetBytes(testContent); |
| 681 | |
| 682 | var formData = new MultiPartFormDataBinaryContent(); |
| 683 | formData.Add(contentBytes, "file", "test-delete-cancel-file.txt", "text/plain"); |
| 684 | |
| 685 | ClientResult createResult = await client.CreateContainerFileAsync(_testContainerId, formData, formData.ContentType); |
| 686 | |
| 687 | string responseContent = createResult.GetRawResponse().Content.ToString(); |
| 688 | var responseJson = JsonDocument.Parse(responseContent); |
| 689 | string fileId = responseJson.RootElement.GetProperty("id").GetString(); |
| 690 | |
| 691 | using var cancellationTokenSource = new CancellationTokenSource(); |
| 692 | cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(30)); |
| 693 | |
| 694 | // Delete the file with cancellation token |
| 695 | ClientResult<DeleteContainerFileResponse> deleteResult = await client.DeleteContainerFileAsync(_testContainerId, fileId, cancellationTokenSource.Token); |
| 696 | |
| 697 | Assert.That(deleteResult, Is.Not.Null); |
| 698 | Assert.That(deleteResult.Value, Is.Not.Null); |
| 699 | Assert.That(deleteResult.Value.Id, Is.EqualTo(fileId)); |
| 700 | Assert.That(deleteResult.Value.Deleted, Is.True); |
| 701 | |
| 702 | Console.WriteLine($"Successfully deleted file with cancellation token: {fileId}"); |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | [RecordedTest] |
| 707 | public void CreateContainerFileValidatesParameters() |
| 708 | { |
| 709 | ContainerClient client = GetTestClient(); |
| 710 | |
| 711 | if (string.IsNullOrEmpty(_testContainerId)) |
| 712 | { |
| 713 | Assert.Ignore("No test container available - likely running without API key"); |
| 714 | return; |
| 715 | } |
| 716 | |
| 717 | // Test null content |
| 718 | Assert.ThrowsAsync<ArgumentNullException>(async () => |
| 719 | await client.CreateContainerFileAsync(_testContainerId, null, "multipart/form-data")); |
| 720 | |
| 721 | // Test null/empty container ID |
| 722 | var testFormData = new MultiPartFormDataBinaryContent(); |
| 723 | testFormData.Add("test", "file", "test.txt", "text/plain"); |
| 724 | |
| 725 | Assert.ThrowsAsync<ArgumentNullException>(async () => |
| 726 | await client.CreateContainerFileAsync(null, testFormData, testFormData.ContentType)); |
| 727 | Assert.ThrowsAsync<ArgumentException>(async () => |
| 728 | await client.CreateContainerFileAsync("", testFormData, testFormData.ContentType)); |
| 729 | |
| 730 | Console.WriteLine("Parameter validation tests passed"); |
| 731 | } |
| 732 | |
| 733 | [RecordedTest] |
| 734 | public void GetContainerFileValidatesParameters() |
| 735 | { |
| 736 | ContainerClient client = GetTestClient(); |
| 737 | |
| 738 | // Test null/empty container ID and file ID |
| 739 | Assert.ThrowsAsync<ArgumentNullException>(async () => |
| 740 | await client.GetContainerFileAsync(null, "file123")); |
| 741 | Assert.ThrowsAsync<ArgumentException>(async () => |
| 742 | await client.GetContainerFileAsync("", "file123")); |
| 743 | Assert.ThrowsAsync<ArgumentNullException>(async () => |
| 744 | await client.GetContainerFileAsync("container123", null)); |
| 745 | Assert.ThrowsAsync<ArgumentException>(async () => |
| 746 | await client.GetContainerFileAsync("container123", "")); |
| 747 | |
| 748 | Assert.ThrowsAsync<ArgumentNullException>(async () => |
| 749 | await client.DownloadContainerFileAsync(null, "file123")); |
| 750 | Assert.ThrowsAsync<ArgumentException>(async () => |
| 751 | await client.DownloadContainerFileAsync("", "file123")); |
| 752 | Assert.ThrowsAsync<ArgumentNullException>(async () => |
| 753 | await client.DownloadContainerFileAsync("container123", null)); |
| 754 | Assert.ThrowsAsync<ArgumentException>(async () => |
| 755 | await client.DownloadContainerFileAsync("container123", "")); |
| 756 | |
| 757 | Console.WriteLine("Parameter validation tests passed for GetContainerFile methods"); |
| 758 | } |
| 759 | |
| 760 | [RecordedTest] |
| 761 | public void DeleteContainerFileValidatesParameters() |
| 762 | { |
| 763 | ContainerClient client = GetTestClient(); |
| 764 | |
| 765 | // Test null/empty container ID and file ID |
| 766 | Assert.ThrowsAsync<ArgumentNullException>(async () => |
| 767 | await client.DeleteContainerFileAsync(null, "file123")); |
| 768 | Assert.ThrowsAsync<ArgumentException>(async () => |
| 769 | await client.DeleteContainerFileAsync("", "file123")); |
| 770 | Assert.ThrowsAsync<ArgumentNullException>(async () => |
| 771 | await client.DeleteContainerFileAsync("container123", null)); |
| 772 | Assert.ThrowsAsync<ArgumentException>(async () => |
| 773 | await client.DeleteContainerFileAsync("container123", "")); |
| 774 | |
| 775 | Console.WriteLine("Parameter validation tests passed for DeleteContainerFile methods"); |
| 776 | } |
| 777 | |
| 778 | [RecordedTest] |
| 779 | public void GetContainerValidatesParameters() |
| 780 | { |
| 781 | ContainerClient client = GetTestClient(); |
| 782 | |
| 783 | // Test null/empty container ID |
| 784 | Assert.ThrowsAsync<ArgumentNullException>(async () => |
| 785 | await client.GetContainerAsync(null)); |
| 786 | Assert.ThrowsAsync<ArgumentException>(async () => |
| 787 | await client.GetContainerAsync("")); |
| 788 | |
| 789 | Console.WriteLine("Parameter validation tests passed for GetContainer methods"); |
| 790 | } |
| 791 | |
| 792 | private static void Validate(ContainerResource container) |
| 793 | { |
| 794 | Assert.That(container, Is.Not.Null); |
| 795 | Assert.That(container.Id, Is.Not.Null.And.Not.Empty); |
| 796 | Assert.That(container.Object, Is.Not.Null.And.Not.Empty); |
| 797 | Assert.That(container.CreatedAt, Is.GreaterThan(DateTimeOffset.MinValue)); |
| 798 | Assert.That(container.Status, Is.Not.Null.And.Not.Empty); |
| 799 | // Name can be null/empty for some containers |
| 800 | } |
| 801 | |
| 802 | private static void Validate(ContainerFileResource file) |
| 803 | { |
| 804 | Assert.That(file, Is.Not.Null); |
| 805 | Assert.That(file.Id, Is.Not.Null.And.Not.Empty); |
| 806 | Assert.That(file.Object, Is.Not.Null.And.Not.Empty); |
| 807 | Assert.That(file.ContainerId, Is.Not.Null.And.Not.Empty); |
| 808 | Assert.That(file.CreatedAt, Is.GreaterThan(DateTimeOffset.MinValue)); |
| 809 | Assert.That(file.Bytes, Is.GreaterThanOrEqualTo(0)); |
| 810 | Assert.That(file.Path, Is.Not.Null); |
| 811 | Assert.That(file.Source, Is.Not.Null); |
| 812 | } |
| 813 | } |