4 Commits
14 changed files with 819 additions and 1 deletions
+89
View File
@@ -0,0 +1,89 @@
using AnthropicClient;
using AnthropicClient.Models;
namespace AnthropicClient.Examples;
/// <summary>
/// Example demonstrating file operations with the Anthropic API.
/// </summary>
public class FileOperationsExample
{
public static async Task RunExample()
{
// This is a demonstration of the file API methods
// Note: You would need a real API key to run this example
var client = new AnthropicApiClient("your-api-key", new HttpClient());
// Create a file
var fileContent = "Hello, this is a sample file content!"u8.ToArray();
var fileRequest = new FileRequest(fileContent, "sample.txt", "text/plain");
Console.WriteLine("Creating file...");
var createResult = await client.CreateFileAsync(fileRequest);
if (createResult.IsFailure)
{
Console.WriteLine($"Failed to create file: {createResult.Error.Error.Message}");
return;
}
var fileId = createResult.Value.Id;
Console.WriteLine($"File created with ID: {fileId}");
// List files
Console.WriteLine("\nListing files...");
var listResult = await client.ListFilesAsync();
if (listResult.IsSuccess)
{
Console.WriteLine($"Found {listResult.Value.Data.Length} files");
foreach (var file in listResult.Value.Data)
{
Console.WriteLine($"- {file.Filename} ({file.Id})");
}
}
// Get file metadata
Console.WriteLine($"\nGetting file metadata for {fileId}...");
var getResult = await client.GetFileAsync(fileId);
if (getResult.IsSuccess)
{
var file = getResult.Value;
Console.WriteLine($"File: {file.Filename}");
Console.WriteLine($"Size: {file.SizeBytes} bytes");
Console.WriteLine($"Content Type: {file.ContentType}");
Console.WriteLine($"Created: {file.CreatedAt}");
}
// Download file
Console.WriteLine($"\nDownloading file {fileId}...");
var downloadResult = await client.DownloadFileAsync(fileId);
if (downloadResult.IsSuccess)
{
var download = downloadResult.Value;
var contentText = System.Text.Encoding.UTF8.GetString(download.Content);
Console.WriteLine($"Downloaded content: {contentText}");
}
// List all files with pagination
Console.WriteLine("\nListing all files (with pagination)...");
await foreach (var pageResult in client.ListAllFilesAsync(limit: 10))
{
if (pageResult.IsSuccess)
{
Console.WriteLine($"Page with {pageResult.Value.Data.Length} files");
}
}
// Delete file
Console.WriteLine($"\nDeleting file {fileId}...");
var deleteResult = await client.DeleteFileAsync(fileId);
if (deleteResult.IsSuccess)
{
Console.WriteLine($"File deleted: {deleteResult.Value.Deleted}");
}
}
}
+85
View File
@@ -18,6 +18,7 @@ public class AnthropicApiClient : IAnthropicApiClient
private string CountTokensEndpoint => $"{MessagesEndpoint}/count_tokens"; private string CountTokensEndpoint => $"{MessagesEndpoint}/count_tokens";
private string MessageBatchesEndpoint => $"{MessagesEndpoint}/batches"; private string MessageBatchesEndpoint => $"{MessagesEndpoint}/batches";
private const string ModelsEndpoint = "models"; private const string ModelsEndpoint = "models";
private const string FilesEndpoint = "files";
private const string JsonContentType = "application/json"; private const string JsonContentType = "application/json";
private const string EventPrefix = "event:"; private const string EventPrefix = "event:";
private const string DataPrefix = "data:"; private const string DataPrefix = "data:";
@@ -380,6 +381,79 @@ public class AnthropicApiClient : IAnthropicApiClient
return await CreateResultAsync<AnthropicModel>(response); return await CreateResultAsync<AnthropicModel>(response);
} }
/// <inheritdoc/>
public async Task<AnthropicResult<AnthropicFile>> CreateFileAsync(FileRequest request, CancellationToken cancellationToken = default)
{
var formData = new MultipartFormDataContent();
formData.Add(new ByteArrayContent(request.Content), "file", request.Filename);
formData.Add(new StringContent(request.Purpose), "purpose");
var httpRequest = new HttpRequestMessage(HttpMethod.Post, FilesEndpoint)
{
Content = formData
};
var response = await _httpClient.SendAsync(httpRequest, cancellationToken);
return await CreateResultAsync<AnthropicFile>(response);
}
/// <inheritdoc/>
public async Task<AnthropicResult<Page<AnthropicFile>>> ListFilesAsync(PagingRequest? request = null, CancellationToken cancellationToken = default)
{
var pagingRequest = request ?? new PagingRequest();
var endpoint = $"{FilesEndpoint}?{pagingRequest.ToQueryParameters()}";
var response = await SendRequestAsync(endpoint, cancellationToken: cancellationToken);
return await CreateResultAsync<Page<AnthropicFile>>(response);
}
/// <inheritdoc/>
public async IAsyncEnumerable<AnthropicResult<Page<AnthropicFile>>> ListAllFilesAsync(int limit = 20, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await foreach (var result in GetAllPagesAsync<AnthropicFile>(FilesEndpoint, limit, cancellationToken))
{
yield return result;
}
}
/// <inheritdoc/>
public async Task<AnthropicResult<AnthropicFile>> GetFileAsync(string fileId, CancellationToken cancellationToken = default)
{
var endpoint = $"{FilesEndpoint}/{fileId}";
var response = await SendRequestAsync(endpoint, cancellationToken: cancellationToken);
return await CreateResultAsync<AnthropicFile>(response);
}
/// <inheritdoc/>
public async Task<AnthropicResult<FileDownloadResponse>> DownloadFileAsync(string fileId, CancellationToken cancellationToken = default)
{
var endpoint = $"{FilesEndpoint}/{fileId}/content";
var response = await SendRequestAsync(endpoint, cancellationToken: cancellationToken);
var anthropicHeaders = new AnthropicHeaders(response.Headers);
if (response.IsSuccessStatusCode is false)
{
var errorContent = await response.Content.ReadAsStringAsync();
var error = Deserialize<AnthropicError>(errorContent) ?? new AnthropicError();
return AnthropicResult<FileDownloadResponse>.Failure(error, anthropicHeaders);
}
var content = await response.Content.ReadAsByteArrayAsync();
var contentType = response.Content.Headers.ContentType?.MediaType ?? "application/octet-stream";
var filename = ExtractFilenameFromContentDisposition(response.Content.Headers.ContentDisposition?.FileName) ?? fileId;
var sizeBytes = content.Length;
var downloadResponse = new FileDownloadResponse(content, filename, contentType, sizeBytes);
return AnthropicResult<FileDownloadResponse>.Success(downloadResponse, anthropicHeaders);
}
/// <inheritdoc/>
public async Task<AnthropicResult<FileDeleteResponse>> DeleteFileAsync(string fileId, CancellationToken cancellationToken = default)
{
var endpoint = $"{FilesEndpoint}/{fileId}";
var response = await SendRequestAsync(endpoint, HttpMethod.Delete, cancellationToken);
return await CreateResultAsync<FileDeleteResponse>(response);
}
private async IAsyncEnumerable<AnthropicResult<Page<T>>> GetAllPagesAsync<T>(string endpoint, int limit = 20, [EnumeratorCancellation] CancellationToken cancellationToken = default) private async IAsyncEnumerable<AnthropicResult<Page<T>>> GetAllPagesAsync<T>(string endpoint, int limit = 20, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{ {
var pagingRequest = new PagingRequest(limit: limit); var pagingRequest = new PagingRequest(limit: limit);
@@ -449,6 +523,17 @@ public class AnthropicApiClient : IAnthropicApiClient
return AnthropicResult<T>.Success(model, anthropicHeaders); return AnthropicResult<T>.Success(model, anthropicHeaders);
} }
private static string? ExtractFilenameFromContentDisposition(string? contentDisposition)
{
if (string.IsNullOrEmpty(contentDisposition))
{
return null;
}
// Remove quotes if present
return contentDisposition!.Trim('"');
}
private async Task<HttpResponseMessage> SendRequestAsync(string endpoint, HttpMethod? method = null, CancellationToken cancellationToken = default) private async Task<HttpResponseMessage> SendRequestAsync(string endpoint, HttpMethod? method = null, CancellationToken cancellationToken = default)
{ {
var request = new HttpRequestMessage(method ?? HttpMethod.Get, endpoint); var request = new HttpRequestMessage(method ?? HttpMethod.Get, endpoint);
@@ -111,4 +111,52 @@ public interface IAnthropicApiClient
/// <param name="cancellationToken">A token to cancel the asynchronous operation.</param> /// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains the response as an <see cref="AnthropicResult{T}"/> where T is <see cref="AnthropicModel"/>.</returns> /// <returns>A task that represents the asynchronous operation. The task result contains the response as an <see cref="AnthropicResult{T}"/> where T is <see cref="AnthropicModel"/>.</returns>
Task<AnthropicResult<AnthropicModel>> GetModelAsync(string modelId, CancellationToken cancellationToken = default); Task<AnthropicResult<AnthropicModel>> GetModelAsync(string modelId, CancellationToken cancellationToken = default);
/// <summary>
/// Creates a file asynchronously.
/// </summary>
/// <param name="request">The file request to create.</param>
/// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains the response as an <see cref="AnthropicResult{T}"/> where T is <see cref="AnthropicFile"/>.</returns>
Task<AnthropicResult<AnthropicFile>> CreateFileAsync(FileRequest request, CancellationToken cancellationToken = default);
/// <summary>
/// Lists files asynchronously, returning a single page of results.
/// </summary>
/// <param name="request">The paging request to use for listing the files.</param>
/// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains the response as an <see cref="AnthropicResult{T}"/> where T is <see cref="Page{T}"/> where T is <see cref="AnthropicFile"/>.</returns>
Task<AnthropicResult<Page<AnthropicFile>>> ListFilesAsync(PagingRequest? request = null, CancellationToken cancellationToken = default);
/// <summary>
/// Lists all files asynchronously, returning every page of results.
/// </summary>
/// <param name="limit">The maximum number of files to return in each page.</param>
/// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
/// <returns>An asynchronous enumerable that yields the response as an <see cref="AnthropicResult{T}"/> where T is <see cref="Page{T}"/> where T is <see cref="AnthropicFile"/>.</returns>
IAsyncEnumerable<AnthropicResult<Page<AnthropicFile>>> ListAllFilesAsync(int limit = 20, CancellationToken cancellationToken = default);
/// <summary>
/// Gets a file by its ID asynchronously.
/// </summary>
/// <param name="fileId">The ID of the file to get.</param>
/// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains the response as an <see cref="AnthropicResult{T}"/> where T is <see cref="AnthropicFile"/>.</returns>
Task<AnthropicResult<AnthropicFile>> GetFileAsync(string fileId, CancellationToken cancellationToken = default);
/// <summary>
/// Downloads a file by its ID asynchronously.
/// </summary>
/// <param name="fileId">The ID of the file to download.</param>
/// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains the response as an <see cref="AnthropicResult{T}"/> where T is <see cref="FileDownloadResponse"/>.</returns>
Task<AnthropicResult<FileDownloadResponse>> DownloadFileAsync(string fileId, CancellationToken cancellationToken = default);
/// <summary>
/// Deletes a file by its ID asynchronously.
/// </summary>
/// <param name="fileId">The ID of the file to delete.</param>
/// <param name="cancellationToken">A token to cancel the asynchronous operation.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains the response as an <see cref="AnthropicResult{T}"/> where T is <see cref="FileDeleteResponse"/>.</returns>
Task<AnthropicResult<FileDeleteResponse>> DeleteFileAsync(string fileId, CancellationToken cancellationToken = default);
} }
@@ -0,0 +1,42 @@
using System.Text.Json.Serialization;
namespace AnthropicClient.Models;
/// <summary>
/// Represents a file in the Anthropic API.
/// </summary>
public class AnthropicFile
{
/// <summary>
/// The type of the object.
/// </summary>
public string Type { get; init; } = "file";
/// <summary>
/// The unique identifier for the file.
/// </summary>
public string Id { get; init; } = string.Empty;
/// <summary>
/// The filename of the file.
/// </summary>
public string Filename { get; init; } = string.Empty;
/// <summary>
/// The MIME type of the file.
/// </summary>
[JsonPropertyName("content_type")]
public string ContentType { get; init; } = string.Empty;
/// <summary>
/// The size of the file in bytes.
/// </summary>
[JsonPropertyName("size_bytes")]
public int SizeBytes { get; init; }
/// <summary>
/// The date and time when the file was created.
/// </summary>
[JsonPropertyName("created_at")]
public DateTimeOffset CreatedAt { get; init; }
}
@@ -0,0 +1,24 @@
using System.Text.Json.Serialization;
namespace AnthropicClient.Models;
/// <summary>
/// Represents the response from a file deletion operation.
/// </summary>
public class FileDeleteResponse
{
/// <summary>
/// The type of the object.
/// </summary>
public string Type { get; init; } = "file_deleted";
/// <summary>
/// The unique identifier for the deleted file.
/// </summary>
public string Id { get; init; } = string.Empty;
/// <summary>
/// Indicates whether the file was successfully deleted.
/// </summary>
public bool Deleted { get; init; }
}
@@ -0,0 +1,42 @@
namespace AnthropicClient.Models;
/// <summary>
/// Represents the response from downloading a file.
/// </summary>
public class FileDownloadResponse
{
/// <summary>
/// The file content as a byte array.
/// </summary>
public byte[] Content { get; }
/// <summary>
/// The filename of the file.
/// </summary>
public string Filename { get; }
/// <summary>
/// The MIME type of the file.
/// </summary>
public string ContentType { get; }
/// <summary>
/// The size of the file in bytes.
/// </summary>
public int SizeBytes { get; }
/// <summary>
/// Initializes a new instance of the <see cref="FileDownloadResponse"/> class.
/// </summary>
/// <param name="content">The file content as a byte array.</param>
/// <param name="filename">The filename of the file.</param>
/// <param name="contentType">The MIME type of the file.</param>
/// <param name="sizeBytes">The size of the file in bytes.</param>
public FileDownloadResponse(byte[] content, string filename, string contentType, int sizeBytes)
{
Content = content;
Filename = filename;
ContentType = contentType;
SizeBytes = sizeBytes;
}
}
+51
View File
@@ -0,0 +1,51 @@
using AnthropicClient.Utils;
namespace AnthropicClient.Models;
/// <summary>
/// Represents a request to create a file.
/// </summary>
public class FileRequest
{
/// <summary>
/// The file content as a byte array.
/// </summary>
public byte[] Content { get; }
/// <summary>
/// The filename of the file.
/// </summary>
public string Filename { get; }
/// <summary>
/// The MIME type of the file.
/// </summary>
public string ContentType { get; }
/// <summary>
/// The purpose of the file.
/// </summary>
public string Purpose { get; }
/// <summary>
/// Initializes a new instance of the <see cref="FileRequest"/> class.
/// </summary>
/// <param name="content">The file content as a byte array.</param>
/// <param name="filename">The filename of the file.</param>
/// <param name="contentType">The MIME type of the file.</param>
/// <param name="purpose">The purpose of the file (default: "user_upload").</param>
/// <exception cref="ArgumentNullException">Thrown when content, filename, or contentType is null.</exception>
/// <exception cref="ArgumentException">Thrown when filename or contentType is empty.</exception>
public FileRequest(byte[] content, string filename, string contentType, string purpose = "user_upload")
{
ArgumentValidator.ThrowIfNull(content, nameof(content));
ArgumentValidator.ThrowIfNullOrWhitespace(filename, nameof(filename));
ArgumentValidator.ThrowIfNullOrWhitespace(contentType, nameof(contentType));
ArgumentValidator.ThrowIfNullOrWhitespace(purpose, nameof(purpose));
Content = content;
Filename = filename;
ContentType = contentType;
Purpose = purpose;
}
}
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net9.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
@@ -0,0 +1,164 @@
namespace AnthropicClient.Tests.Integration;
public class AnthropicApiClientFileTests : IntegrationTest
{
[Fact]
public async Task CreateFileAsync_WhenCalled_ItShouldReturnFileResponse()
{
var fileResponseJson = @"{
""type"": ""file"",
""id"": ""file_abc123"",
""filename"": ""example.txt"",
""content_type"": ""text/plain"",
""size_bytes"": 1024,
""created_at"": ""2024-03-15T10:30:00Z""
}";
_mockHttpMessageHandler
.WhenCreateFileRequest()
.Respond(HttpStatusCode.OK, "application/json", fileResponseJson);
var content = "Hello World"u8.ToArray();
var request = new FileRequest(content, "example.txt", "text/plain");
var result = await Client.CreateFileAsync(request);
result.IsSuccess.Should().BeTrue();
result.Value.Should().NotBeNull();
result.Value!.Id.Should().Be("file_abc123");
result.Value.Filename.Should().Be("example.txt");
result.Value.ContentType.Should().Be("text/plain");
result.Value.SizeBytes.Should().Be(1024);
}
[Fact]
public async Task ListFilesAsync_WhenCalled_ItShouldReturnFilesPage()
{
var filesResponseJson = @"{
""data"": [
{
""type"": ""file"",
""id"": ""file_abc123"",
""filename"": ""example.txt"",
""content_type"": ""text/plain"",
""size_bytes"": 1024,
""created_at"": ""2024-03-15T10:30:00Z""
}
],
""has_more"": false,
""first_id"": ""file_abc123"",
""last_id"": ""file_abc123""
}";
_mockHttpMessageHandler
.WhenListFilesRequest()
.Respond(HttpStatusCode.OK, "application/json", filesResponseJson);
var result = await Client.ListFilesAsync();
result.IsSuccess.Should().BeTrue();
result.Value.Should().NotBeNull();
result.Value!.Data.Should().HaveCount(1);
result.Value.Data[0].Id.Should().Be("file_abc123");
result.Value.HasMore.Should().BeFalse();
}
[Fact]
public async Task GetFileAsync_WhenCalled_ItShouldReturnFileResponse()
{
var fileResponseJson = @"{
""type"": ""file"",
""id"": ""file_abc123"",
""filename"": ""example.txt"",
""content_type"": ""text/plain"",
""size_bytes"": 1024,
""created_at"": ""2024-03-15T10:30:00Z""
}";
_mockHttpMessageHandler
.WhenGetFileRequest("file_abc123")
.Respond(HttpStatusCode.OK, "application/json", fileResponseJson);
var result = await Client.GetFileAsync("file_abc123");
result.IsSuccess.Should().BeTrue();
result.Value.Should().NotBeNull();
result.Value!.Id.Should().Be("file_abc123");
result.Value.Filename.Should().Be("example.txt");
}
[Fact]
public async Task DownloadFileAsync_WhenCalled_ItShouldReturnFileContent()
{
var fileContent = "Hello World"u8.ToArray();
var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(fileContent)
};
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "\"example.txt\""
};
_mockHttpMessageHandler
.WhenDownloadFileRequest("file_abc123")
.Respond(_ => httpResponseMessage);
var result = await Client.DownloadFileAsync("file_abc123");
result.IsSuccess.Should().BeTrue();
result.Value.Should().NotBeNull();
result.Value!.Content.Should().BeEquivalentTo(fileContent);
result.Value.Filename.Should().Be("example.txt");
result.Value.ContentType.Should().Be("text/plain");
result.Value.SizeBytes.Should().Be(fileContent.Length);
}
[Fact]
public async Task DeleteFileAsync_WhenCalled_ItShouldReturnDeleteResponse()
{
var deleteResponseJson = @"{
""type"": ""file_deleted"",
""id"": ""file_abc123"",
""deleted"": true
}";
_mockHttpMessageHandler
.WhenDeleteFileRequest("file_abc123")
.Respond(HttpStatusCode.OK, "application/json", deleteResponseJson);
var result = await Client.DeleteFileAsync("file_abc123");
result.IsSuccess.Should().BeTrue();
result.Value.Should().NotBeNull();
result.Value!.Id.Should().Be("file_abc123");
result.Value.Deleted.Should().BeTrue();
}
[Fact]
public async Task CreateFileAsync_WhenCalledAndErrorReturned_ItShouldHandleError()
{
var errorJson = @"{
""type"": ""error"",
""error"": {
""type"": ""invalid_request_error"",
""message"": ""File too large""
}
}";
_mockHttpMessageHandler
.WhenCreateFileRequest()
.Respond(HttpStatusCode.BadRequest, "application/json", errorJson);
var content = "Hello World"u8.ToArray();
var request = new FileRequest(content, "example.txt", "text/plain");
var result = await Client.CreateFileAsync(request);
result.IsSuccess.Should().BeFalse();
result.Error.Should().BeOfType<AnthropicError>();
result.Error.Error.Should().BeOfType<InvalidRequestError>();
}
}
@@ -20,6 +20,7 @@ public static class MockHttpMessageHandlerExtensions
private static readonly string CountTokensEndpoint = $"{BaseUrl}/messages/count_tokens"; private static readonly string CountTokensEndpoint = $"{BaseUrl}/messages/count_tokens";
private static readonly string MessageBatchesEndpoint = $"{BaseUrl}/messages/batches"; private static readonly string MessageBatchesEndpoint = $"{BaseUrl}/messages/batches";
private static readonly string ModelsEndpoint = $"{BaseUrl}/models"; private static readonly string ModelsEndpoint = $"{BaseUrl}/models";
private static readonly string FilesEndpoint = $"{BaseUrl}/files";
private static MockedRequest SetupBaseRequest( private static MockedRequest SetupBaseRequest(
this MockHttpMessageHandler mockHttpMessageHandler, this MockHttpMessageHandler mockHttpMessageHandler,
@@ -103,4 +104,34 @@ public static class MockHttpMessageHandlerExtensions
return mockHttpMessageHandler return mockHttpMessageHandler
.SetupBaseRequest(HttpMethod.Delete, $"{MessageBatchesEndpoint}/{batchId}"); .SetupBaseRequest(HttpMethod.Delete, $"{MessageBatchesEndpoint}/{batchId}");
} }
public static MockedRequest WhenCreateFileRequest(this MockHttpMessageHandler mockHttpMessageHandler)
{
return mockHttpMessageHandler
.SetupBaseRequest(HttpMethod.Post, FilesEndpoint);
}
public static MockedRequest WhenListFilesRequest(this MockHttpMessageHandler mockHttpMessageHandler)
{
return mockHttpMessageHandler
.SetupBaseRequest(HttpMethod.Get, FilesEndpoint);
}
public static MockedRequest WhenGetFileRequest(this MockHttpMessageHandler mockHttpMessageHandler, string fileId)
{
return mockHttpMessageHandler
.SetupBaseRequest(HttpMethod.Get, $"{FilesEndpoint}/{fileId}");
}
public static MockedRequest WhenDownloadFileRequest(this MockHttpMessageHandler mockHttpMessageHandler, string fileId)
{
return mockHttpMessageHandler
.SetupBaseRequest(HttpMethod.Get, $"{FilesEndpoint}/{fileId}/content");
}
public static MockedRequest WhenDeleteFileRequest(this MockHttpMessageHandler mockHttpMessageHandler, string fileId)
{
return mockHttpMessageHandler
.SetupBaseRequest(HttpMethod.Delete, $"{FilesEndpoint}/{fileId}");
}
} }
@@ -0,0 +1,67 @@
namespace AnthropicClient.Tests.Unit.Models;
public class AnthropicFileTests : SerializationTest
{
private const string SampleJson = @"{
""type"": ""file"",
""id"": ""file_abc123"",
""filename"": ""example.txt"",
""content_type"": ""text/plain"",
""size_bytes"": 1024,
""created_at"": ""2024-03-15T10:30:00Z""
}";
[Fact]
public void Constructor_WhenCalled_ItShouldReturnAnInstanceWithPropertiesSet()
{
var file = new AnthropicFile();
file.Type.Should().Be("file");
file.Id.Should().BeEmpty();
file.Filename.Should().BeEmpty();
file.ContentType.Should().BeEmpty();
file.SizeBytes.Should().Be(0);
file.CreatedAt.Should().Be(default);
}
[Fact]
public void JsonDeserialization_WhenDeserialized_ItShouldHaveExpectedValues()
{
var result = Deserialize<AnthropicFile>(SampleJson);
result.Should().NotBeNull();
result!.Type.Should().Be("file");
result.Id.Should().Be("file_abc123");
result.Filename.Should().Be("example.txt");
result.ContentType.Should().Be("text/plain");
result.SizeBytes.Should().Be(1024);
result.CreatedAt.Should().Be(new DateTimeOffset(2024, 3, 15, 10, 30, 0, TimeSpan.Zero));
}
[Fact]
public void JsonSerialization_WhenSerialized_ItShouldReturnExpectedShape()
{
var file = new AnthropicFile
{
Type = "file",
Id = "file_abc123",
Filename = "example.txt",
ContentType = "text/plain",
SizeBytes = 1024,
CreatedAt = new DateTimeOffset(2024, 3, 15, 10, 30, 0, TimeSpan.Zero)
};
var result = Serialize(file);
var expectedJson = @"{
""type"": ""file"",
""id"": ""file_abc123"",
""filename"": ""example.txt"",
""content_type"": ""text/plain"",
""size_bytes"": 1024,
""created_at"": ""2024-03-15T10:30:00+00:00""
}";
JsonAssert.Equal(expectedJson, result);
}
}
@@ -0,0 +1,52 @@
namespace AnthropicClient.Tests.Unit.Models;
public class FileDeleteResponseTests : SerializationTest
{
private const string SampleJson = @"{
""type"": ""file_deleted"",
""id"": ""file_abc123"",
""deleted"": true
}";
[Fact]
public void Constructor_WhenCalled_ItShouldReturnAnInstanceWithPropertiesSet()
{
var response = new FileDeleteResponse();
response.Type.Should().Be("file_deleted");
response.Id.Should().BeEmpty();
response.Deleted.Should().BeFalse();
}
[Fact]
public void JsonDeserialization_WhenDeserialized_ItShouldHaveExpectedValues()
{
var result = Deserialize<FileDeleteResponse>(SampleJson);
result.Should().NotBeNull();
result!.Type.Should().Be("file_deleted");
result.Id.Should().Be("file_abc123");
result.Deleted.Should().BeTrue();
}
[Fact]
public void JsonSerialization_WhenSerialized_ItShouldReturnExpectedShape()
{
var response = new FileDeleteResponse
{
Type = "file_deleted",
Id = "file_abc123",
Deleted = true
};
var result = Serialize(response);
var expectedJson = @"{
""type"": ""file_deleted"",
""id"": ""file_abc123"",
""deleted"": true
}";
JsonAssert.Equal(expectedJson, result);
}
}
@@ -0,0 +1,20 @@
namespace AnthropicClient.Tests.Unit.Models;
public class FileDownloadResponseTests
{
[Fact]
public void Constructor_WhenCalled_ItShouldReturnAnInstanceWithPropertiesSet()
{
var content = "Hello World"u8.ToArray();
var filename = "example.txt";
var contentType = "text/plain";
var sizeBytes = 1024;
var response = new FileDownloadResponse(content, filename, contentType, sizeBytes);
response.Content.Should().BeEquivalentTo(content);
response.Filename.Should().Be(filename);
response.ContentType.Should().Be(contentType);
response.SizeBytes.Should().Be(sizeBytes);
}
}
@@ -0,0 +1,103 @@
namespace AnthropicClient.Tests.Unit.Models;
public class FileRequestTests
{
[Fact]
public void Constructor_WhenCalled_ItShouldReturnAnInstanceWithPropertiesSet()
{
var content = "Hello World"u8.ToArray();
var filename = "example.txt";
var contentType = "text/plain";
var purpose = "user_upload";
var request = new FileRequest(content, filename, contentType, purpose);
request.Content.Should().BeEquivalentTo(content);
request.Filename.Should().Be(filename);
request.ContentType.Should().Be(contentType);
request.Purpose.Should().Be(purpose);
}
[Fact]
public void Constructor_WhenCalledWithDefaultPurpose_ItShouldSetPurposeToUserUpload()
{
var content = "Hello World"u8.ToArray();
var filename = "example.txt";
var contentType = "text/plain";
var request = new FileRequest(content, filename, contentType);
request.Content.Should().BeEquivalentTo(content);
request.Filename.Should().Be(filename);
request.ContentType.Should().Be(contentType);
request.Purpose.Should().Be("user_upload");
}
[Fact]
public void Constructor_WhenContentIsNull_ItShouldThrowArgumentNullException()
{
var act = () => new FileRequest(null!, "example.txt", "text/plain");
act.Should().Throw<ArgumentNullException>().WithParameterName("content");
}
[Fact]
public void Constructor_WhenFilenameIsNull_ItShouldThrowArgumentException()
{
var content = "Hello World"u8.ToArray();
var act = () => new FileRequest(content, null!, "text/plain");
act.Should().Throw<ArgumentException>().WithParameterName("filename");
}
[Fact]
public void Constructor_WhenFilenameIsEmpty_ItShouldThrowArgumentException()
{
var content = "Hello World"u8.ToArray();
var act = () => new FileRequest(content, "", "text/plain");
act.Should().Throw<ArgumentException>().WithParameterName("filename");
}
[Fact]
public void Constructor_WhenContentTypeIsNull_ItShouldThrowArgumentException()
{
var content = "Hello World"u8.ToArray();
var act = () => new FileRequest(content, "example.txt", null!);
act.Should().Throw<ArgumentException>().WithParameterName("contentType");
}
[Fact]
public void Constructor_WhenContentTypeIsEmpty_ItShouldThrowArgumentException()
{
var content = "Hello World"u8.ToArray();
var act = () => new FileRequest(content, "example.txt", "");
act.Should().Throw<ArgumentException>().WithParameterName("contentType");
}
[Fact]
public void Constructor_WhenPurposeIsNull_ItShouldThrowArgumentException()
{
var content = "Hello World"u8.ToArray();
var act = () => new FileRequest(content, "example.txt", "text/plain", null!);
act.Should().Throw<ArgumentException>().WithParameterName("purpose");
}
[Fact]
public void Constructor_WhenPurposeIsEmpty_ItShouldThrowArgumentException()
{
var content = "Hello World"u8.ToArray();
var act = () => new FileRequest(content, "example.txt", "text/plain", "");
act.Should().Throw<ArgumentException>().WithParameterName("purpose");
}
}