簡體   English   中英

如何集成測試 Azure Blob Storage?

[英]How to integration test Azure Blob Storage?

我正在開展一個企業業務項目,我需要將應用程序從本地遷移到 Azure 雲。

某些應用程序需要 Azure Blob 存儲。 所有 Azure 雲基礎設施都可以使用管理身份訪問,並且業務要求是測試和驗證 Azure Blob 方法,而無需訪問 Z3A580F142203677F1F0BC30898F63F5 生產或生產門戶。 也就是說,業務要求我們通過在本地和 GitHub 工作流上測試代碼,甚至在將代碼推送到雲之前使所有存儲工作正常。

當然,我可以啟動我的個人 Azure 帳戶並使用它,但仍然會使用我的帳戶作為游樂場進行測試,但不是真正可用的測試。

通用測試 Azure Blob 存儲的整個想法,無需對 Blob 存儲具有任何訪問權限。

這可能嗎?我怎樣才能做到這一點?

以下是我對 Azure Blob 的工作 POC 方法:

private readonly BlobContainerClient _blobContainerClient;

public AzureBlobStorage(string connectionString, string container)
{
    _blobContainerClient = new BlobContainerClient(connectionString, container);
    _blobContainerClient.CreateIfNotExists();
}

public async Task<string> ReadTextFile(string filename)
{
    var blob = _blobContainerClient.GetBlobClient(filename);
    if (!await _blobContainerClient.ExistsAsync()) return string.Empty;
    var reading = await blob.DownloadStreamingAsync();
    StreamReader reader = new StreamReader(reading.Value.Content);
    return await reader.ReadToEndAsync();
}

public async Task CreateTextFile(string filename, byte[] data)
{
    var blob = _blobContainerClient.GetBlobClient(filename);
    await using var ms = new MemoryStream(data, false);
    await blob.UploadAsync(ms, CancellationToken.None);
}

public async Task DeleteTextFile(string filename)
{
    var blobClient = _blobContainerClient.GetBlobClient(filename);
    await blobClient.DeleteAsync();
}

經過一番研究,我找到了解決方案並寫了一篇關於它的文章。 這是解決方案的簡短版本。

要針對測試環境進行集成測試,我建議您遵循以下答案:

這是可能的,但需要幾個步驟:

  1. 安裝和部署 Azurite(Azurite 是 Azure Blob Storage 的本地版本,我使用的是 docker 版本)。
// here we pull azurite image
docker pull mcr.microsoft.com/azure-storage/azurite
// here we run azurite image and store data under c:\azurite folder
docker run -p 10000:10000 -p 10001:10001 -p 10002:10002 -v c:/azurite:/data mcr.microsoft.com/azure-storage/azurite
  1. 下載並安裝Azure 存儲資源管理器(可選),這樣您就可以看到自己在做什么。
  2. 確保 Azurite 在 docker 桌面上啟動並運行。
  3. 用任何語言編寫您自己的 Azure Blob 代碼。 (我使用了 C#,您可以在問題代碼示例中看到)。
  4. 創建針對 Azurite 的方法的測試(以下答案中的示例)。
  5. When all working locally, we start automating Azurite Docker startup in C# code using Docker.DotNet so it can automatically pull and fire up Azurite for testing locally and in GitHub actions for Continuous Integration.

就我而言,我使用 azure 存儲方法制作了一個簡單的 class。 您可以執行以下操作(僅示例):

[Fact]
public async Task AzureBlobStorageTest()
{
    // Arrange
    await _azureBlobStorage?.CreateTextFile("file.txt", Encoding.UTF8.GetBytes(Content))!;

    // Act
    var readTextFile = await _azureBlobStorage.ReadTextFile("file.txt");
    
    // Assert
    Assert.Equal(Content, readTextFile);

    // Finalizing
    await _azureBlobStorage.DeleteTextFile("file.txt");
}

您可以更詳細地閱讀這些步驟並找到源代碼。

享受

免責聲明:正如我上面提到的,我寫了 3 篇關於解決這個問題的文章。 這個鏈接是指我個人的web站點

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM