2017-10-12 78 views
5

我正在構建.NET Core 2.0 Web API,並且正在創建一個Docker鏡像。我對Docker頗爲陌生,所以如果之前已經回答了問題,我很抱歉。從多階段Docker構建(.NET Core 2.0)中提取單元測試結果

我有用於創建圖像的以下Docker文件。特別是,我在構建過程中運行單元測試,並將結果輸出到./test/test_results.xml(在構建過程中創建的臨時容器中,我猜)。我的問題是,如何在構建完成後訪問這些測試結果?

FROM microsoft/aspnetcore-build:2.0 AS build-env 

WORKDIR /app 

# Copy main csproj file for DataService 
COPY src/DataService.csproj ./src/ 
RUN dotnet restore ./src/DataService.csproj 

# Copy test csproj file for DataService 
COPY test/DataService.Tests.csproj ./test/ 
RUN dotnet restore ./test/DataService.Tests.csproj 

# Copy everything else (excluding elements in dockerignore) 
COPY . ./ 

# Run the unit tests 
RUN dotnet test --results-directory ./ --logger "trx;LogFileName=test_results.xml" ./test/DataService.Tests.csproj 

# Publish the app to the out directory 
RUN dotnet publish ./src/DataService.csproj -c Release -o out 

# Build the runtime image 
FROM microsoft/aspnetcore:2.0 
WORKDIR /app 
EXPOSE 5001 
COPY --from=build-env /app/src/out . 

# Copy test results to the final image as well?? 
# COPY --from=build-env /app/test/test_results.xml . 

ENTRYPOINT ["dotnet", "DataService.dll"] 

我採取的一種方法是在行# COPY --from=build-env /app/test/test_results.xml .註釋。這使我的最終形象test_results.xml。然後,我可以使用以下PowerShell腳本提取這些結果並從最終映像中刪除test_results.xml

$id=$(docker create dataservice) 
docker cp ${id}:app/test_results.xml ./test/test_results.xml 
docker start $id 
docker exec $id rm -rf /app/test_results.xml 
docker commit $id dataservice 
docker rm -vf $id 

這似乎很難看,我想知道是否有更乾淨的方法來做到這一點。

我希望有一種方法可以在docker build期間安裝卷,但似乎並沒有在官方Docker中支持。

我現在正在創建一個單獨的圖像,僅用於單元測試。

不知道是否有推薦的方式來實現我想要的。

+0

你有沒有找到一個解決方案呢?我遇到了完全相同的問題。 – Mike

+0

@Mike不,對不起,還沒有。我剛剛採用了我提到的將測試結果臨時添加到最終圖像並提取它們的方法。相當新的Docker,所以我只是想檢查是否有其他方式做這個或推薦的方式。 – Francis

回答

0

感謝您的問題 - 我需要解決同樣的問題。

我根據構建結果添加了一個單獨的容器階段。測試和它的輸出都在那裏處理,所以他們永遠不會到達最終的容器。因此,建立-ENV用於構建,然後中間測試容器是基於該生成-ENV圖像上,並最終基於與在複製生成-ENV的結果運行時容器。

# ---- Test ---- 
# run tests and capture results for later use. This use the results of the build stage 
FROM build AS test 
#Use label so we can later obtain this container from the multi-stage build 
LABEL test=true 
WORKDIR/
#Store test results in a file that we will later extract 
RUN dotnet test --results-directory ../../TestResults/ --logger "trx;LogFileName=test_results.xml" "./src/ProjectNameTests/ProjectNameTests.csproj" 

我添加了一個外殼腳本作爲下一步,然後將圖像標記爲項目測試。

#!bin/bash 
id=`docker images --filter "label=test=true" -q` 
docker tag $id projectname-test:latest 

之後,我基本上做了你所做的事情,就是使用docker cp並獲取文件。不同的是我的測試結果從來沒有在最終的圖像,所以我不碰最終的形象。

總的來說,我認爲處理測試的正確方法可能是創建一個測試映像(基於構建映像),併爲測試結果運行安裝的卷,並在容器啓動時運行單元測試。有一個適當的圖像/容器也可以讓你運行集成測試等。這篇文章較舊,但細節類似https://blogs.infosupport.com/build-deploy-test-aspnetcore-docker-linux-tfs2015/