From b75fbe8e2c9459335129e0daa2ff5263d87c2843 Mon Sep 17 00:00:00 2001 From: Marcel Skierkowski Date: Tue, 8 Apr 2025 14:26:04 +0000 Subject: [PATCH] refactor: mock filesystem in ocloc ult pt.1 Mocked IO operations in ./ocloc_tests application Mocked gtest stdout capture in ocloc tests Related-To: NEO-14084 Signed-off-by: Marcel Skierkowski --- .../decoder/decoder_tests.cpp | 30 +- .../decoder/encoder_tests.cpp | 20 +- .../decoder/zebin_manipulator_tests.cpp | 35 +- .../mock/mock_argument_helper.h | 34 +- .../mock/mock_multi_command.h | 9 +- .../mock/mock_offline_compiler.cpp | 4 +- .../offline_compiler/ocloc_api_tests.cpp | 442 +++++- .../ocloc_fatbinary_tests.cpp | 980 +++++++------ .../offline_compiler/ocloc_fatbinary_tests.h | 34 +- .../ocloc_fcl_facade_tests.cpp | 53 +- .../ocloc_igc_facade_tests.cpp | 53 +- .../offline_compiler_tests.cpp | 1273 +++++++++++------ .../offline_compiler/offline_compiler_tests.h | 41 +- .../offline_compiler/offline_linker_tests.cpp | 108 +- .../offline_compiler/stdout_capturer.h | 11 +- .../ptl/offline_compiler_tests_ptl.cpp | 13 +- .../source/decoder/helper.cpp | 27 +- .../source/offline_compiler.cpp | 7 +- shared/source/utilities/io_functions.cpp | 6 +- shared/source/utilities/io_functions.h | 26 +- shared/test/common/helpers/stdout_capture.h | 73 + .../test/common/libult/mock_io_functions.cpp | 5 +- shared/test/common/mocks/mock_compilers.cpp | 41 +- shared/test/common/mocks/mock_io_functions.h | 8 +- 24 files changed, 2136 insertions(+), 1197 deletions(-) create mode 100644 shared/test/common/helpers/stdout_capture.h diff --git a/opencl/test/unit_test/offline_compiler/decoder/decoder_tests.cpp b/opencl/test/unit_test/offline_compiler/decoder/decoder_tests.cpp index 4fa407cf3d..ee1102a768 100644 --- a/opencl/test/unit_test/offline_compiler/decoder/decoder_tests.cpp +++ b/opencl/test/unit_test/offline_compiler/decoder/decoder_tests.cpp @@ -10,6 +10,7 @@ #include "shared/source/helpers/hw_info.h" #include "shared/source/helpers/product_config_helper.h" #include "shared/test/common/helpers/gtest_helpers.h" +#include "shared/test/common/helpers/mock_file_io.h" #include "shared/test/common/helpers/test_files.h" #include "shared/test/common/helpers/variable_backup.h" @@ -493,7 +494,6 @@ TEST(DecoderTests, GivenProperStructWhenReadingStructFieldsThenFieldsVectorGetsP TEST(DecoderTests, GivenProperPatchListFileWhenParsingTokensThenFileIsParsedCorrectly) { MockDecoder decoder; - decoder.pathToPatch = clFiles; decoder.parseTokens(); EXPECT_EQ(static_cast(28), (decoder.programHeader.size)); @@ -532,31 +532,12 @@ TEST(DecoderTests, GivenProperPatchListFileWhenParsingTokensThenFileIsParsedCorr EXPECT_EQ(static_cast(4), (decoder.kernelHeader.fields[8].size)); EXPECT_EQ("KernelUnpaddedSize", (decoder.kernelHeader.fields[8].name)); - EXPECT_EQ(static_cast(4), (decoder.patchTokens[2]->size)); - EXPECT_EQ("PATCH_TOKEN_STATE_SIP", (decoder.patchTokens[2]->name)); - EXPECT_EQ(static_cast(4), (decoder.patchTokens[2]->fields[0].size)); - EXPECT_EQ("SystemKernelOffset", (decoder.patchTokens[2]->fields[0].name)); - - EXPECT_EQ(static_cast(12), decoder.patchTokens[5]->size); - EXPECT_EQ("PATCH_TOKEN_SAMPLER_STATE_ARRAY", decoder.patchTokens[5]->name); - EXPECT_EQ(static_cast(4), (decoder.patchTokens[5]->fields[0].size)); - EXPECT_EQ("Offset", (decoder.patchTokens[5]->fields[0].name)); - EXPECT_EQ(static_cast(4), (decoder.patchTokens[5]->fields[1].size)); - EXPECT_EQ("Count", (decoder.patchTokens[5]->fields[1].name)); - EXPECT_EQ(static_cast(4), (decoder.patchTokens[5]->fields[2].size)); - EXPECT_EQ("BorderColorOffset", (decoder.patchTokens[5]->fields[2].name)); - EXPECT_EQ(static_cast(8), decoder.patchTokens[42]->size); EXPECT_EQ("PATCH_TOKEN_ALLOCATE_CONSTANT_MEMORY_SURFACE_PROGRAM_BINARY_INFO", decoder.patchTokens[42]->name); EXPECT_EQ(static_cast(4), (decoder.patchTokens[42]->fields[0].size)); EXPECT_EQ("ConstantBufferIndex", (decoder.patchTokens[42]->fields[0].name)); EXPECT_EQ(static_cast(4), (decoder.patchTokens[42]->fields[1].size)); EXPECT_EQ("InlineDataSize", (decoder.patchTokens[42]->fields[1].name)); - - EXPECT_EQ(static_cast(4), decoder.patchTokens[19]->size); - EXPECT_EQ("PATCH_TOKEN_MEDIA_INTERFACE_DESCRIPTOR_LOAD", decoder.patchTokens[19]->name); - EXPECT_EQ(static_cast(4), (decoder.patchTokens[19]->fields[0].size)); - EXPECT_EQ("InterfaceDescriptorDataOffset", (decoder.patchTokens[19]->fields[0].name)); } TEST(DecoderTests, WhenPathToPatchTokensNotProvidedThenUseDefaults) { @@ -618,7 +599,6 @@ TEST(DecoderTests, GivenValidBinaryWithoutPatchTokensWhenProcessingBinaryThenBin std::stringstream ptmFile; MockDecoder decoder; - decoder.pathToPatch = clFiles; decoder.pathToDump = "non_existing_folder/"; decoder.parseTokens(); @@ -645,9 +625,10 @@ TEST(DecoderTests, givenBinaryWithKernelBinaryHeaderWhenAtLeastOneOfTheKernelSiz std::stringstream ptmFile; MockDecoder decoder{false}; - decoder.pathToPatch = clFiles; + decoder.mockArgHelper->messagePrinter.setSuppressMessages(true); decoder.pathToDump = "non_existing_folder/"; decoder.parseTokens(); + decoder.mockArgHelper->messagePrinter.setSuppressMessages(false); std::string binaryString = binarySS.str(); std::vector binary(binaryString.begin(), binaryString.end()); @@ -696,7 +677,6 @@ TEST(DecoderTests, GivenValidBinaryWhenProcessingBinaryThenProgramAndKernelAndPa std::vector binary(binaryString.begin(), binaryString.end()); std::stringstream ptmFile; MockDecoder decoder; - decoder.pathToPatch = clFiles; decoder.pathToDump = "non_existing_folder/"; decoder.parseTokens(); @@ -704,7 +684,7 @@ TEST(DecoderTests, GivenValidBinaryWhenProcessingBinaryThenProgramAndKernelAndPa int retVal = decoder.processBinary(ptr, binary.size(), ptmFile); EXPECT_EQ(0, retVal); - std::string expectedOutput = "ProgramBinaryHeader:\n\t4 Magic 1229870147\n\t4 Version 0\n\t4 Device 0\n\t4 GPUPointerSizeInBytes 0\n\t4 NumberOfKernels 1\n\t4 SteppingId 0\n\t4 PatchListSize 30\nPATCH_TOKEN_ALLOCATE_CONSTANT_MEMORY_SURFACE_PROGRAM_BINARY_INFO:\n\t4 Token 42\n\t4 Size 16\n\t4 ConstantBufferIndex 0\n\t4 InlineDataSize 14\n\tHex 0 1 2 3 4 5 6 7 8 9 a b c d\nKernel #0\nKernelBinaryHeader:\n\t4 CheckSum 4294967295\n\t8 ShaderHashCode 18446744073709551615\n\t4 KernelNameSize 14\n\t4 PatchListSize 12\n\t4 KernelHeapSize 0\n\t4 GeneralStateHeapSize 0\n\t4 DynamicStateHeapSize 0\n\t4 SurfaceStateHeapSize 0\n\t4 KernelUnpaddedSize 0\n\tKernelName ExampleKernel\nPATCH_TOKEN_MEDIA_INTERFACE_DESCRIPTOR_LOAD:\n\t4 Token 19\n\t4 Size 12\n\t4 InterfaceDescriptorDataOffset 0\n"; + std::string expectedOutput = "ProgramBinaryHeader:\n\t4 Magic 1229870147\n\t4 Version 0\n\t4 Device 0\n\t4 GPUPointerSizeInBytes 0\n\t4 NumberOfKernels 1\n\t4 SteppingId 0\n\t4 PatchListSize 30\nPATCH_TOKEN_ALLOCATE_CONSTANT_MEMORY_SURFACE_PROGRAM_BINARY_INFO:\n\t4 Token 42\n\t4 Size 16\n\t4 ConstantBufferIndex 0\n\t4 InlineDataSize 14\n\tHex 0 1 2 3 4 5 6 7 8 9 a b c d\nKernel #0\nKernelBinaryHeader:\n\t4 CheckSum 4294967295\n\t8 ShaderHashCode 18446744073709551615\n\t4 KernelNameSize 14\n\t4 PatchListSize 12\n\t4 KernelHeapSize 0\n\t4 GeneralStateHeapSize 0\n\t4 DynamicStateHeapSize 0\n\t4 SurfaceStateHeapSize 0\n\t4 KernelUnpaddedSize 0\n\tKernelName ExampleKernel\nUnidentified PatchToken:\n\t4 Token 19\n\t4 Size 12\n\tHex 0 0 0 0\n"; EXPECT_EQ(expectedOutput, ptmFile.str()); EXPECT_TRUE(decoder.getMockIga()->disasmWasCalled); EXPECT_FALSE(decoder.getMockIga()->asmWasCalled); @@ -817,4 +797,4 @@ TEST(DecoderHelperTest, GivenProductFamilyWhenTranslatingToIgaGenBaseThenExpecte } } -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/opencl/test/unit_test/offline_compiler/decoder/encoder_tests.cpp b/opencl/test/unit_test/offline_compiler/decoder/encoder_tests.cpp index 9fe274cd3b..93e39f3202 100644 --- a/opencl/test/unit_test/offline_compiler/decoder/encoder_tests.cpp +++ b/opencl/test/unit_test/offline_compiler/decoder/encoder_tests.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018-2023 Intel Corporation + * Copyright (C) 2018-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -8,6 +8,7 @@ #include "shared/offline_compiler/source/decoder/binary_decoder.h" #include "shared/source/helpers/aligned_memory.h" #include "shared/source/helpers/array_count.h" +#include "shared/test/common/helpers/stdout_capture.h" #include "shared/test/common/helpers/test_files.h" #include "opencl/test/unit_test/offline_compiler/environment.h" @@ -50,9 +51,10 @@ TEST(EncoderTests, GivenFlagsWhichRequireMoreArgsWithoutThemWhenParsingThenError constexpr auto suppressMessages{false}; MockEncoder encoder{suppressMessages}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = encoder.validateInput(args); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(-1, result); @@ -111,9 +113,10 @@ TEST(EncoderTests, GivenMissingDumpFlagAndArgHelperOutputEnabledWhenParsingValid encoder.mockArgHelper->hasOutput = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = encoder.validateInput(args); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(0, result); EXPECT_TRUE(output.empty()) << output; @@ -126,9 +129,10 @@ TEST(EncoderTests, GivenMissingPTMFileWhenEncodingThenErrorIsReturnedAndLogIsPri constexpr auto suppressMessages{false}; MockEncoder encoder{suppressMessages}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = encoder.encode(); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(-1, result); EXPECT_EQ("Error! Couldn't find PTM.txt", output); @@ -586,4 +590,4 @@ TEST(EncoderTests, WhenProcessingDeviceBinaryAndAsmIsAvailableThenAseembleItWith EXPECT_EQ(encoder.filesMap["kernel_KernelHeap.asm"], encoder.getMockIga()->receivedAsm); } -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/opencl/test/unit_test/offline_compiler/decoder/zebin_manipulator_tests.cpp b/opencl/test/unit_test/offline_compiler/decoder/zebin_manipulator_tests.cpp index db505e0d33..8ee94c1e24 100644 --- a/opencl/test/unit_test/offline_compiler/decoder/zebin_manipulator_tests.cpp +++ b/opencl/test/unit_test/offline_compiler/decoder/zebin_manipulator_tests.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2024 Intel Corporation + * Copyright (C) 2022-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -10,7 +10,10 @@ #include "shared/source/device_binary_format/elf/elf.h" #include "shared/source/device_binary_format/elf/elf_encoder.h" #include "shared/source/helpers/product_config_helper.h" +#include "shared/test/common/helpers/stdout_capture.h" +#include "shared/test/common/helpers/variable_backup.h" #include "shared/test/common/mocks/mock_elf.h" +#include "shared/test/common/mocks/mock_io_functions.h" #include "shared/test/common/mocks/mock_modules_zebin.h" #include "shared/test/common/test_macros/test.h" @@ -107,6 +110,7 @@ kernels: }; TEST(ZebinManipulatorTests, GivenValidZebinWhenItIsDisassembledAndAssembledBackThenItIsSameBinary) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); MockZebin mockZebin32; MockZebin mockZebin64; for (const auto zebin : {&mockZebin32.storage, &mockZebin64.storage}) { @@ -210,9 +214,10 @@ TEST_F(ZebinManipulatorValidateInputTests, GivenInvalidInputWhenValidatingInputT "asm/disasm", "-unknown_arg"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); auto retVal = NEO::Zebin::Manipulator::validateInput(args, &iga, &argHelper, arguments); - const auto output{testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, retVal); EXPECT_EQ("Unknown argument -unknown_arg\n", output); @@ -224,9 +229,10 @@ TEST_F(ZebinManipulatorValidateInputTests, GivenMissingFileWhenValidatingInputTh "-dump", "./dump/"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); auto retVal = NEO::Zebin::Manipulator::validateInput(args, &iga, &argHelper, arguments); - const auto output{testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, retVal); EXPECT_EQ("Error: Missing -file argument\n", output); @@ -238,9 +244,10 @@ TEST_F(ZebinManipulatorValidateInputTests, GivenMissingSecondPartOfTheArgumentWh "-arg"}; for (const auto halfArg : {"-file", "-device", "-dump"}) { args[2] = halfArg; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); auto retVal = NEO::Zebin::Manipulator::validateInput(args, &iga, &argHelper, arguments); - const auto output{testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, retVal); const auto expectedOutput = "Unknown argument " + std::string(halfArg) + "\n"; @@ -253,9 +260,11 @@ TEST_F(ZebinManipulatorValidateInputTests, GivenValidArgsButDumpNotSpecifiedWhen "asm/disasm", "-file", "binary.bin"}; - testing::internal::CaptureStdout(); + + StdoutCapture capture; + capture.captureStdout(); auto retVal = NEO::Zebin::Manipulator::validateInput(args, &iga, &argHelper, arguments); - const auto output{testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_SUCCESS, retVal); EXPECT_EQ("Warning: Path to dump -dump not specified. Using \"./dump/\" as dump folder.\n", output); @@ -567,6 +576,8 @@ TEST_F(ZebinEncoderTests, GivenInvalidIntelGTNotesSectionWhenGetIntelGTNotesThen } TEST_F(ZebinEncoderTests, GivenInvalidSymtabFileWhenAppendSymtabThenErrorIsReturned) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); + MockElfEncoder elfEncoder; NEO::Zebin::Manipulator::SectionInfo sectionInfo; sectionInfo.name = ".symtab"; @@ -578,6 +589,8 @@ TEST_F(ZebinEncoderTests, GivenInvalidSymtabFileWhenAppendSymtabThenErrorIsRetur } TEST_F(ZebinEncoderTests, GivenInvalidRelFileWhenAppendRelThenErrorIsReturned) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); + MockElfEncoder elfEncoder; NEO::Zebin::Manipulator::SectionInfo sectionInfo; sectionInfo.name = ".rel.text"; @@ -589,6 +602,8 @@ TEST_F(ZebinEncoderTests, GivenInvalidRelFileWhenAppendRelThenErrorIsReturned) { } TEST_F(ZebinEncoderTests, GivenInvalidRelaFileWhenAppendRelaThenErrorIsReturned) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); + MockElfEncoder elfEncoder; NEO::Zebin::Manipulator::SectionInfo sectionInfo; sectionInfo.name = ".rela.text"; @@ -649,4 +664,4 @@ TEST_F(ZebinEncoderTests, GivenMissingFileWhenCheckIfAllFilesExistThenErrorIsRet TEST_F(ZebinEncoderTests, WhenPrintHelpIsCalledThenHelpIsPrinted) { encoder.printHelp(); EXPECT_FALSE(getOutput().empty()); -} +} \ No newline at end of file diff --git a/opencl/test/unit_test/offline_compiler/mock/mock_argument_helper.h b/opencl/test/unit_test/offline_compiler/mock/mock_argument_helper.h index c1840be99d..22d4547244 100644 --- a/opencl/test/unit_test/offline_compiler/mock/mock_argument_helper.h +++ b/opencl/test/unit_test/offline_compiler/mock/mock_argument_helper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2024 Intel Corporation + * Copyright (C) 2020-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -69,13 +69,17 @@ class MockOclocArgHelper : public OclocArgHelper { return std::vector(file.begin(), file.end()); } + std::string getLog() { + return messagePrinter.getLog().str(); + } + protected: bool fileExists(const std::string &filename) const override { if (filesMap.find(filename) != filesMap.end()) { return true; } - return OclocArgHelper::fileExists(filename); + return OclocArgHelper::sourceFileExists(filename); } std::unique_ptr loadDataFromFile(const std::string &filename, size_t &retSize) override { @@ -83,6 +87,14 @@ class MockOclocArgHelper : public OclocArgHelper { return OclocArgHelper::loadDataFromFile(filename, retSize); } + if (Source *s = findSourceFile(filename)) { + auto size = s->length; + std::unique_ptr ret(new char[size]()); + memcpy_s(ret.get(), size, s->data, s->length); + retSize = s->length; + return ret; + } + if (shouldLoadDataFromFileReturnZeroSize) { retSize = 0; return {}; @@ -90,17 +102,15 @@ class MockOclocArgHelper : public OclocArgHelper { if (!fileExists(filename)) { return OclocArgHelper::loadDataFromFile(filename, retSize); + } else { + const auto &file = filesMap[filename]; + std::unique_ptr result{new char[file.size() + 1]}; + std::copy(file.begin(), file.end(), result.get()); + result[file.size()] = '\0'; + retSize = file.size() + 1; + + return result; } - - const auto &file = filesMap[filename]; - - std::unique_ptr result{new char[file.size() + 1]}; - std::copy(file.begin(), file.end(), result.get()); - result[file.size()] = '\0'; - - retSize = file.size() + 1; - - return result; } void saveOutput(const std::string &filename, const void *pData, const size_t &dataSize) override { diff --git a/opencl/test/unit_test/offline_compiler/mock/mock_multi_command.h b/opencl/test/unit_test/offline_compiler/mock/mock_multi_command.h index d746ed2e08..7a274edae0 100644 --- a/opencl/test/unit_test/offline_compiler/mock/mock_multi_command.h +++ b/opencl/test/unit_test/offline_compiler/mock/mock_multi_command.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2023 Intel Corporation + * Copyright (C) 2022-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -32,8 +32,9 @@ class MockMultiCommand : public MultiCommand { using MultiCommand::splitLineInSeparateArgs; MockMultiCommand() : MultiCommand{} { + filesMap[clCopybufferFilename] = kernelSources; uniqueHelper = std::make_unique(filesMap); - uniqueHelper->setAllCallBase(true); + uniqueHelper->setAllCallBase(false); argHelper = uniqueHelper.get(); } @@ -53,6 +54,8 @@ class MockMultiCommand : public MultiCommand { std::unique_ptr uniqueHelper{}; int singleBuildCalledCount{0}; bool callBaseSingleBuild{true}; + const std::string clCopybufferFilename = "some_kernel.cl"; + std::string kernelSources = "example_kernel(){}"; }; -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/opencl/test/unit_test/offline_compiler/mock/mock_offline_compiler.cpp b/opencl/test/unit_test/offline_compiler/mock/mock_offline_compiler.cpp index 9745b00488..f81fb17049 100644 --- a/opencl/test/unit_test/offline_compiler/mock/mock_offline_compiler.cpp +++ b/opencl/test/unit_test/offline_compiler/mock/mock_offline_compiler.cpp @@ -15,7 +15,7 @@ namespace NEO { MockOfflineCompiler::MockOfflineCompiler() : OfflineCompiler() { uniqueHelper = std::make_unique(filesMap); - uniqueHelper->setAllCallBase(true); + uniqueHelper->setAllCallBase(false); argHelper = uniqueHelper.get(); auto uniqueFclFacadeMock = std::make_unique(argHelper); @@ -88,4 +88,4 @@ void MockOfflineCompiler::createDir(const std::string &path) { } } -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/opencl/test/unit_test/offline_compiler/ocloc_api_tests.cpp b/opencl/test/unit_test/offline_compiler/ocloc_api_tests.cpp index 60116170e7..048c28748a 100644 --- a/opencl/test/unit_test/offline_compiler/ocloc_api_tests.cpp +++ b/opencl/test/unit_test/offline_compiler/ocloc_api_tests.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2024 Intel Corporation + * Copyright (C) 2020-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -19,7 +19,11 @@ #include "shared/source/helpers/file_io.h" #include "shared/source/helpers/product_config_helper.h" #include "shared/source/helpers/string.h" +#include "shared/test/common/helpers/gtest_helpers.h" +#include "shared/test/common/helpers/mock_file_io.h" +#include "shared/test/common/helpers/stdout_capture.h" #include "shared/test/common/helpers/variable_backup.h" +#include "shared/test/common/mocks/mock_io_functions.h" #include "shared/test/common/mocks/mock_os_library.h" #include "environment.h" @@ -29,6 +33,7 @@ #include #include +#include #include #include @@ -43,8 +48,52 @@ void mockedAbortOclocExecution(int errorCode) { TEST(OclocApiTests, WhenOclocVersionIsCalledThenCurrentOclocVersionIsReturned) { EXPECT_EQ(ocloc_version_t::OCLOC_VERSION_CURRENT, oclocVersion()); } +class OclocApiTest : public ::testing::Test { + protected: + void SetUp() override { + std::string spvFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".spv"; + std::string binFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".bin"; + std::string dbgFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".dbg"; + std::vector mockByteArray = {0x01, 0x02, 0x03, 0x04}; + writeDataToFile(spvFile.c_str(), mockByteArray.data(), mockByteArray.size()); + writeDataToFile(binFile.c_str(), mockByteArray.data(), mockByteArray.size()); + writeDataToFile(dbgFile.c_str(), mockByteArray.data(), mockByteArray.size()); + writeDataToFile(clCopybufferFilename.c_str(), kernelSources.data(), mockByteArray.size()); + } + + const std::string clCopybufferFilename = "some_kernel.cl"; + std::string kernelSources = "example_kernel(){}"; +}; +TEST_F(OclocApiTest, WhenGoodArgsAreGivenThenSuccessIsReturned) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "copybuffer.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + VariableBackup mockFseek(&NEO::IoFunctions::fseekPtr, [](FILE *stream, long int offset, int origin) -> int { return 0; }); + VariableBackup mockFtell(&NEO::IoFunctions::ftellPtr, [](FILE *stream) -> long int { + std::string kernelSources = "example_kernel(){}"; + std::stringstream fileStream(kernelSources); + fileStream.seekg(0, std::ios::end); + return static_cast(fileStream.tellg()); + }); + VariableBackup mockFread(&NEO::IoFunctions::freadPtr, [](void *ptr, size_t size, size_t count, FILE *stream) -> size_t { + std::string kernelSources = "example_kernel(){}"; + std::stringstream fileStream(kernelSources); + size_t totalBytes = size * count; + fileStream.read(static_cast(ptr), totalBytes); + return static_cast(fileStream.gcount() / size); + }); -TEST(OclocApiTests, WhenGoodArgsAreGivenThenSuccessIsReturned) { std::string clFileName(clFiles + "copybuffer.cl"); const char *argv[] = { "ocloc", @@ -54,19 +103,49 @@ TEST(OclocApiTests, WhenGoodArgsAreGivenThenSuccessIsReturned) { gEnvironment->devicePrefix.c_str()}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_SUCCESS); EXPECT_EQ(std::string::npos, output.find("Command was: ocloc -file test_files/copybuffer.cl -device "s + argv[4])); EXPECT_NE(std::string::npos, output.find("Build succeeded.\n")); } -TEST(OclocApiTests, GivenQuietModeAndValidArgumentsWhenRunningOclocThenSuccessIsReturnedAndBuildSucceededMessageIsNotPrinted) { +TEST_F(OclocApiTest, GivenQuietModeAndValidArgumentsWhenRunningOclocThenSuccessIsReturnedAndBuildSucceededMessageIsNotPrinted) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "copybuffer.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + VariableBackup mockFseek(&NEO::IoFunctions::fseekPtr, [](FILE *stream, long int offset, int origin) -> int { return 0; }); + VariableBackup mockFtell(&NEO::IoFunctions::ftellPtr, [](FILE *stream) -> long int { + std::string kernelSources = "example_kernel(){}"; + std::stringstream fileStream(kernelSources); + fileStream.seekg(0, std::ios::end); + return static_cast(fileStream.tellg()); + }); + VariableBackup mockFread(&NEO::IoFunctions::freadPtr, [](void *ptr, size_t size, size_t count, FILE *stream) -> size_t { + std::string kernelSources = "example_kernel(){}"; + std::stringstream fileStream(kernelSources); + size_t totalBytes = size * count; + fileStream.read(static_cast(ptr), totalBytes); + return static_cast(fileStream.gcount() / size); + }); + std::string clFileName(clFiles + "copybuffer.cl"); const char *argv[] = { "ocloc", @@ -77,12 +156,13 @@ TEST(OclocApiTests, GivenQuietModeAndValidArgumentsWhenRunningOclocThenSuccessIs gEnvironment->devicePrefix.c_str()}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_SUCCESS, retVal); EXPECT_EQ(std::string::npos, output.find("Command was: ocloc -file test_files/copybuffer.cl -device "s + argv[4])); @@ -187,12 +267,13 @@ TEST(OclocApiTests, GivenNoQueryWhenQueryingThenErrorIsReturned) { "ocloc", "query"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_INVALID_COMMAND_LINE); EXPECT_STREQ("Error: Invalid command line. Expected ocloc query . See ocloc query --help\nCommand was: ocloc query\n", output.c_str()); @@ -204,12 +285,13 @@ TEST(OclocApiTests, GivenInvalidQueryWhenQueryingThenErrorIsReturned) { "query", "unknown_query"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_INVALID_COMMAND_LINE); EXPECT_STREQ("Error: Invalid command line.\nUnknown argument unknown_query\nCommand was: ocloc query unknown_query\n", output.c_str()); @@ -220,12 +302,13 @@ TEST(OclocApiTests, givenNoAcronymWhenIdsCommandIsInvokeThenErrorIsReported) { "ocloc", "ids"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_INVALID_COMMAND_LINE); EXPECT_STREQ("Error: Invalid command line. Expected ocloc ids .\nCommand was: ocloc ids\n", output.c_str()); @@ -237,18 +320,47 @@ TEST(OclocApiTests, givenUnknownAcronymWhenIdsCommandIsInvokeThenErrorIsReported "ids", "unk"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_INVALID_COMMAND_LINE); EXPECT_STREQ("Error: Invalid command line. Unknown acronym unk.\nCommand was: ocloc ids unk\n", output.c_str()); } -TEST(OclocApiTests, WhenGoodFamilyNameIsProvidedThenSuccessIsReturned) { +TEST_F(OclocApiTest, WhenGoodFamilyNameIsProvidedThenSuccessIsReturned) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "copybuffer.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + VariableBackup mockFseek(&NEO::IoFunctions::fseekPtr, [](FILE *stream, long int offset, int origin) -> int { return 0; }); + VariableBackup mockFtell(&NEO::IoFunctions::ftellPtr, [](FILE *stream) -> long int { + std::string kernelSource = "example_kernel(){}"; + std::stringstream fileStream(kernelSource); + fileStream.seekg(0, std::ios::end); + return static_cast(fileStream.tellg()); + }); + VariableBackup mockFread(&NEO::IoFunctions::freadPtr, [](void *ptr, size_t size, size_t count, FILE *stream) -> size_t { + std::string kernelSource = "example_kernel(){}"; + std::stringstream fileStream(kernelSource); + size_t totalBytes = size * count; + fileStream.read(static_cast(ptr), totalBytes); + return static_cast(fileStream.gcount() / size); + }); std::string clFileName(clFiles + "copybuffer.cl"); std::unique_ptr argHelper = std::make_unique(); auto allSupportedDeviceConfigs = argHelper->productConfigHelper->getDeviceAotInfo(); @@ -275,18 +387,34 @@ TEST(OclocApiTests, WhenGoodFamilyNameIsProvidedThenSuccessIsReturned) { family.c_str()}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_SUCCESS); EXPECT_EQ(std::string::npos, output.find("Command was: ocloc -file " + clFileName + " -device " + family)); } TEST(OclocApiTests, WhenArgsWithMissingFileAreGivenThenErrorMessageIsProduced) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + const char *argv[] = { "ocloc", "-q", @@ -296,18 +424,34 @@ TEST(OclocApiTests, WhenArgsWithMissingFileAreGivenThenErrorMessageIsProduced) { gEnvironment->devicePrefix.c_str()}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_INVALID_FILE); EXPECT_NE(std::string::npos, output.find("Command was: ocloc -q -file test_files/IDoNotExist.cl -device "s + argv[5])); } TEST(OclocApiTests, givenInputOptionsAndInternalOptionsWhenCmdlineIsPrintedThenBothAreInQuotes) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + const char *argv[] = { "ocloc", "-q", @@ -318,12 +462,13 @@ TEST(OclocApiTests, givenInputOptionsAndInternalOptionsWhenCmdlineIsPrintedThenB "-options", "-D DEBUG -cl-kernel-arg-info", "-internal_options", "-internalOption1 -internal-option-2"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_NE(retVal, OCLOC_SUCCESS); EXPECT_TRUE(output.find("Command was: ocloc -q -file test_files/IDoNotExist.cl -device " + gEnvironment->devicePrefix + @@ -334,6 +479,21 @@ TEST(OclocApiTests, givenInputOptionsAndInternalOptionsWhenCmdlineIsPrintedThenB } TEST(OclocApiTests, givenInputOptionsCalledOptionsWhenCmdlineIsPrintedThenQuotesAreCorrect) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + const char *argv[] = { "ocloc", "-q", @@ -344,12 +504,13 @@ TEST(OclocApiTests, givenInputOptionsCalledOptionsWhenCmdlineIsPrintedThenQuotes "-options", "-options", "-internal_options", "-internalOption"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_NE(retVal, OCLOC_SUCCESS); EXPECT_TRUE(output.find("Command was: ocloc -q -file test_files/IDoNotExist.cl -device " + gEnvironment->devicePrefix + @@ -359,7 +520,22 @@ TEST(OclocApiTests, givenInputOptionsCalledOptionsWhenCmdlineIsPrintedThenQuotes EXPECT_EQ(quotesCount, 4u); } -TEST(OclocApiTests, GivenIncludeHeadersWhenCompilingThenPassesToFclHeadersPackedAsElf) { +TEST_F(OclocApiTest, GivenIncludeHeadersWhenCompilingThenPassesToFclHeadersPackedAsElf) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + auto prevFclDebugVars = NEO::getFclDebugVars(); auto debugVars = prevFclDebugVars; std::string receivedInput; @@ -460,17 +636,19 @@ TEST(OclocApiTests, GivenHelpParameterWhenDecodingThenHelpMsgIsPrintedAndSuccess "--help"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_FALSE(output.empty()); EXPECT_EQ(retVal, OCLOC_SUCCESS); } TEST(OclocApiTests, GivenNonExistingFileWhenDecodingThenAbortIsCalled) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); VariableBackup oclocAbortBackup{&abortOclocExecution, &mockedAbortOclocExecution}; const char *argv[] = { @@ -482,12 +660,13 @@ TEST(OclocApiTests, GivenNonExistingFileWhenDecodingThenAbortIsCalled) { "test_files/created"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_NE(std::string::npos, output.find("mockedAbortOclocExecution() called with error code = 1")); EXPECT_EQ(-1, retVal); @@ -500,18 +679,48 @@ TEST(OclocApiTests, GivenMissingFileNameWhenDecodingThenErrorIsReturned) { "-file"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_NE(std::string::npos, output.find("Unknown argument -file\n")); EXPECT_EQ(-1, retVal); } -TEST(OclocApiTests, GivenOnlySpirVWithMultipleDevicesWhenCompilingThenFirstDeviceIsSelected) { +TEST_F(OclocApiTest, GivenOnlySpirVWithMultipleDevicesWhenCompilingThenFirstDeviceIsSelected) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "copybuffer.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + VariableBackup mockFseek(&NEO::IoFunctions::fseekPtr, [](FILE *stream, long int offset, int origin) -> int { return 0; }); + VariableBackup mockFtell(&NEO::IoFunctions::ftellPtr, [](FILE *stream) -> long int { + std::string kernelSource = "example_kernel(){}"; + std::stringstream fileStream(kernelSource); + fileStream.seekg(0, std::ios::end); + return static_cast(fileStream.tellg()); + }); + VariableBackup mockFread(&NEO::IoFunctions::freadPtr, [](void *ptr, size_t size, size_t count, FILE *stream) -> size_t { + std::string kernelSource = "example_kernel(){}"; + std::stringstream fileStream(kernelSource); + size_t totalBytes = size * count; + fileStream.read(static_cast(ptr), totalBytes); + return static_cast(fileStream.gcount() / size); + }); + std::string clFileName(clFiles + "copybuffer.cl"); AOT::FAMILY productFamily = AOT::UNKNOWN_FAMILY; std::string familyAcronym(""); @@ -555,12 +764,13 @@ TEST(OclocApiTests, GivenOnlySpirVWithMultipleDevicesWhenCompilingThenFirstDevic } } - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_SUCCESS); EXPECT_EQ(std::string::npos, output.find("Command was: ocloc -device " + firstDeviceAcronym + " -spv_only")); @@ -584,41 +794,88 @@ TEST(OclocApiTests, GivenHelpParameterWhenCompilingThenHelpMsgIsPrintedAndSucces } TEST(OclocApiTests, GivenHelpParameterWhenEncodingThenHelpMsgIsPrintedAndSuccessIsReturned) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + const char *argv[] = { "ocloc", "asm", "--help"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_FALSE(output.empty()); EXPECT_EQ(retVal, OCLOC_SUCCESS); } TEST(OclocApiTests, GivenMissingDumpFileNameWhenEncodingThenErrorIsReturned) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + const char *argv[] = { "ocloc", "asm", "-dump"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_NE(std::string::npos, output.find("Unknown argument -dump\n")); EXPECT_EQ(-1, retVal); } TEST(OclocApiTests, GivenValidArgumentsAndMissingPtmFileWhenEncodingThenErrorIsReturned) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + const char *argv[] = { "ocloc", "asm", @@ -628,12 +885,13 @@ TEST(OclocApiTests, GivenValidArgumentsAndMissingPtmFileWhenEncodingThenErrorIsR "test_files/binary_gen.bin"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_NE(std::string::npos, output.find("Error! Couldn't find PTM.txt")); EXPECT_EQ(-1, retVal); @@ -646,18 +904,34 @@ TEST(OclocApiTests, GiveMultiCommandHelpArgumentsWhenInvokingOclocThenHelpIsPrin "--help"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_FALSE(output.empty()); EXPECT_EQ(-1, retVal); } TEST(OclocApiTests, GivenNonexistentFileWhenValidateIsInvokedThenErrorIsPrinted) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + const char *argv[] = { "ocloc", "validate", @@ -665,13 +939,14 @@ TEST(OclocApiTests, GivenNonexistentFileWhenValidateIsInvokedThenErrorIsPrinted) "some_special_nonexistent_file.gen"}; unsigned int argc = sizeof(argv) / sizeof(argv[0]); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_EQ(-1, retVal); const std::string expectedErrorMessage{"Error : Input file missing : some_special_nonexistent_file.gen\nCommand was: ocloc validate -file some_special_nonexistent_file.gen\n"}; @@ -683,13 +958,14 @@ TEST(OclocApiTests, GivenCommandWithoutArgsWhenOclocIsInvokedThenHelpIsPrinted) "ocloc"}; unsigned int argc = sizeof(argv) / sizeof(argv[0]); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_SUCCESS, retVal); EXPECT_FALSE(output.empty()); } @@ -703,13 +979,14 @@ TEST(OclocApiTests, GivenHelpArgumentWhenOclocIsInvokedThenHelpIsPrinted) { unsigned int argc = sizeof(argv) / sizeof(argv[0]); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_SUCCESS, retVal); EXPECT_FALSE(output.empty()); } @@ -722,12 +999,13 @@ TEST(OclocApiTests, GivenHelpParameterWhenLinkingThenHelpMsgIsPrintedAndSuccessI "--help"}; unsigned int argc = sizeof(argv) / sizeof(argv[0]); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_FALSE(output.empty()); EXPECT_EQ(OCLOC_SUCCESS, retVal); } @@ -739,12 +1017,13 @@ TEST(OclocApiTests, GivenInvalidParameterWhenLinkingThenErrorIsReturned) { "--dummy_param"}; unsigned int argc = sizeof(argv) / sizeof(argv[0]); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, retVal); const std::string expectedInitError{"Invalid option (arg 2): --dummy_param\n"}; @@ -758,12 +1037,13 @@ TEST(OclocApiTests, GivenInvalidCommandLineWhenConcatenatingThenErrorIsReturned) "ocloc", "concat"}; unsigned int argc = sizeof(argv) / sizeof(argv[0]); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, retVal); const std::string emptyCommandLineError = "No files to concatenate were provided.\n"; const std::string expectedErrorMessage = emptyCommandLineError + NEO::OclocConcat::helpMessage.str() + "Command was: ocloc concat\n"; @@ -808,12 +1088,13 @@ TEST(OclocApiTests, GivenValidCommandLineAndFatBinariesWhenConcatenatingThenNewF "-out", "catFatBinary.ar"}; unsigned int argc = sizeof(argv) / sizeof(argv[0]); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 2, sourcesData, sourcesLen, sourcesName, 0, nullptr, nullptr, nullptr, &numOutputs, &outputData, &outputLen, &outputName); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_SUCCESS, retVal); EXPECT_TRUE(output.empty()); @@ -851,7 +1132,36 @@ TEST(OclocApiTests, GivenValidCommandLineAndFatBinariesWhenConcatenatingThenNewF oclocFreeOutput(&numOutputs, &outputData, &outputLen, &outputName); } -TEST(OclocApiTests, GivenVerboseModeWhenCompilingThenPrintCommandLine) { +TEST_F(OclocApiTest, GivenVerboseModeWhenCompilingThenPrintCommandLine) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "copybuffer.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + VariableBackup mockFseek(&NEO::IoFunctions::fseekPtr, [](FILE *stream, long int offset, int origin) -> int { return 0; }); + VariableBackup mockFtell(&NEO::IoFunctions::ftellPtr, [](FILE *stream) -> long int { + std::string kernelSource = "example_kernel(){}"; + std::stringstream fileStream(kernelSource); + fileStream.seekg(0, std::ios::end); + return static_cast(fileStream.tellg()); + }); + VariableBackup mockFread(&NEO::IoFunctions::freadPtr, [](void *ptr, size_t size, size_t count, FILE *stream) -> size_t { + std::string kernelSource = "example_kernel(){}"; + std::stringstream fileStream(kernelSource); + size_t totalBytes = size * count; + fileStream.read(static_cast(ptr), totalBytes); + return static_cast(fileStream.gcount() / size); + }); + std::string clFileName(clFiles + "copybuffer.cl"); const char *argv[] = { "ocloc", @@ -862,12 +1172,13 @@ TEST(OclocApiTests, GivenVerboseModeWhenCompilingThenPrintCommandLine) { "-v"}; unsigned int argc = sizeof(argv) / sizeof(const char *); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_SUCCESS); EXPECT_NE(std::string::npos, output.find("Command was: ocloc -file "s + clFileName.c_str() + " -device "s + argv[4] + " -v")) << output; @@ -919,14 +1230,15 @@ struct OclocFallbackTests : ::testing::Test { &numOutputs, &dataOutputs, &lenOutputs, &nameOutputs); return retVal; } else { - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); testing::internal::CaptureStderr(); auto retVal = oclocInvoke(argc, argv, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - capturedStdout = testing::internal::GetCapturedStdout(); + capturedStdout = capture.getCapturedStdout(); capturedStderr = testing::internal::GetCapturedStderr(); return retVal; } @@ -950,6 +1262,7 @@ struct OclocFallbackTests : ::testing::Test { }; TEST_F(OclocFallbackTests, GivenNoFormerOclocNameWhenInvalidDeviceErrorIsReturnedThenDontFallback) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); Ocloc::oclocFormerLibName = ""; @@ -966,6 +1279,7 @@ TEST_F(OclocFallbackTests, GivenNoFormerOclocNameWhenInvalidDeviceErrorIsReturne } TEST_F(OclocFallbackTests, GivenInvalidFormerOclocNameWhenInvalidDeviceErrorIsReturnedThenFallbackButWithoutLoadingLib) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); Ocloc::oclocFormerLibName = "invalidName"; @@ -1012,6 +1326,7 @@ int mockOclocInvoke(unsigned int numArgs, const char *argv[], } TEST_F(OclocFallbackTests, GivenValidFormerOclocNameWhenFormerOclocReturnsSuccessThenSuccessIsPropagatedAndCommandLineIsNotPrinted) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); Ocloc::oclocFormerLibName = "oclocFormer"; VariableBackup funcBackup{&NEO::OsLibrary::loadFunc, MockOsLibraryCustom::load}; @@ -1032,6 +1347,7 @@ TEST_F(OclocFallbackTests, GivenValidFormerOclocNameWhenFormerOclocReturnsSucces } TEST_F(OclocFallbackTests, GivenValidFormerOclocNameWhenFormerOclocReturnsErrorThenErrorIsPropagated) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); Ocloc::oclocFormerLibName = "oclocFormer"; VariableBackup funcBackup{&NEO::OsLibrary::loadFunc, MockOsLibraryCustom::load}; @@ -1063,6 +1379,8 @@ TEST_F(OclocFallbackTests, GivenValidFormerOclocNameWhenFormerOclocReturnsErrorT } TEST_F(OclocFallbackTests, GivenValidFormerOclocNameWhenFormerOclocReturnsOutputsThenOutputIsPropagated) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); + for (auto &expectedRetVal : {ocloc_error_t::OCLOC_SUCCESS, ocloc_error_t::OCLOC_OUT_OF_HOST_MEMORY, ocloc_error_t::OCLOC_BUILD_PROGRAM_FAILURE, @@ -1098,4 +1416,4 @@ TEST_F(OclocFallbackTests, GivenValidFormerOclocNameWhenFormerOclocReturnsOutput oclocFreeOutput(&numOutputs, &dataOutputs, &lenOutputs, &nameOutputs); } passOutputs = false; -} +} \ No newline at end of file diff --git a/opencl/test/unit_test/offline_compiler/ocloc_fatbinary_tests.cpp b/opencl/test/unit_test/offline_compiler/ocloc_fatbinary_tests.cpp index d0169f339b..49ed22432e 100644 --- a/opencl/test/unit_test/offline_compiler/ocloc_fatbinary_tests.cpp +++ b/opencl/test/unit_test/offline_compiler/ocloc_fatbinary_tests.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2024 Intel Corporation + * Copyright (C) 2020-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -20,6 +20,9 @@ #include "shared/source/helpers/product_config_helper.h" #include "shared/source/release_helper/release_helper.h" #include "shared/test/common/helpers/gtest_helpers.h" +#include "shared/test/common/helpers/stdout_capture.h" +#include "shared/test/common/helpers/variable_backup.h" +#include "shared/test/common/mocks/mock_io_functions.h" #include "environment.h" #include "mock/mock_argument_helper.h" @@ -27,6 +30,7 @@ #include "platforms.h" #include +#include #include extern Environment *gEnvironment; @@ -329,13 +333,14 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenClosedRangeTooExtensiveWhenProdu std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", target}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_NE(retVal, OCLOC_SUCCESS); resString << "Invalid range : " << acronymsString.str() << " - should be from:to or :to or from:\n"; resString << "Failed to parse target devices from : " << target << "\n"; @@ -373,72 +378,76 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenTwoTargetsOfProductsWhenFatBinar if (enabledProductsAcronyms.size() < 2) { GTEST_SKIP(); } - for (unsigned int product = 0; product < enabledProductsAcronyms.size() - 1; product++) { - auto acronym0 = enabledProductsAcronyms.at(product); - auto acronym1 = enabledProductsAcronyms.at(product + 1); - std::vector expected{acronym0, acronym1}; - std::string acronymsTarget = acronym0.str() + "," + acronym1.str(); - auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); - EXPECT_EQ(got, expected); + std::vector expected{}; + expected.insert(expected.end(), enabledProductsAcronyms.begin(), enabledProductsAcronyms.begin() + 2); - oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - std::stringstream resString; - std::vector argv = { - "ocloc", - "-file", - clFiles + "copybuffer.cl", - "-device", - acronymsTarget}; + std::string acronym0 = enabledProductsAcronyms.front().str(); + std::string acronym1 = (enabledProductsAcronyms.begin() + 1)->str(); - testing::internal::CaptureStdout(); - int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); - EXPECT_EQ(retVal, OCLOC_SUCCESS); + std::string acronymsTarget = acronym0 + "," + acronym1; + auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); + EXPECT_EQ(got, expected); - for (const auto &product : expected) { - resString << "Build succeeded for : " << product.str() + ".\n"; - } + oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); + std::stringstream resString; + std::vector argv = { + "ocloc", + "-file", + clCopybufferFilename.c_str(), + "-device", + acronymsTarget}; - EXPECT_STREQ(output.c_str(), resString.str().c_str()); + StdoutCapture capture; + capture.captureStdout(); + int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); + auto output = capture.getCapturedStdout(); + EXPECT_EQ(retVal, OCLOC_SUCCESS); + + for (const auto &product : expected) { + resString << "Build succeeded for : " << product.str() + ".\n"; } + + EXPECT_STREQ(output.c_str(), resString.str().c_str()); } TEST_F(OclocFatBinaryProductAcronymsTests, givenTwoVersionsOfProductConfigsWhenFatBinaryBuildIsInvokedThenSuccessIsReturned) { if (enabledProducts.size() < 2) { GTEST_SKIP(); } - for (unsigned int product = 0; product < enabledProducts.size() - 1; product++) { - auto config0 = enabledProducts.at(product).aotConfig; - auto config1 = enabledProducts.at(product + 1).aotConfig; - auto configStr0 = ProductConfigHelper::parseMajorMinorRevisionValue(config0); - auto configStr1 = ProductConfigHelper::parseMajorMinorRevisionValue(config1); - std::vector expected{configStr0, configStr1}; - std::string acronymsTarget = configStr0 + "," + configStr1; - auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); - EXPECT_EQ(got, expected); + auto config0 = enabledProducts.at(0).aotConfig; + auto config1 = enabledProducts.at(1).aotConfig; - oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - std::stringstream resString; - std::vector argv = { - "ocloc", - "-file", - clFiles + "copybuffer.cl", - "-device", - acronymsTarget}; + auto configStr0 = ProductConfigHelper::parseMajorMinorRevisionValue(config0); + auto configStr1 = ProductConfigHelper::parseMajorMinorRevisionValue(config1); - testing::internal::CaptureStdout(); - int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); - EXPECT_EQ(retVal, OCLOC_SUCCESS); + std::vector expected{configStr0, configStr1}; - for (const auto &product : expected) { - resString << "Build succeeded for : " << product.str() + ".\n"; - } + std::string acronymsTarget = configStr0 + "," + configStr1; + auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); + EXPECT_EQ(got, expected); - EXPECT_STREQ(output.c_str(), resString.str().c_str()); + oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); + std::stringstream resString; + std::vector argv = { + "ocloc", + "-file", + clCopybufferFilename.c_str(), + "-device", + acronymsTarget}; + + StdoutCapture capture; + capture.captureStdout(); + int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); + auto output = capture.getCapturedStdout(); + EXPECT_EQ(retVal, OCLOC_SUCCESS); + + for (const auto &product : expected) { + resString << "Build succeeded for : " << product.str() + ".\n"; } + + EXPECT_STREQ(output.c_str(), resString.str().c_str()); } TEST_F(OclocFatBinaryProductAcronymsTests, givenProductsAcronymsWithoutDashesWhenBuildFatBinaryThenSuccessIsReturned) { @@ -458,13 +467,14 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenProductsAcronymsWithoutDashesWhe std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", acronymsTarget}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_SUCCESS); for (const auto &product : expected) { @@ -478,40 +488,42 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenBinaryOutputNameOptionWhenBuildi if (enabledProductsAcronyms.size() < 2) { GTEST_SKIP(); } - for (unsigned int product = 0; product < enabledProductsAcronyms.size() - 1; product++) { - auto acronym0 = enabledProductsAcronyms.at(product); - auto acronym1 = enabledProductsAcronyms.at(product + 1); - std::vector expected{acronym0, acronym1}; - std::string acronymsTarget = acronym0.str() + "," + acronym1.str(); - auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); - EXPECT_EQ(got, expected); + std::vector expected{}; + expected.insert(expected.end(), enabledProductsAcronyms.begin(), enabledProductsAcronyms.begin() + 2); - oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - std::stringstream resString; - std::vector argv = { - "ocloc", - "-o", - "expected_output.bin", - "-file", - clFiles + "copybuffer.cl", - "-device", - acronymsTarget}; + std::string acronym0 = enabledProductsAcronyms.front().str(); + std::string acronym1 = (enabledProductsAcronyms.begin() + 1)->str(); - testing::internal::CaptureStdout(); - int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); - EXPECT_EQ(retVal, OCLOC_SUCCESS); + std::string acronymsTarget = acronym0 + "," + acronym1; + auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); + EXPECT_EQ(got, expected); - EXPECT_EQ(1u, NEO::virtualFileList.size()); - EXPECT_TRUE(NEO::virtualFileList.find("expected_output.bin") != NEO::virtualFileList.end()); + oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); + std::stringstream resString; + std::vector argv = { + "ocloc", + "-o", + "expected_output.bin", + "-file", + clCopybufferFilename.c_str(), + "-device", + acronymsTarget}; - for (const auto &product : expected) { - resString << "Build succeeded for : " << product.str() + ".\n"; - } + StdoutCapture capture; + capture.captureStdout(); + int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); + auto output = capture.getCapturedStdout(); + EXPECT_EQ(retVal, OCLOC_SUCCESS); - EXPECT_STREQ(output.c_str(), resString.str().c_str()); + EXPECT_EQ(4u, NEO::virtualFileList.size()); + EXPECT_TRUE(NEO::virtualFileList.find("expected_output.bin") != NEO::virtualFileList.end()); + + for (const auto &product : expected) { + resString << "Build succeeded for : " << product.str() + ".\n"; } + + EXPECT_STREQ(output.c_str(), resString.str().c_str()); } TEST_F(OclocFatBinaryProductAcronymsTests, givenBinaryOutputDirOptionWhenBuildingThenCorrectFileIsCreated) { @@ -532,19 +544,20 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenBinaryOutputDirOptionWhenBuildin std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-out_dir", "../expected_output_directory", "-device", acronymsTarget}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_SUCCESS); - const std::string expectedFatbinaryFileName = "../expected_output_directory/copybuffer.ar"; - EXPECT_EQ(1u, NEO::virtualFileList.size()); + const std::string expectedFatbinaryFileName = "../expected_output_directory/some_kernel.ar"; + EXPECT_EQ(4u, NEO::virtualFileList.size()); EXPECT_TRUE(NEO::virtualFileList.find(expectedFatbinaryFileName) != NEO::virtualFileList.end()); for (const auto &product : expected) { @@ -559,7 +572,7 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenBinaryOutputDirOptionWhenBuildin std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-out_dir", "../expected_output_directory", "-output", @@ -567,13 +580,14 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenBinaryOutputDirOptionWhenBuildin "-device", acronymsTarget}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_SUCCESS); const std::string expectedFatbinaryFileName = "../expected_output_directory/expected_filename"; - EXPECT_EQ(2u, NEO::virtualFileList.size()); + EXPECT_EQ(5u, NEO::virtualFileList.size()); EXPECT_TRUE(NEO::virtualFileList.find(expectedFatbinaryFileName) != NEO::virtualFileList.end()); for (const auto &product : expected) { @@ -650,129 +664,123 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenFamiliesAcronymsWithoutDashesWhe } TEST_F(OclocFatBinaryProductAcronymsTests, givenTwoTargetsOfReleasesWhenFatBinaryBuildIsInvokedThenSuccessIsReturned) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); if (enabledReleasesAcronyms.size() < 2) { GTEST_SKIP(); } - for (unsigned int product = 0; product < enabledReleasesAcronyms.size() - 1; product++) { - auto acronym0 = enabledReleasesAcronyms.at(product); - auto acronym1 = enabledReleasesAcronyms.at(product + 1); - std::vector expected{}; + std::vector expected{}; - auto release0 = oclocArgHelperWithoutInput->productConfigHelper->getReleaseFromDeviceName(acronym0.str()); - auto release1 = oclocArgHelperWithoutInput->productConfigHelper->getReleaseFromDeviceName(acronym1.str()); - getProductsAcronymsForTarget(expected, release0, oclocArgHelperWithoutInput.get()); - getProductsAcronymsForTarget(expected, release1, oclocArgHelperWithoutInput.get()); + std::string acronym0 = enabledReleasesAcronyms.front().str(); + std::string acronym1 = (enabledReleasesAcronyms.begin() + 1)->str(); - std::string acronymsTarget = acronym0.str() + "," + acronym1.str(); - auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); - EXPECT_EQ(got, expected); + auto release0 = oclocArgHelperWithoutInput->productConfigHelper->getReleaseFromDeviceName(acronym0); + auto release1 = oclocArgHelperWithoutInput->productConfigHelper->getReleaseFromDeviceName(acronym1); + getProductsAcronymsForTarget(expected, release0, oclocArgHelperWithoutInput.get()); + getProductsAcronymsForTarget(expected, release1, oclocArgHelperWithoutInput.get()); - oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - std::stringstream resString; - std::vector argv = { - "ocloc", - "-file", - clFiles + "copybuffer.cl", - "-device", - acronymsTarget}; + std::string acronymsTarget = acronym0 + "," + acronym1; + auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); + EXPECT_EQ(got, expected); - testing::internal::CaptureStdout(); - int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); - EXPECT_EQ(retVal, OCLOC_SUCCESS); + oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); + std::stringstream resString; + std::vector argv = { + "ocloc", + "-file", + clCopybufferFilename.c_str(), + "-device", + acronymsTarget}; - for (const auto &product : expected) { - resString << "Build succeeded for : " << product.str() + ".\n"; - } + StdoutCapture capture; + capture.captureStdout(); + int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); + auto output = capture.getCapturedStdout(); + EXPECT_EQ(retVal, OCLOC_SUCCESS); - EXPECT_STREQ(output.c_str(), resString.str().c_str()); + for (const auto &product : expected) { + resString << "Build succeeded for : " << product.str() + ".\n"; } + + EXPECT_STREQ(output.c_str(), resString.str().c_str()); } TEST_F(OclocFatBinaryProductAcronymsTests, givenTwoTargetsOfFamiliesWhenFatBinaryBuildIsInvokedThenSuccessIsReturned) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); if (enabledFamiliesAcronyms.size() < 2) { GTEST_SKIP(); } - for (unsigned int product = 0; product < enabledFamiliesAcronyms.size() - 1; product++) { - auto acronym0 = enabledFamiliesAcronyms.at(product); - auto acronym1 = enabledFamiliesAcronyms.at(product + 1); - std::vector expected{}; + std::string acronym0 = enabledFamiliesAcronyms.front().str(); + std::string acronym1 = (enabledFamiliesAcronyms.begin() + 1)->str(); - auto family0 = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(acronym0.str()); - auto family1 = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(acronym1.str()); - getProductsAcronymsForTarget(expected, family0, oclocArgHelperWithoutInput.get()); - getProductsAcronymsForTarget(expected, family1, oclocArgHelperWithoutInput.get()); + std::vector expected{}; - std::string acronymsTarget = acronym0.str() + "," + acronym1.str(); - auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); - EXPECT_EQ(got, expected); + auto family0 = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(acronym0); + auto family1 = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(acronym1); + getProductsAcronymsForTarget(expected, family0, oclocArgHelperWithoutInput.get()); + getProductsAcronymsForTarget(expected, family1, oclocArgHelperWithoutInput.get()); - oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - std::stringstream resString; - std::vector argv = { - "ocloc", - "-file", - clFiles + "copybuffer.cl", - "-device", - acronymsTarget}; + std::string acronymsTarget = acronym0 + "," + acronym1; + auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); + EXPECT_EQ(got, expected); - testing::internal::CaptureStdout(); - int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); - EXPECT_EQ(retVal, OCLOC_SUCCESS); + oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); + std::stringstream resString; + std::vector argv = { + "ocloc", + "-file", + clCopybufferFilename.c_str(), + "-device", + acronymsTarget}; - for (const auto &product : expected) { - resString << "Build succeeded for : " << product.str() + ".\n"; - } + StdoutCapture capture; + capture.captureStdout(); + int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); + auto output = capture.getCapturedStdout(); + EXPECT_EQ(retVal, OCLOC_SUCCESS); - EXPECT_STREQ(output.c_str(), resString.str().c_str()); + for (const auto &product : expected) { + resString << "Build succeeded for : " << product.str() + ".\n"; } + + EXPECT_STREQ(output.c_str(), resString.str().c_str()); } TEST_F(OclocFatBinaryProductAcronymsTests, givenProductsClosedRangeWhenFatBinaryBuildIsInvokedThenSuccessIsReturned) { if (enabledProductsAcronyms.size() < 3) { GTEST_SKIP(); } - for (unsigned int product = 0; product < enabledProductsAcronyms.size() - 1; product++) { - if (product == enabledProductsAcronyms.size() / 2) { - continue; - } - std::vector expected{}; - auto acronymFrom = enabledProductsAcronyms.at(product); - auto acronymTo = enabledProductsAcronyms.at(enabledProductsAcronyms.size() / 2); - auto prodFromIt = std::find(enabledProductsAcronyms.begin(), enabledProductsAcronyms.end(), acronymFrom); - auto prodToIt = std::find(enabledProductsAcronyms.begin(), enabledProductsAcronyms.end(), acronymTo); - if (prodFromIt > prodToIt) { - std::swap(prodFromIt, prodToIt); - } - expected.insert(expected.end(), prodFromIt, ++prodToIt); + std::vector expected{}; + expected.insert(expected.end(), enabledProductsAcronyms.begin(), enabledProductsAcronyms.begin() + 4); - std::string acronymsTarget = acronymFrom.str() + ":" + acronymTo.str(); - auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); - EXPECT_EQ(got, expected); + std::string acronymFrom = enabledProductsAcronyms.front().str(); + std::string acronymsTo = (enabledProductsAcronyms.begin() + 3)->str(); - oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - std::stringstream resString; - std::vector argv = { - "ocloc", - "-file", - clFiles + "copybuffer.cl", - "-device", - acronymsTarget}; + std::string acronymsTarget = acronymFrom + ":" + acronymsTo; + auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); + EXPECT_EQ(got, expected); - testing::internal::CaptureStdout(); - int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); - EXPECT_EQ(retVal, OCLOC_SUCCESS); + oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); + std::stringstream resString; + std::vector argv = { + "ocloc", + "-file", + clCopybufferFilename.c_str(), + "-device", + acronymsTarget}; - for (const auto &product : expected) { - resString << "Build succeeded for : " << product.str() + ".\n"; - } + StdoutCapture capture; + capture.captureStdout(); + int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); + auto output = capture.getCapturedStdout(); + EXPECT_EQ(retVal, OCLOC_SUCCESS); - EXPECT_STREQ(output.c_str(), resString.str().c_str()); + for (const auto &product : expected) { + resString << "Build succeeded for : " << product.str() + ".\n"; } + + EXPECT_STREQ(output.c_str(), resString.str().c_str()); } TEST_F(OclocFatBinaryProductAcronymsTests, givenProductsClosedRangeWithoutDashesWhenFatBinaryBuildIsInvokedThenSuccessIsReturned) { @@ -797,13 +805,14 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenProductsClosedRangeWithoutDashes std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", acronymsTarget}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_SUCCESS); for (const auto &product : expected) { @@ -886,13 +895,14 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenClosedRangeWithOneFamilyBeingGen std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", acronymsTarget}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_SUCCESS); for (const auto &product : expected) { @@ -907,94 +917,93 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenFamiliesClosedRangeWhenFatBinary if (enabledFamiliesAcronyms.size() < 3) { GTEST_SKIP(); } - for (unsigned int family = 0; family < enabledFamiliesAcronyms.size() - 1; family++) { - if (family == enabledFamiliesAcronyms.size() / 2) { - continue; - } - std::vector expected{}; - auto acronymFrom = enabledFamiliesAcronyms.at(family); - auto acronymTo = enabledFamiliesAcronyms.at(enabledFamiliesAcronyms.size() / 2); - auto familyFromIt = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(acronymFrom.str()); - auto familyToIt = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(acronymTo.str()); + std::vector expected{}; + auto acronymFrom = enabledFamiliesAcronyms.at(0); + auto acronymTo = enabledFamiliesAcronyms.at(2); - if (familyFromIt > familyToIt) { - std::swap(familyFromIt, familyToIt); - } - while (familyFromIt <= familyToIt) { - getProductsAcronymsForTarget(expected, familyFromIt, oclocArgHelperWithoutInput.get()); - familyFromIt = static_cast(static_cast(familyFromIt) + 1); - } + auto familyFromIt = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(acronymFrom.str()); + auto familyToIt = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(acronymTo.str()); - std::string acronymsTarget = acronymFrom.str() + ":" + acronymTo.str(); - auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); - EXPECT_EQ(got, expected); - - oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - std::stringstream resString; - std::vector argv = { - "ocloc", - "-file", - clFiles + "copybuffer.cl", - "-device", - acronymsTarget}; - - testing::internal::CaptureStdout(); - int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); - EXPECT_EQ(retVal, OCLOC_SUCCESS); - - for (const auto &product : expected) { - resString << "Build succeeded for : " << product.str() + ".\n"; - } - - EXPECT_STREQ(output.c_str(), resString.str().c_str()); + if (familyFromIt > familyToIt) { + std::swap(familyFromIt, familyToIt); } + while (familyFromIt <= familyToIt) { + getProductsAcronymsForTarget(expected, familyFromIt, oclocArgHelperWithoutInput.get()); + familyFromIt = static_cast(static_cast(familyFromIt) + 1); + } + + std::string acronymsTarget = acronymFrom.str() + ":" + acronymTo.str(); + auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); + EXPECT_EQ(got, expected); + + oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); + std::stringstream resString; + std::vector argv = { + "ocloc", + "-file", + clCopybufferFilename.c_str(), + "-device", + acronymsTarget}; + + StdoutCapture capture; + capture.captureStdout(); + int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); + auto output = capture.getCapturedStdout(); + EXPECT_EQ(retVal, OCLOC_SUCCESS); + + for (const auto &product : expected) { + resString << "Build succeeded for : " << product.str() + ".\n"; + } + + EXPECT_STREQ(output.c_str(), resString.str().c_str()); } TEST_F(OclocFatBinaryProductAcronymsTests, givenOpenRangeFromProductWhenFatBinaryBuildIsInvokedThenSuccessIsReturned) { if (enabledProductsAcronyms.size() < 2) { GTEST_SKIP(); } - for (auto acronymIt = enabledProductsAcronyms.begin(); acronymIt != enabledProductsAcronyms.end(); ++acronymIt) { - std::vector expected{}; - expected.insert(expected.end(), acronymIt, enabledProductsAcronyms.end()); - std::string acronymsTarget = (*acronymIt).str() + ":"; - auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); - EXPECT_EQ(got, expected); + std::vector expected{}; + expected.insert(expected.end(), enabledProductsAcronyms.end() - 2, enabledProductsAcronyms.end()); - oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - std::stringstream resString; - std::vector argv = { - "ocloc", - "-file", - clFiles + "copybuffer.cl", - "-device", - acronymsTarget}; + std::string acronymsTarget = (enabledProductsAcronyms.end() - 2)->str() + ":"; + auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); + EXPECT_EQ(got, expected); - testing::internal::CaptureStdout(); - int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); - EXPECT_EQ(retVal, OCLOC_SUCCESS); + oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); + std::stringstream resString; + std::vector argv = { + "ocloc", + "-file", + clCopybufferFilename.c_str(), + "-device", + acronymsTarget}; - for (const auto &product : expected) { - resString << "Build succeeded for : " << product.str() + ".\n"; - } + StdoutCapture capture; + capture.captureStdout(); + int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); + auto output = capture.getCapturedStdout(); + EXPECT_EQ(retVal, OCLOC_SUCCESS); - EXPECT_STREQ(output.c_str(), resString.str().c_str()); + for (const auto &product : expected) { + resString << "Build succeeded for : " << product.str() + ".\n"; } + + EXPECT_STREQ(output.c_str(), resString.str().c_str()); } TEST_F(OclocFatBinaryProductAcronymsTests, givenOpenRangeFromProductWithoutDashesWhenFatBinaryBuildIsInvokedThenSuccessIsReturned) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); auto acronyms = prepareProductsWithoutDashes(oclocArgHelperWithoutInput.get()); - if (acronyms.empty()) { + if (acronyms.size() < 2) { GTEST_SKIP(); } - std::string acronymsTarget = acronyms[0] + ":"; + std::string acronym = acronyms[acronyms.size() - 2]; + std::string acronymsTarget = acronym + ":"; std::vector expected{}; - auto acronymIt = std::find_if(enabledProductsAcronyms.begin(), enabledProductsAcronyms.end(), ProductConfigHelper::findAcronymWithoutDash(acronyms[0])); + auto acronymIt = std::find_if(enabledProductsAcronyms.begin(), enabledProductsAcronyms.end(), ProductConfigHelper::findAcronymWithoutDash(acronym)); expected.insert(expected.end(), acronymIt, enabledProductsAcronyms.end()); auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); @@ -1005,13 +1014,14 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenOpenRangeFromProductWithoutDashe std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", acronymsTarget}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(retVal, OCLOC_SUCCESS); for (const auto &product : expected) { @@ -1022,37 +1032,37 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenOpenRangeFromProductWithoutDashe } TEST_F(OclocFatBinaryProductAcronymsTests, givenOpenRangeToProductWhenFatBinaryBuildIsInvokedThenSuccessIsReturned) { - if (enabledProductsAcronyms.size() < 2) { + if (enabledProductsAcronyms.size() < 3) { GTEST_SKIP(); } - for (auto acronymIt = enabledProductsAcronyms.begin(); acronymIt != enabledProductsAcronyms.end(); ++acronymIt) { - std::vector expected{}; - expected.insert(expected.end(), enabledProductsAcronyms.begin(), acronymIt + 1); - std::string acronymsTarget = ":" + (*acronymIt).str(); - auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); - EXPECT_EQ(got, expected); + std::vector expected{}; + expected.insert(expected.end(), enabledProductsAcronyms.begin(), enabledProductsAcronyms.begin() + 4); - oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - std::stringstream resString; - std::vector argv = { - "ocloc", - "-file", - clFiles + "copybuffer.cl", - "-device", - acronymsTarget}; + std::string acronymsTarget = ":" + (enabledProductsAcronyms.begin() + 3)->str(); + auto got = NEO::getTargetProductsForFatbinary(acronymsTarget, oclocArgHelperWithoutInput.get()); + EXPECT_EQ(got, expected); - testing::internal::CaptureStdout(); - int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); - EXPECT_EQ(retVal, OCLOC_SUCCESS); + oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); + std::stringstream resString; + std::vector argv = { + "ocloc", + "-file", + clCopybufferFilename.c_str(), + "-device", + acronymsTarget}; - for (const auto &product : expected) { - resString << "Build succeeded for : " << product.str() + ".\n"; - } + StdoutCapture capture; + capture.captureStdout(); + int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); + auto output = capture.getCapturedStdout(); + EXPECT_EQ(retVal, OCLOC_SUCCESS); - EXPECT_STREQ(output.c_str(), resString.str().c_str()); + for (const auto &product : expected) { + resString << "Build succeeded for : " << product.str() + ".\n"; } + + EXPECT_STREQ(output.c_str(), resString.str().c_str()); } TEST_F(OclocFatBinaryProductAcronymsTests, givenOpenRangeFromReleaseWithoutDashesWhenGetProductsForFatBinaryThenCorrectAcronymsAreReturned) { @@ -1160,42 +1170,42 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenOpenRangeFromReleaseWhenFatBinar GTEST_SKIP(); } - for (const auto &release : enabledReleasesAcronyms) { - std::vector expected{}; + const auto release = enabledReleasesAcronyms[enabledReleasesAcronyms.size() - 3].str(); + std::vector expected{}; - auto releaseFromId = oclocArgHelperWithoutInput->productConfigHelper->getReleaseFromDeviceName(release.str()); - auto releaseToId = AOT::RELEASE_MAX; - while (releaseFromId < releaseToId) { - getProductsAcronymsForTarget(expected, releaseFromId, oclocArgHelperWithoutInput.get()); - releaseFromId = static_cast(static_cast(releaseFromId) + 1); - } - if (expected.empty()) { - GTEST_SKIP(); - } - std::string releasesTarget = release.str() + ":"; - auto got = NEO::getTargetProductsForFatbinary(releasesTarget, oclocArgHelperWithoutInput.get()); - EXPECT_EQ(got, expected); - - oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - std::stringstream resString; - std::vector argv = { - "ocloc", - "-file", - clFiles + "copybuffer.cl", - "-device", - releasesTarget}; - - testing::internal::CaptureStdout(); - int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); - EXPECT_EQ(retVal, OCLOC_SUCCESS); - - for (const auto &product : expected) { - resString << "Build succeeded for : " << product.str() + ".\n"; - } - - EXPECT_STREQ(output.c_str(), resString.str().c_str()); + auto releaseFromId = oclocArgHelperWithoutInput->productConfigHelper->getReleaseFromDeviceName(release); + auto releaseToId = AOT::RELEASE_MAX; + while (releaseFromId < releaseToId) { + getProductsAcronymsForTarget(expected, releaseFromId, oclocArgHelperWithoutInput.get()); + releaseFromId = static_cast(static_cast(releaseFromId) + 1); } + if (expected.empty()) { + GTEST_SKIP(); + } + std::string releasesTarget = release + ":"; + auto got = NEO::getTargetProductsForFatbinary(releasesTarget, oclocArgHelperWithoutInput.get()); + EXPECT_EQ(got, expected); + + oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); + std::stringstream resString; + std::vector argv = { + "ocloc", + "-file", + clCopybufferFilename.c_str(), + "-device", + releasesTarget}; + + StdoutCapture capture; + capture.captureStdout(); + int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); + auto output = capture.getCapturedStdout(); + EXPECT_EQ(retVal, OCLOC_SUCCESS); + + for (const auto &product : expected) { + resString << "Build succeeded for : " << product.str() + ".\n"; + } + + EXPECT_STREQ(output.c_str(), resString.str().c_str()); } TEST_F(OclocFatBinaryProductAcronymsTests, givenDeviceOptionsForNotCompiledDeviceAndListOfProductsWhenFatBinaryBuildIsInvokedThenWarningIsPrinted) { @@ -1211,16 +1221,17 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenDeviceOptionsForNotCompiledDevic std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", products.str().c_str(), "-device_options", enabledProductsAcronyms[2].str(), "deviceOptions"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); [[maybe_unused]] int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); std::stringstream expectedErrorMessage; expectedErrorMessage << "Warning! -device_options set for non-compiled device: " + enabledProductsAcronyms[2].str() + "\n"; @@ -1232,6 +1243,21 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenDeviceOptionsForCompiledDeviceAn GTEST_SKIP(); } + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + std::stringstream products; products << enabledProductsAcronyms[0].str() + "," + enabledProductsAcronyms[1].str(); @@ -1240,16 +1266,17 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenDeviceOptionsForCompiledDeviceAn std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", products.str().c_str(), "-device_options", enabledProductsAcronyms[0].str(), "deviceOptions"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); [[maybe_unused]] int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); std::stringstream errorMessage1, errorMessage2; errorMessage1 << "Warning! -device_options set for non-compiled device: " << enabledProductsAcronyms[0].str() << "\n"; @@ -1264,6 +1291,21 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenDeviceOptionsForMultipleDevicesS GTEST_SKIP(); } + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + std::stringstream products, productsForDeviceOptions; products << enabledProductsAcronyms[0].str() << "," << enabledProductsAcronyms[1].str() << "," @@ -1277,16 +1319,17 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenDeviceOptionsForMultipleDevicesS std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", products.str().c_str(), "-device_options", productsForDeviceOptions.str().c_str(), "deviceOptions"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); [[maybe_unused]] int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); std::stringstream expectedErrorMessage; expectedErrorMessage << "Warning! -device_options set for non-compiled device"; @@ -1298,43 +1341,43 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenOpenRangeToReleaseWhenFatBinaryB GTEST_SKIP(); } - for (const auto &release : enabledReleasesAcronyms) { - std::vector expected{}; + const auto release = (enabledReleasesAcronyms.end() - 3)->str(); + std::vector expected{}; - auto releaseFromId = static_cast(static_cast(AOT::UNKNOWN_RELEASE) + 1); - auto releaseToId = oclocArgHelperWithoutInput->productConfigHelper->getReleaseFromDeviceName(release.str()); + auto releaseFromId = static_cast(static_cast(AOT::UNKNOWN_RELEASE) + 1); + auto releaseToId = oclocArgHelperWithoutInput->productConfigHelper->getReleaseFromDeviceName(release); - while (releaseFromId <= releaseToId) { - getProductsAcronymsForTarget(expected, releaseFromId, oclocArgHelperWithoutInput.get()); - releaseFromId = static_cast(static_cast(releaseFromId) + 1); - } - if (expected.empty()) { - GTEST_SKIP(); - } - std::string releasesTarget = ":" + release.str(); - auto got = NEO::getTargetProductsForFatbinary(releasesTarget, oclocArgHelperWithoutInput.get()); - EXPECT_EQ(got, expected); - - oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - std::stringstream resString; - std::vector argv = { - "ocloc", - "-file", - clFiles + "copybuffer.cl", - "-device", - releasesTarget}; - - testing::internal::CaptureStdout(); - int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); - EXPECT_EQ(retVal, OCLOC_SUCCESS); - - for (const auto &product : expected) { - resString << "Build succeeded for : " << product.str() + ".\n"; - } - - EXPECT_STREQ(output.c_str(), resString.str().c_str()); + while (releaseFromId <= releaseToId) { + getProductsAcronymsForTarget(expected, releaseFromId, oclocArgHelperWithoutInput.get()); + releaseFromId = static_cast(static_cast(releaseFromId) + 1); } + if (expected.empty()) { + GTEST_SKIP(); + } + std::string releasesTarget = ":" + release; + auto got = NEO::getTargetProductsForFatbinary(releasesTarget, oclocArgHelperWithoutInput.get()); + EXPECT_EQ(got, expected); + + oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); + std::stringstream resString; + std::vector argv = { + "ocloc", + "-file", + clCopybufferFilename.c_str(), + "-device", + releasesTarget}; + + StdoutCapture capture; + capture.captureStdout(); + int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); + auto output = capture.getCapturedStdout(); + EXPECT_EQ(retVal, OCLOC_SUCCESS); + + for (const auto &product : expected) { + resString << "Build succeeded for : " << product.str() + ".\n"; + } + + EXPECT_STREQ(output.c_str(), resString.str().c_str()); } TEST_F(OclocFatBinaryProductAcronymsTests, givenReleaseWhichHasNoDeviceAcronymWhenGetTargetProductsForFatbinaryThenCorrectResultIsReturned) { @@ -1487,40 +1530,40 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenOpenRangeFromFamilyWhenFatBinary GTEST_SKIP(); } - for (const auto &family : enabledFamiliesAcronyms) { - std::vector expected{}; + const auto family = (enabledFamiliesAcronyms.end() - 3)->str(); + std::vector expected{}; - auto familyFromId = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(family.str()); - auto familyToId = AOT::FAMILY_MAX; - while (familyFromId < familyToId) { - getProductsAcronymsForTarget(expected, familyFromId, oclocArgHelperWithoutInput.get()); - familyFromId = static_cast(static_cast(familyFromId) + 1); - } - - std::string familiesTarget = family.str() + ":"; - auto got = NEO::getTargetProductsForFatbinary(familiesTarget, oclocArgHelperWithoutInput.get()); - EXPECT_EQ(got, expected); - - oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - std::stringstream resString; - std::vector argv = { - "ocloc", - "-file", - clFiles + "copybuffer.cl", - "-device", - familiesTarget}; - - testing::internal::CaptureStdout(); - int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); - EXPECT_EQ(retVal, OCLOC_SUCCESS); - - for (const auto &product : expected) { - resString << "Build succeeded for : " << product.str() + ".\n"; - } - - EXPECT_STREQ(output.c_str(), resString.str().c_str()); + auto familyFromId = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(family); + auto familyToId = AOT::FAMILY_MAX; + while (familyFromId < familyToId) { + getProductsAcronymsForTarget(expected, familyFromId, oclocArgHelperWithoutInput.get()); + familyFromId = static_cast(static_cast(familyFromId) + 1); } + + std::string familiesTarget = family + ":"; + auto got = NEO::getTargetProductsForFatbinary(familiesTarget, oclocArgHelperWithoutInput.get()); + EXPECT_EQ(got, expected); + + oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); + std::stringstream resString; + std::vector argv = { + "ocloc", + "-file", + clCopybufferFilename.c_str(), + "-device", + familiesTarget}; + + StdoutCapture capture; + capture.captureStdout(); + int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); + auto output = capture.getCapturedStdout(); + EXPECT_EQ(retVal, OCLOC_SUCCESS); + + for (const auto &product : expected) { + resString << "Build succeeded for : " << product.str() + ".\n"; + } + + EXPECT_STREQ(output.c_str(), resString.str().c_str()); } TEST_F(OclocFatBinaryProductAcronymsTests, givenOpenRangeToFamilyWhenFatBinaryBuildIsInvokedThenSuccessIsReturned) { @@ -1528,41 +1571,41 @@ TEST_F(OclocFatBinaryProductAcronymsTests, givenOpenRangeToFamilyWhenFatBinaryBu GTEST_SKIP(); } - for (const auto &family : enabledFamiliesAcronyms) { - std::vector expected{}; + const auto &family = enabledFamiliesAcronyms.at(2); + std::vector expected{}; - auto familyFromId = static_cast(static_cast(AOT::UNKNOWN_FAMILY) + 1); - auto familyToId = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(family.str()); + auto familyFromId = static_cast(static_cast(AOT::UNKNOWN_FAMILY) + 1); + auto familyToId = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(family.str()); - while (familyFromId <= familyToId && familyFromId < AOT::FAMILY_MAX) { - getProductsAcronymsForTarget(expected, familyFromId, oclocArgHelperWithoutInput.get()); - familyFromId = static_cast(static_cast(familyFromId) + 1); - } - - std::string familiesTarget = ":" + family.str(); - auto got = NEO::getTargetProductsForFatbinary(familiesTarget, oclocArgHelperWithoutInput.get()); - EXPECT_EQ(got, expected); - - oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - std::stringstream resString; - std::vector argv = { - "ocloc", - "-file", - clFiles + "copybuffer.cl", - "-device", - familiesTarget}; - - testing::internal::CaptureStdout(); - int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); - EXPECT_EQ(retVal, OCLOC_SUCCESS); - - for (const auto &product : expected) { - resString << "Build succeeded for : " << product.str() + ".\n"; - } - - EXPECT_STREQ(output.c_str(), resString.str().c_str()); + while (familyFromId <= familyToId && familyFromId < AOT::FAMILY_MAX) { + getProductsAcronymsForTarget(expected, familyFromId, oclocArgHelperWithoutInput.get()); + familyFromId = static_cast(static_cast(familyFromId) + 1); } + + std::string familiesTarget = ":" + family.str(); + auto got = NEO::getTargetProductsForFatbinary(familiesTarget, oclocArgHelperWithoutInput.get()); + EXPECT_EQ(got, expected); + + oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); + std::stringstream resString; + std::vector argv = { + "ocloc", + "-file", + clCopybufferFilename.c_str(), + "-device", + familiesTarget}; + + StdoutCapture capture; + capture.captureStdout(); + int retVal = buildFatBinary(argv, oclocArgHelperWithoutInput.get()); + auto output = capture.getCapturedStdout(); + EXPECT_EQ(retVal, OCLOC_SUCCESS); + + for (const auto &product : expected) { + resString << "Build succeeded for : " << product.str() + ".\n"; + } + + EXPECT_STREQ(output.c_str(), resString.str().c_str()); } TEST_F(OclocFatBinaryTest, givenSpirvInputWhenFatBinaryIsRequestedThenArchiveContainsOptions) { @@ -1571,6 +1614,21 @@ TEST_F(OclocFatBinaryTest, givenSpirvInputWhenFatBinaryIsRequestedThenArchiveCon GTEST_SKIP(); } + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + char data[] = {1, 2, 3, 4, 5, 6, 7, 8}; MockCompilerDebugVars igcDebugVars(gEnvironment->igcDebugVars); igcDebugVars.binaryToReturn = data; @@ -1685,9 +1743,10 @@ TEST_F(OclocFatBinaryTest, givenDeviceFlagWithoutConsecutiveArgumentWhenBuilding "ocloc", "-device"}; - ::testing::internal::CaptureStdout(); + ::StdoutCapture capture; + capture.captureStdout(); const auto result = buildFatBinary(args, &mockArgHelper); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, result); @@ -1709,9 +1768,10 @@ TEST_F(OclocFatBinaryTest, givenFlagsWhichRequireMoreArgsWithoutThemWhenBuilding devices, flag}; - ::testing::internal::CaptureStdout(); + ::StdoutCapture capture; + capture.captureStdout(); const auto result = buildFatBinary(args, &mockArgHelper); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, result); @@ -1878,9 +1938,10 @@ TEST_F(OclocFatBinaryTest, givenEmptyFileWhenAppendingGenericIrThenInvalidFileIs mockArgHelperFilesMap[emptyFile] = ""; mockArgHelper.shouldLoadDataFromFileReturnZeroSize = true; - ::testing::internal::CaptureStdout(); + ::StdoutCapture capture; + capture.captureStdout(); const auto errorCode{appendGenericIr(ar, emptyFile, &mockArgHelper, dummyOptions)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_FILE, errorCode); EXPECT_EQ("Error! Couldn't read input file!\n", output); @@ -1892,9 +1953,10 @@ TEST_F(OclocFatBinaryTest, givenInvalidIrFileWhenAppendingGenericIrThenInvalidFi std::string dummyOptions{"-cl-opt-disable "}; mockArgHelperFilesMap[dummyFile] = "This is not IR!"; - ::testing::internal::CaptureStdout(); + ::StdoutCapture capture; + capture.captureStdout(); const auto errorCode{appendGenericIr(ar, dummyFile, &mockArgHelper, dummyOptions)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_FILE, errorCode); @@ -1903,11 +1965,11 @@ TEST_F(OclocFatBinaryTest, givenInvalidIrFileWhenAppendingGenericIrThenInvalidFi EXPECT_EQ(expectedErrorMessage, output); } -TEST(OclocFatBinaryHelpersTest, givenPreviousCompilationErrorWhenBuildingFatbinaryForTargetThenNothingIsDoneAndErrorIsReturned) { +TEST_F(OclocTest, givenPreviousCompilationErrorWhenBuildingFatbinaryForTargetThenNothingIsDoneAndErrorIsReturned) { const std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -1932,11 +1994,11 @@ TEST(OclocFatBinaryHelpersTest, givenPreviousCompilationErrorWhenBuildingFatbina EXPECT_EQ(0, mockOfflineCompiler.buildCalledCount); } -TEST(OclocFatBinaryHelpersTest, givenPreviousCompilationSuccessAndFailingBuildWhenBuildingFatbinaryForTargetThenCompilationIsInvokedAndErrorLogIsPrinted) { +TEST_F(OclocTest, givenPreviousCompilationSuccessAndFailingBuildWhenBuildingFatbinaryForTargetThenCompilationIsInvokedAndErrorLogIsPrinted) { const std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -1950,10 +2012,11 @@ TEST(OclocFatBinaryHelpersTest, givenPreviousCompilationSuccessAndFailingBuildWh const auto mockArgHelper = mockOfflineCompiler.uniqueHelper.get(); const auto deviceConfig = getDeviceConfig(mockOfflineCompiler, mockArgHelper); - ::testing::internal::CaptureStdout(); + ::StdoutCapture capture; + capture.captureStdout(); const int previousReturnValue{OCLOC_SUCCESS}; const auto buildResult = buildFatBinaryForTarget(previousReturnValue, argv, pointerSize, ar, &mockOfflineCompiler, mockArgHelper, deviceConfig); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_FILE, buildResult); EXPECT_EQ(1, mockOfflineCompiler.buildCalledCount); @@ -1971,13 +2034,13 @@ TEST(OclocFatBinaryHelpersTest, givenPreviousCompilationSuccessAndFailingBuildWh EXPECT_EQ(expectedOutput, output); } -TEST(OclocFatBinaryHelpersTest, givenNonEmptyBuildLogWhenBuildingFatbinaryForTargetThenBuildLogIsPrinted) { +TEST_F(OclocTest, givenNonEmptyBuildLogWhenBuildingFatbinaryForTargetThenBuildLogIsPrinted) { using namespace std::string_literals; const std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -1996,10 +2059,11 @@ TEST(OclocFatBinaryHelpersTest, givenNonEmptyBuildLogWhenBuildingFatbinaryForTar const auto mockArgHelper = mockOfflineCompiler.uniqueHelper.get(); const auto deviceConfig = getDeviceConfig(mockOfflineCompiler, mockArgHelper); - ::testing::internal::CaptureStdout(); + ::StdoutCapture capture; + capture.captureStdout(); const int previousReturnValue{OCLOC_SUCCESS}; const auto buildResult = buildFatBinaryForTarget(previousReturnValue, argv, pointerSize, ar, &mockOfflineCompiler, mockArgHelper, deviceConfig); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_SUCCESS, buildResult); EXPECT_EQ(1, mockOfflineCompiler.buildCalledCount); @@ -2008,14 +2072,15 @@ TEST(OclocFatBinaryHelpersTest, givenNonEmptyBuildLogWhenBuildingFatbinaryForTar EXPECT_EQ(expectedOutput, output); } -TEST(OclocFatBinaryHelpersTest, givenNonEmptyBuildLogWhenBuildingFatbinaryForTargetThenBuildLogIsNotPrinted) { - ::testing::internal::CaptureStdout(); +TEST_F(OclocTest, givenNonEmptyBuildLogWhenBuildingFatbinaryForTargetThenBuildLogIsNotPrinted) { + ::StdoutCapture capture; + capture.captureStdout(); const std::vector argv = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -2036,25 +2101,26 @@ TEST(OclocFatBinaryHelpersTest, givenNonEmptyBuildLogWhenBuildingFatbinaryForTar const int previousReturnValue{OCLOC_SUCCESS}; buildFatBinaryForTarget(previousReturnValue, argv, pointerSize, ar, &mockOfflineCompiler, mockArgHelper, deviceConfig); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_TRUE(output.empty()) << output; } -TEST(OclocFatBinaryHelpersTest, givenListOfDeprecatedAcronymsThenUseThemAsIs) { +TEST_F(OclocTest, givenListOfDeprecatedAcronymsThenUseThemAsIs) { ProductConfigHelper productConfigHelper; auto allDeperecatedAcronyms = productConfigHelper.getDeprecatedAcronyms(); if (allDeperecatedAcronyms.empty()) { return; } - ::testing::internal::CaptureStdout(); + ::StdoutCapture capture; + capture.captureStdout(); std::vector argv = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", allDeperecatedAcronyms[0].str()}; int deviceArgIndex = 5; @@ -2077,7 +2143,7 @@ TEST(OclocFatBinaryHelpersTest, givenListOfDeprecatedAcronymsThenUseThemAsIs) { auto retVal = buildFatBinaryForTarget(previousReturnValue, argv, pointerSize, ar, &mockOfflineCompiler, mockArgHelper, product.str()); EXPECT_EQ(0, retVal); } - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_TRUE(output.empty()) << output; auto encodedFatbin = ar.encode(); @@ -2096,7 +2162,7 @@ TEST(OclocFatBinaryHelpersTest, givenListOfDeprecatedAcronymsThenUseThemAsIs) { } } -TEST(OclocFatBinaryHelpersTest, givenListOfGenericAcronymsThenUseThemAsIs) { +TEST_F(OclocTest, givenListOfGenericAcronymsThenUseThemAsIs) { ProductConfigHelper productConfigHelper; std::vector genericAcronyms{}; @@ -2107,13 +2173,14 @@ TEST(OclocFatBinaryHelpersTest, givenListOfGenericAcronymsThenUseThemAsIs) { GTEST_SKIP(); } - ::testing::internal::CaptureStdout(); + ::StdoutCapture capture; + capture.captureStdout(); std::vector argv = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", genericAcronyms[0].str()}; int deviceArgIndex = 5; @@ -2136,7 +2203,7 @@ TEST(OclocFatBinaryHelpersTest, givenListOfGenericAcronymsThenUseThemAsIs) { auto retVal = buildFatBinaryForTarget(previousReturnValue, argv, pointerSize, ar, &mockOfflineCompiler, mockArgHelper, product.str()); EXPECT_EQ(0, retVal); } - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_TRUE(output.empty()) << output; auto encodedFatbin = ar.encode(); @@ -2155,13 +2222,13 @@ TEST(OclocFatBinaryHelpersTest, givenListOfGenericAcronymsThenUseThemAsIs) { } } -TEST(OclocFatBinaryHelpersTest, givenQuietModeWhenBuildingFatbinaryForTargetThenNothingIsPrinted) { +TEST_F(OclocTest, givenQuietModeWhenBuildingFatbinaryForTargetThenNothingIsPrinted) { using namespace std::string_literals; const std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-q", "-device", gEnvironment->devicePrefix.c_str()}; @@ -2178,10 +2245,11 @@ TEST(OclocFatBinaryHelpersTest, givenQuietModeWhenBuildingFatbinaryForTargetThen const auto mockArgHelper = mockOfflineCompiler.uniqueHelper.get(); const auto deviceConfig = getDeviceConfig(mockOfflineCompiler, mockArgHelper); - ::testing::internal::CaptureStdout(); + ::StdoutCapture capture; + capture.captureStdout(); const int previousReturnValue{OCLOC_SUCCESS}; const auto buildResult = buildFatBinaryForTarget(previousReturnValue, argv, pointerSize, ar, &mockOfflineCompiler, mockArgHelper, deviceConfig); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_SUCCESS, buildResult); EXPECT_EQ(1, mockOfflineCompiler.buildCalledCount); @@ -2189,34 +2257,34 @@ TEST(OclocFatBinaryHelpersTest, givenQuietModeWhenBuildingFatbinaryForTargetThen EXPECT_TRUE(output.empty()) << output; } -TEST(OclocFatBinaryHelpersTest, WhenDeviceArgIsPresentReturnsCorrectIndex) { +TEST_F(OclocTest, WhenDeviceArgIsPresentReturnsCorrectIndex) { std::vector args = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; EXPECT_EQ(4, getDeviceArgValueIdx(args)); } -TEST(OclocFatBinaryHelpersTest, WhenDeviceArgIsLastReturnsMinusOne) { +TEST_F(OclocTest, WhenDeviceArgIsLastReturnsMinusOne) { std::vector args = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device"}; EXPECT_EQ(-1, getDeviceArgValueIdx(args)); } -TEST(OclocFatBinaryHelpersTest, WhenDeviceArgIsAbsentReturnsMinusOne) { +TEST_F(OclocTest, WhenDeviceArgIsAbsentReturnsMinusOne) { std::vector args = { "ocloc", "-file", - clFiles + "copybuffer.cl"}; + clCopybufferFilename.c_str()}; EXPECT_EQ(-1, getDeviceArgValueIdx(args)); } -TEST(OclocFatBinaryHelpersTest, WhenArgsAreEmptyReturnsMinusOne) { +TEST_F(OclocTest, WhenArgsAreEmptyReturnsMinusOne) { std::vector args = {}; EXPECT_EQ(-1, getDeviceArgValueIdx(args)); } @@ -2245,4 +2313,4 @@ TEST_P(OclocFatbinaryPerProductTests, givenReleaseWhenGetTargetProductsForFarbin EXPECT_EQ(got, expected); } GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OclocFatbinaryPerProductTests); -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/opencl/test/unit_test/offline_compiler/ocloc_fatbinary_tests.h b/opencl/test/unit_test/offline_compiler/ocloc_fatbinary_tests.h index a19829c8ef..6143cd0f82 100644 --- a/opencl/test/unit_test/offline_compiler/ocloc_fatbinary_tests.h +++ b/opencl/test/unit_test/offline_compiler/ocloc_fatbinary_tests.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2023 Intel Corporation + * Copyright (C) 2020-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -10,14 +10,35 @@ #include "shared/offline_compiler/source/ocloc_arg_helper.h" #include "shared/offline_compiler/source/ocloc_fatbinary.h" #include "shared/source/helpers/product_config_helper.h" +#include "shared/test/common/helpers/mock_file_io.h" +#include "environment.h" #include "gtest/gtest.h" #include "mock/mock_argument_helper.h" #include +extern Environment *gEnvironment; + namespace NEO { -class OclocEnabledAcronyms : public ::testing::Test { + +class OclocTest : public ::testing::Test { + void SetUp() override { + std::string spvFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".spv"; + std::string binFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".bin"; + std::string dbgFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".dbg"; + std::vector mockByteArray = {0x01, 0x02, 0x03, 0x04}; + writeDataToFile(spvFile.c_str(), mockByteArray.data(), mockByteArray.size()); + writeDataToFile(binFile.c_str(), mockByteArray.data(), mockByteArray.size()); + writeDataToFile(dbgFile.c_str(), mockByteArray.data(), mockByteArray.size()); + } + + protected: + const std::string clCopybufferFilename = "some_kernel.cl"; + std::string copyKernelSources = "example_kernel(){}"; +}; + +class OclocEnabledAcronyms : public OclocTest { public: std::vector enabledProducts{}; std::vector enabledProductsAcronyms{}; @@ -28,7 +49,8 @@ class OclocEnabledAcronyms : public ::testing::Test { class OclocFatBinaryProductAcronymsTests : public OclocEnabledAcronyms { public: OclocFatBinaryProductAcronymsTests() { - oclocArgHelperWithoutInput = std::make_unique(); + mockArgHelperFilesMap[clCopybufferFilename] = copyKernelSources; + oclocArgHelperWithoutInput = std::make_unique(mockArgHelperFilesMap); oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(true); enabledProducts = oclocArgHelperWithoutInput->productConfigHelper->getDeviceAotInfo(); @@ -37,7 +59,9 @@ class OclocFatBinaryProductAcronymsTests : public OclocEnabledAcronyms { enabledReleasesAcronyms = oclocArgHelperWithoutInput->productConfigHelper->getReleasesAcronyms(); } - std::unique_ptr oclocArgHelperWithoutInput; + protected: + std::unique_ptr oclocArgHelperWithoutInput; + MockOclocArgHelper::FilesMap mockArgHelperFilesMap{}; }; class OclocFatBinaryTest : public OclocEnabledAcronyms { @@ -75,4 +99,4 @@ struct OclocFatbinaryPerProductTests : public ::testing::TestWithParam argHelper; }; -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/opencl/test/unit_test/offline_compiler/ocloc_fcl_facade_tests.cpp b/opencl/test/unit_test/offline_compiler/ocloc_fcl_facade_tests.cpp index 0792cbfb59..87a6990349 100644 --- a/opencl/test/unit_test/offline_compiler/ocloc_fcl_facade_tests.cpp +++ b/opencl/test/unit_test/offline_compiler/ocloc_fcl_facade_tests.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2023 Intel Corporation + * Copyright (C) 2022-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -11,6 +11,7 @@ #include "shared/source/debug_settings/debug_settings_manager.h" #include "shared/source/os_interface/os_inc_base.h" #include "shared/test/common/helpers/debug_manager_state_restore.h" +#include "shared/test/common/helpers/stdout_capture.h" #include "mock/mock_ocloc_fcl_facade.h" @@ -22,9 +23,10 @@ TEST_F(OclocFclFacadeTest, GivenMissingFclLibraryWhenPreparingFclThenFailureIsRe MockOclocFclFacade mockFclFacade{&mockArgHelper}; mockFclFacade.shouldFailLoadingOfFclLib = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto fclPreparationResult{mockFclFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, fclPreparationResult); EXPECT_FALSE(mockFclFacade.isInitialized()); @@ -39,9 +41,10 @@ TEST_F(OclocFclFacadeTest, GivenFailingLoadingOfFclSymbolsWhenPreparingFclThenFa MockOclocFclFacade mockFclFacade{&mockArgHelper}; mockFclFacade.shouldFailLoadingOfFclCreateMainFunction = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto fclPreparationResult{mockFclFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, fclPreparationResult); EXPECT_FALSE(mockFclFacade.isInitialized()); @@ -54,9 +57,10 @@ TEST_F(OclocFclFacadeTest, GivenFailingCreationOfFclMainWhenPreparingFclThenFail MockOclocFclFacade mockFclFacade{&mockArgHelper}; mockFclFacade.shouldFailCreationOfFclMain = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto fclPreparationResult{mockFclFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, fclPreparationResult); EXPECT_FALSE(mockFclFacade.isInitialized()); @@ -73,9 +77,10 @@ TEST_F(OclocFclFacadeTest, GivenIncompatibleFclInterfacesWhenPreparingFclThenFai mockFclFacade.isFclInterfaceCompatibleReturnValue = false; mockFclFacade.getIncompatibleInterfaceReturnValue = "SomeImportantInterface"; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto fclPreparationResult{mockFclFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, fclPreparationResult); EXPECT_FALSE(mockFclFacade.isInitialized()); @@ -88,9 +93,10 @@ TEST_F(OclocFclFacadeTest, GivenFailingCreationOfFclDeviceContextWhenPreparingFc MockOclocFclFacade mockFclFacade{&mockArgHelper}; mockFclFacade.shouldFailCreationOfFclDeviceContext = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto fclPreparationResult{mockFclFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, fclPreparationResult); EXPECT_FALSE(mockFclFacade.isInitialized()); @@ -103,9 +109,10 @@ TEST_F(OclocFclFacadeTest, GivenNoneErrorsSetAndNotPopulateFclInterfaceWhenPrepa MockOclocFclFacade mockFclFacade{&mockArgHelper}; mockFclFacade.shouldPopulateFclInterfaceReturnValue = false; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto fclPreparationResult{mockFclFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_SUCCESS, fclPreparationResult); EXPECT_TRUE(output.empty()) << output; @@ -118,9 +125,10 @@ TEST_F(OclocFclFacadeTest, GivenPopulateFclInterfaceAndInvalidFclDeviceContextWh mockFclFacade.shouldPopulateFclInterfaceReturnValue = true; mockFclFacade.shouldReturnInvalidFclPlatformHandle = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto fclPreparationResult{mockFclFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, fclPreparationResult); EXPECT_FALSE(mockFclFacade.isInitialized()); @@ -135,9 +143,10 @@ TEST_F(OclocFclFacadeTest, GivenPopulateFclInterfaceWhenPreparingFclThenSuccessI MockOclocFclFacade mockFclFacade{&mockArgHelper}; mockFclFacade.shouldPopulateFclInterfaceReturnValue = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto fclPreparationResult{mockFclFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_SUCCESS, fclPreparationResult); EXPECT_TRUE(output.empty()) << output; @@ -149,9 +158,10 @@ TEST_F(OclocFclFacadeTest, GivenPopulateFclInterfaceWhenPreparingFclThenSuccessI TEST_F(OclocFclFacadeTest, GivenNoneErrorsSetWhenPreparingFclThenSuccessIsReported) { MockOclocFclFacade mockFclFacade{&mockArgHelper}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto fclPreparationResult{mockFclFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_SUCCESS, fclPreparationResult); EXPECT_TRUE(output.empty()) << output; @@ -164,9 +174,10 @@ TEST_F(OclocFclFacadeTest, GivenNoneErrorsSetWhenPreparingFclThenSuccessIsReport TEST_F(OclocFclFacadeTest, GivenInitializedFclWhenGettingIncompatibleInterfaceThenEmptyStringIsReturned) { MockOclocFclFacade mockFclFacade{&mockArgHelper}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto fclPreparationResult{mockFclFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; ASSERT_EQ(OCLOC_SUCCESS, fclPreparationResult); diff --git a/opencl/test/unit_test/offline_compiler/ocloc_igc_facade_tests.cpp b/opencl/test/unit_test/offline_compiler/ocloc_igc_facade_tests.cpp index a26be7c0f9..6e385f66d2 100644 --- a/opencl/test/unit_test/offline_compiler/ocloc_igc_facade_tests.cpp +++ b/opencl/test/unit_test/offline_compiler/ocloc_igc_facade_tests.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2024 Intel Corporation + * Copyright (C) 2022-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -11,6 +11,7 @@ #include "shared/source/debug_settings/debug_settings_manager.h" #include "shared/source/os_interface/os_inc_base.h" #include "shared/test/common/helpers/debug_manager_state_restore.h" +#include "shared/test/common/helpers/stdout_capture.h" #include "shared/test/common/mocks/mock_compilers.h" #include "mock/mock_ocloc_igc_facade.h" @@ -23,11 +24,12 @@ TEST_F(OclocIgcFacadeTest, GivenMissingIgcLibraryWhenPreparingIgcThenFailureIsRe MockOclocIgcFacade mockIgcFacade{&mockArgHelper}; mockIgcFacade.shouldFailLoadingOfIgcLib = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); std::string libName = "invalidigc.so"; auto igcNameGuard = NEO::pushIgcDllName(libName.c_str()); const auto igcPreparationResult{mockIgcFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, igcPreparationResult); EXPECT_FALSE(mockIgcFacade.isInitialized()); @@ -42,9 +44,10 @@ TEST_F(OclocIgcFacadeTest, GivenFailingLoadingOfIgcSymbolsWhenPreparingIgcThenFa MockOclocIgcFacade mockIgcFacade{&mockArgHelper}; mockIgcFacade.shouldFailLoadingOfIgcCreateMainFunction = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto igcPreparationResult{mockIgcFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, igcPreparationResult); EXPECT_FALSE(mockIgcFacade.isInitialized()); @@ -57,9 +60,10 @@ TEST_F(OclocIgcFacadeTest, GivenFailingCreationOfIgcMainWhenPreparingIgcThenFail MockOclocIgcFacade mockIgcFacade{&mockArgHelper}; mockIgcFacade.shouldFailCreationOfIgcMain = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto igcPreparationResult{mockIgcFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, igcPreparationResult); EXPECT_FALSE(mockIgcFacade.isInitialized()); @@ -76,9 +80,10 @@ TEST_F(OclocIgcFacadeTest, GivenIncompatibleIgcInterfacesWhenPreparingIgcThenFai mockIgcFacade.isIgcInterfaceCompatibleReturnValue = false; mockIgcFacade.getIncompatibleInterfaceReturnValue = "SomeImportantInterface"; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto igcPreparationResult{mockIgcFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, igcPreparationResult); EXPECT_FALSE(mockIgcFacade.isInitialized()); @@ -91,9 +96,10 @@ TEST_F(OclocIgcFacadeTest, GivenMissingPatchtokenInterfaceWhenPreparingIgcThenFa MockOclocIgcFacade mockIgcFacade{&mockArgHelper}; mockIgcFacade.isPatchtokenInterfaceSupportedReturnValue = false; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto igcPreparationResult{mockIgcFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, igcPreparationResult); EXPECT_FALSE(mockIgcFacade.isInitialized()); @@ -106,9 +112,10 @@ TEST_F(OclocIgcFacadeTest, GivenFailingCreationOfIgcDeviceContextWhenPreparingIg MockOclocIgcFacade mockIgcFacade{&mockArgHelper}; mockIgcFacade.shouldFailCreationOfIgcDeviceContext = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto igcPreparationResult{mockIgcFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, igcPreparationResult); EXPECT_FALSE(mockIgcFacade.isInitialized()); @@ -127,9 +134,10 @@ TEST_F(OclocIgcFacadeTest, GivenInvalidIgcDeviceContextWhenPreparingIgcThenFailu MockOclocIgcFacade mockIgcFacade{&mockArgHelper}; mockIgcFacade.*invalidReturnFlag = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto igcPreparationResult{mockIgcFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, igcPreparationResult); EXPECT_FALSE(mockIgcFacade.isInitialized()); @@ -142,9 +150,10 @@ TEST_F(OclocIgcFacadeTest, GivenInvalidIgcDeviceContextWhenPreparingIgcThenFailu TEST_F(OclocIgcFacadeTest, GivenNoneErrorsSetWhenPreparingIgcThenSuccessIsReported) { MockOclocIgcFacade mockIgcFacade{&mockArgHelper}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto igcPreparationResult{mockIgcFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_SUCCESS, igcPreparationResult); EXPECT_TRUE(output.empty()) << output; @@ -154,9 +163,10 @@ TEST_F(OclocIgcFacadeTest, GivenNoneErrorsSetWhenPreparingIgcThenSuccessIsReport TEST_F(OclocIgcFacadeTest, GivenInitializedIgcWhenGettingIncompatibleInterfaceThenEmptyStringIsReturned) { MockOclocIgcFacade mockIgcFacade{&mockArgHelper}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto igcPreparationResult{mockIgcFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; ASSERT_EQ(OCLOC_SUCCESS, igcPreparationResult); @@ -170,9 +180,10 @@ TEST_F(OclocIgcFacadeTest, GivenFailingCreationOfIgcDeviceContext3WhenGettingRev MockOclocIgcFacade mockIgcFacade{&mockArgHelper}; mockIgcFacade.shouldFailCreationOfIgcDeviceContext3 = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto igcPreparationResult{mockIgcFacade.initialize(hwInfo)}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; ASSERT_EQ(OCLOC_SUCCESS, igcPreparationResult); diff --git a/opencl/test/unit_test/offline_compiler/offline_compiler_tests.cpp b/opencl/test/unit_test/offline_compiler/offline_compiler_tests.cpp index 7968fe0f23..ea0bb76088 100644 --- a/opencl/test/unit_test/offline_compiler/offline_compiler_tests.cpp +++ b/opencl/test/unit_test/offline_compiler/offline_compiler_tests.cpp @@ -18,11 +18,11 @@ #include "shared/source/device_binary_format/elf/elf_decoder.h" #include "shared/source/device_binary_format/elf/ocl_elf.h" #include "shared/source/helpers/compiler_product_helper.h" -#include "shared/source/helpers/file_io.h" #include "shared/source/helpers/hw_info.h" #include "shared/source/helpers/product_config_helper.h" #include "shared/test/common/helpers/debug_manager_state_restore.h" #include "shared/test/common/helpers/gtest_helpers.h" +#include "shared/test/common/helpers/stdout_capture.h" #include "shared/test/common/helpers/variable_backup.h" #include "shared/test/common/mocks/mock_compiler_cache.h" #include "shared/test/common/mocks/mock_compilers.h" @@ -44,12 +44,17 @@ #include #include #include +#include #include +#include #include +#include +#include extern Environment *gEnvironment; namespace NEO { +extern std::map virtualFileList; void MultiCommandTests::createFileWithArgs(const std::vector &singleArgs, int numOfBuild) { @@ -62,11 +67,11 @@ void MultiCommandTests::createFileWithArgs(const std::vector &singl } void MultiCommandTests::deleteFileWithArgs() { - remove(nameOfFileWithArgs.c_str()); + filesMap.erase(nameOfFileWithArgs); } void MultiCommandTests::deleteOutFileList() { - remove(outFileList.c_str()); + NEO::virtualFileList.erase(outFileList.c_str()); } std::string getCompilerOutputFileName(const std::string &fileName, const std::string &type) { @@ -79,11 +84,7 @@ std::string getCompilerOutputFileName(const std::string &fileName, const std::st } bool compilerOutputExists(const std::string &fileName, const std::string &type) { - return fileExists(getCompilerOutputFileName(fileName, type)); -} - -void compilerOutputRemove(const std::string &fileName, const std::string &type) { - std::remove(getCompilerOutputFileName(fileName, type).c_str()); + return NEO::virtualFileList.find(getCompilerOutputFileName(fileName, type)) != NEO::virtualFileList.end(); } template @@ -96,6 +97,8 @@ bool isAnyIrSectionDefined(const SectionHeaders §ionHeaders) { } TEST_F(MultiCommandTests, WhenBuildingMultiCommandThenSuccessIsReturned) { + VariableBackup mockCreateDir(&NEO::IoFunctions::mkdirPtr, [](const char *path) -> int { return 0; }); + nameOfFileWithArgs = "ImAMulitiComandMinimalGoodFile.txt"; std::vector argv = { "ocloc", @@ -106,13 +109,12 @@ TEST_F(MultiCommandTests, WhenBuildingMultiCommandThenSuccessIsReturned) { std::vector singleArgs = { "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; int numOfBuild = 4; createFileWithArgs(singleArgs, numOfBuild); - auto pMultiCommand = std::unique_ptr(MultiCommand::create(argv, retVal, oclocArgHelperWithoutInput.get())); EXPECT_NE(nullptr, pMultiCommand); @@ -122,6 +124,8 @@ TEST_F(MultiCommandTests, WhenBuildingMultiCommandThenSuccessIsReturned) { } TEST_F(MultiCommandTests, GivenOutputFileWhenBuildingMultiCommandThenSuccessIsReturned) { + VariableBackup mockCreateDir(&NEO::IoFunctions::mkdirPtr, [](const char *path) -> int { return 0; }); + nameOfFileWithArgs = "ImAMulitiComandMinimalGoodFile.txt"; std::vector argv = { "ocloc", @@ -133,7 +137,7 @@ TEST_F(MultiCommandTests, GivenOutputFileWhenBuildingMultiCommandThenSuccessIsRe std::vector singleArgs = { "-gen_file", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -156,6 +160,8 @@ TEST_F(MultiCommandTests, GivenOutputFileWhenBuildingMultiCommandThenSuccessIsRe } TEST_F(MultiCommandTests, GivenSpecifiedOutputDirWhenBuildingMultiCommandThenSuccessIsReturned) { + VariableBackup mockCreateDir(&NEO::IoFunctions::mkdirPtr, [](const char *path) -> int { return 0; }); + nameOfFileWithArgs = "ImAMulitiComandMinimalGoodFile.txt"; std::vector argv = { "ocloc", @@ -166,7 +172,7 @@ TEST_F(MultiCommandTests, GivenSpecifiedOutputDirWhenBuildingMultiCommandThenSuc std::vector singleArgs = { "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-out_dir", @@ -192,6 +198,8 @@ TEST_F(MultiCommandTests, GivenSpecifiedOutputDirWhenBuildingMultiCommandThenSuc } TEST_F(MultiCommandTests, GivenSpecifiedOutputDirWithProductConfigValueWhenBuildingMultiCommandThenSuccessIsReturned) { + VariableBackup mockCreateDir(&NEO::IoFunctions::mkdirPtr, [](const char *path) -> int { return 0; }); + auto &allEnabledDeviceConfigs = oclocArgHelperWithoutInput->productConfigHelper->getDeviceAotInfo(); if (allEnabledDeviceConfigs.empty()) { GTEST_SKIP(); @@ -215,7 +223,7 @@ TEST_F(MultiCommandTests, GivenSpecifiedOutputDirWithProductConfigValueWhenBuild std::vector singleArgs = { "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", configStr, "-out_dir", @@ -249,9 +257,10 @@ TEST_F(MultiCommandTests, GivenMissingTextFileWithArgsWhenBuildingMultiCommandTh "-q", }; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); auto pMultiCommand = std::unique_ptr(MultiCommand::create(argv, retVal, oclocArgHelperWithoutInput.get())); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_STRNE(output.c_str(), ""); EXPECT_EQ(nullptr, pMultiCommand); @@ -259,6 +268,8 @@ TEST_F(MultiCommandTests, GivenMissingTextFileWithArgsWhenBuildingMultiCommandTh debugManager.flags.PrintDebugMessages.set(false); } TEST_F(MultiCommandTests, GivenLackOfClFileWhenBuildingMultiCommandThenInvalidFileErrorIsReturned) { + VariableBackup mockCreateDir(&NEO::IoFunctions::mkdirPtr, [](const char *path) -> int { return 0; }); + nameOfFileWithArgs = "ImAMulitiComandMinimalGoodFile.txt"; std::vector argv = { "ocloc", @@ -275,9 +286,10 @@ TEST_F(MultiCommandTests, GivenLackOfClFileWhenBuildingMultiCommandThenInvalidFi int numOfBuild = 4; createFileWithArgs(singleArgs, numOfBuild); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); auto pMultiCommand = std::unique_ptr(MultiCommand::create(argv, retVal, oclocArgHelperWithoutInput.get())); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(nullptr, pMultiCommand); EXPECT_EQ(OCLOC_INVALID_FILE, retVal); @@ -286,6 +298,8 @@ TEST_F(MultiCommandTests, GivenLackOfClFileWhenBuildingMultiCommandThenInvalidFi deleteFileWithArgs(); } TEST_F(MultiCommandTests, GivenOutputFileListFlagWhenBuildingMultiCommandThenSuccessIsReturned) { + VariableBackup mockCreateDir(&NEO::IoFunctions::mkdirPtr, [](const char *path) -> int { return 0; }); + nameOfFileWithArgs = "ImAMulitiComandMinimalGoodFile.txt"; std::vector argv = { "ocloc", @@ -298,7 +312,7 @@ TEST_F(MultiCommandTests, GivenOutputFileListFlagWhenBuildingMultiCommandThenSuc std::vector singleArgs = { "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -329,9 +343,10 @@ TEST(MultiCommandWhiteboxTest, GivenVerboseModeWhenShowingResultsThenLogsArePrin mockMultiCommand.retValues = {OCLOC_SUCCESS, OCLOC_INVALID_FILE}; mockMultiCommand.quiet = false; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = mockMultiCommand.showResults(); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); const auto maskedResult = result | OCLOC_INVALID_FILE; EXPECT_NE(OCLOC_SUCCESS, result); @@ -348,7 +363,7 @@ TEST(MultiCommandWhiteboxTest, GivenVerboseModeAndDefinedOutputFilenameAndDirect std::vector singleArgs = { "-file", - clFiles + "copybuffer.cl", + "some_kernel.cl", "-output", "SpecialOutputFilename", "-out_dir", @@ -359,9 +374,10 @@ TEST(MultiCommandWhiteboxTest, GivenVerboseModeAndDefinedOutputFilenameAndDirect const auto singleArgsCopy{singleArgs}; const size_t buildId{0}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); mockMultiCommand.addAdditionalOptionsToSingleCommandLine(singleArgs, buildId); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_EQ(singleArgsCopy, singleArgs); } @@ -375,9 +391,10 @@ TEST(MultiCommandWhiteboxTest, GivenHelpArgumentsWhenInitializingThenHelpIsPrint const auto args{singleArgs}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = mockMultiCommand.initialize(args); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); const auto expectedOutput = R"===(Compiles multiple files using a config file. @@ -407,9 +424,10 @@ TEST(MultiCommandWhiteboxTest, GivenCommandLineWithApostrophesWhenSplittingLineI std::vector outputArgs{}; const std::size_t numberOfBuild{0}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = mockMultiCommand.splitLineInSeparateArgs(outputArgs, commandLine, numberOfBuild); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_SUCCESS, result); EXPECT_TRUE(output.empty()) << output; @@ -431,9 +449,10 @@ TEST(MultiCommandWhiteboxTest, GivenCommandLineWithMissingApostropheWhenSplittin std::vector outputArgs{}; const std::size_t numberOfBuild{0}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = mockMultiCommand.splitLineInSeparateArgs(outputArgs, commandLine, numberOfBuild); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_INVALID_FILE, result); @@ -460,13 +479,14 @@ TEST(MultiCommandWhiteboxTest, GivenTwoValidCommandLinesAndVerboseModeWhenRunnin mockMultiCommand.quiet = false; mockMultiCommand.callBaseSingleBuild = false; - const std::string validLine{"-file test_files/copybuffer.cl -output SpecialOutputFilename -out_dir SomeOutputDirectory -device " + gEnvironment->devicePrefix}; + const std::string validLine{"-file some_kernel.cl -output SpecialOutputFilename -out_dir SomeOutputDirectory -device " + gEnvironment->devicePrefix}; mockMultiCommand.lines.push_back(validLine); mockMultiCommand.lines.push_back(validLine); - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); mockMultiCommand.runBuilds("ocloc"); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_EQ(2, mockMultiCommand.singleBuildCalledCount); @@ -494,9 +514,10 @@ TEST(MultiCommandWhiteboxTest, GivenArgsWithQuietModeAndEmptyMulticommandFileWhe "commands.txt", "-q"}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = mockMultiCommand.initialize(args); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_INVALID_FILE, result); @@ -516,9 +537,10 @@ TEST(MultiCommandWhiteboxTest, GivenInvalidArgsWhenInitializingThenErrorIsReturn "commands.txt", "-invalid_option"}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = mockMultiCommand.initialize(args); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, result); @@ -597,9 +619,10 @@ TEST_F(MockOfflineCompilerTests, givenDeviceIdValueWhenInitHwInfoThenCorrectValu mockOfflineCompiler.deviceName = deviceIDStr.str(); EXPECT_FALSE(mockOfflineCompiler.deviceName.empty()); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); mockOfflineCompiler.initHardwareInfo(mockOfflineCompiler.deviceName); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); expectedOutput << "Auto-detected target based on " << deviceIDStr.str() << " device id: " << deviceStr << "\n"; EXPECT_STREQ(output.c_str(), expectedOutput.str().c_str()); @@ -633,9 +656,10 @@ TEST_F(MockOfflineCompilerTests, givenDeviceIdAndRevisionIdValueWhenInitHwInfoTh mockOfflineCompiler.revisionId = 0x0; EXPECT_FALSE(mockOfflineCompiler.deviceName.empty()); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); mockOfflineCompiler.initHardwareInfo(mockOfflineCompiler.deviceName); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); expectedOutput << "Auto-detected target based on " << deviceIDStr.str() << " device id: " << deviceStr << "\n"; EXPECT_STREQ(output.c_str(), expectedOutput.str().c_str()); @@ -893,9 +917,10 @@ TEST_F(OfflineCompilerTests, GivenHelpOptionOnQueryThenSuccessIsReturned) { "query", "--help"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = OfflineCompiler::query(argv.size(), argv, oclocArgHelperWithoutInput.get()); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_STREQ(OfflineCompiler::queryHelp.data(), output.c_str()); EXPECT_EQ(OCLOC_SUCCESS, retVal); @@ -909,9 +934,10 @@ TEST_F(OfflineCompilerTests, GivenHelpOptionOnIdsThenSuccessIsReturned) { "ids", helpFlag.str()}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = OfflineCompiler::queryAcronymIds(argv.size(), argv, oclocArgHelperWithoutInput.get()); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); std::stringstream expectedOutput; expectedOutput << R"===( @@ -932,32 +958,33 @@ TEST_F(OfflineCompilerTests, givenFamilyAcronymWhenIdsCommandIsInvokeThenSuccess GTEST_SKIP(); } auto &supportedDevicesConfigs = oclocArgHelperWithoutInput->productConfigHelper->getDeviceAotInfo(); - for (const auto &familyAcronym : enabledFamilies) { - std::vector expected{}; - auto family = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(familyAcronym.str()); - for (const auto &device : supportedDevicesConfigs) { - if (device.family == family) { - auto config = ProductConfigHelper::parseMajorMinorRevisionValue(device.aotConfig); - expected.push_back(config); - } - } - std::vector argv = { - "ocloc", - "ids", - familyAcronym.str()}; + std::string familyAcronym = enabledFamilies.front().str(); - std::stringstream expectedOutput; - testing::internal::CaptureStdout(); - int retVal = OfflineCompiler::queryAcronymIds(argv.size(), argv, oclocArgHelperWithoutInput.get()); - std::string output = testing::internal::GetCapturedStdout(); - expectedOutput << "Matched ids:\n"; - - for (const auto &prefix : expected) { - expectedOutput << prefix << "\n"; + std::vector expected{}; + auto family = oclocArgHelperWithoutInput->productConfigHelper->getFamilyFromDeviceName(familyAcronym); + for (const auto &device : supportedDevicesConfigs) { + if (device.family == family) { + auto config = ProductConfigHelper::parseMajorMinorRevisionValue(device.aotConfig); + expected.push_back(config); } - EXPECT_STREQ(expectedOutput.str().c_str(), output.c_str()); - EXPECT_EQ(OCLOC_SUCCESS, retVal); } + std::vector argv = { + "ocloc", + "ids", + familyAcronym}; + + std::stringstream expectedOutput; + StdoutCapture capture; + capture.captureStdout(); + int retVal = OfflineCompiler::queryAcronymIds(argv.size(), argv, oclocArgHelperWithoutInput.get()); + std::string output = capture.getCapturedStdout(); + expectedOutput << "Matched ids:\n"; + + for (const auto &prefix : expected) { + expectedOutput << prefix << "\n"; + } + EXPECT_STREQ(expectedOutput.str().c_str(), output.c_str()); + EXPECT_EQ(OCLOC_SUCCESS, retVal); } TEST_F(OfflineCompilerTests, givenReleaseAcronymWhenIdsCommandIsInvokeThenSuccessAndCorrectIdsAreReturned) { @@ -966,32 +993,32 @@ TEST_F(OfflineCompilerTests, givenReleaseAcronymWhenIdsCommandIsInvokeThenSucces GTEST_SKIP(); } auto &supportedDevicesConfigs = oclocArgHelperWithoutInput->productConfigHelper->getDeviceAotInfo(); - for (const auto &releaseAcronym : enabledReleases) { - std::vector expected{}; - auto release = oclocArgHelperWithoutInput->productConfigHelper->getReleaseFromDeviceName(releaseAcronym.str()); - for (const auto &device : supportedDevicesConfigs) { - if (device.release == release) { - auto config = ProductConfigHelper::parseMajorMinorRevisionValue(device.aotConfig); - expected.push_back(config); - } + const auto &releaseAcronym = enabledReleases.front(); + std::vector expected{}; + auto release = oclocArgHelperWithoutInput->productConfigHelper->getReleaseFromDeviceName(releaseAcronym.str()); + for (const auto &device : supportedDevicesConfigs) { + if (device.release == release) { + auto config = ProductConfigHelper::parseMajorMinorRevisionValue(device.aotConfig); + expected.push_back(config); } - std::vector argv = { - "ocloc", - "ids", - releaseAcronym.str()}; - - std::stringstream expectedOutput; - testing::internal::CaptureStdout(); - int retVal = OfflineCompiler::queryAcronymIds(argv.size(), argv, oclocArgHelperWithoutInput.get()); - std::string output = testing::internal::GetCapturedStdout(); - expectedOutput << "Matched ids:\n"; - - for (const auto &prefix : expected) { - expectedOutput << prefix << "\n"; - } - EXPECT_STREQ(expectedOutput.str().c_str(), output.c_str()); - EXPECT_EQ(OCLOC_SUCCESS, retVal); } + std::vector argv = { + "ocloc", + "ids", + releaseAcronym.str()}; + + std::stringstream expectedOutput; + StdoutCapture capture; + capture.captureStdout(); + int retVal = OfflineCompiler::queryAcronymIds(argv.size(), argv, oclocArgHelperWithoutInput.get()); + std::string output = capture.getCapturedStdout(); + expectedOutput << "Matched ids:\n"; + + for (const auto &prefix : expected) { + expectedOutput << prefix << "\n"; + } + EXPECT_STREQ(expectedOutput.str().c_str(), output.c_str()); + EXPECT_EQ(OCLOC_SUCCESS, retVal); } TEST_F(OfflineCompilerTests, givenProductAcronymWhenIdsCommandIsInvokeThenSuccessAndCorrectIdsAreReturned) { @@ -1000,32 +1027,32 @@ TEST_F(OfflineCompilerTests, givenProductAcronymWhenIdsCommandIsInvokeThenSucces GTEST_SKIP(); } auto &supportedDevicesConfigs = oclocArgHelperWithoutInput->productConfigHelper->getDeviceAotInfo(); - for (const auto &productAcronym : enabledProducts) { - std::vector expected{}; - auto product = ProductConfigHelper::getProductConfigFromAcronym(productAcronym.str()); - for (const auto &device : supportedDevicesConfigs) { - if (device.aotConfig.value == product) { - auto config = ProductConfigHelper::parseMajorMinorRevisionValue(device.aotConfig); - expected.push_back(config); - } + const auto &productAcronym = enabledProducts.front(); + std::vector expected{}; + auto product = ProductConfigHelper::getProductConfigFromAcronym(productAcronym.str()); + for (const auto &device : supportedDevicesConfigs) { + if (device.aotConfig.value == product) { + auto config = ProductConfigHelper::parseMajorMinorRevisionValue(device.aotConfig); + expected.push_back(config); } - std::vector argv = { - "ocloc", - "ids", - productAcronym.str()}; - - std::stringstream expectedOutput; - testing::internal::CaptureStdout(); - int retVal = OfflineCompiler::queryAcronymIds(argv.size(), argv, oclocArgHelperWithoutInput.get()); - std::string output = testing::internal::GetCapturedStdout(); - expectedOutput << "Matched ids:\n"; - - for (const auto &prefix : expected) { - expectedOutput << prefix << "\n"; - } - EXPECT_STREQ(expectedOutput.str().c_str(), output.c_str()); - EXPECT_EQ(OCLOC_SUCCESS, retVal); } + std::vector argv = { + "ocloc", + "ids", + productAcronym.str()}; + + std::stringstream expectedOutput; + StdoutCapture capture; + capture.captureStdout(); + int retVal = OfflineCompiler::queryAcronymIds(argv.size(), argv, oclocArgHelperWithoutInput.get()); + std::string output = capture.getCapturedStdout(); + expectedOutput << "Matched ids:\n"; + + for (const auto &prefix : expected) { + expectedOutput << prefix << "\n"; + } + EXPECT_STREQ(expectedOutput.str().c_str(), output.c_str()); + EXPECT_EQ(OCLOC_SUCCESS, retVal); } TEST_F(OfflineCompilerTests, WhenQueryingSupportedDevicesThenNonEmptyOutputFileIsGenerated) { @@ -1065,9 +1092,10 @@ TEST_F(OfflineCompilerTests, GivenFlagsWhichRequireMoreArgsWithoutThemWhenParsin MockOfflineCompiler mockOfflineCompiler{}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = mockOfflineCompiler.parseCommandLine(argv.size(), argv); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, result); @@ -1085,7 +1113,7 @@ TEST_F(OfflineCompilerTests, Given32BitModeFlagWhenParsingThenInternalOptionsCon "ocloc", "compile", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), flag, "-device", gEnvironment->devicePrefix.c_str()}; @@ -1106,7 +1134,7 @@ TEST_F(OfflineCompilerTests, givenConfigFlagWhenParsingCommandLineThenCorrectVal "ocloc", "compile", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-config", @@ -1127,7 +1155,7 @@ TEST_F(OfflineCompilerTests, givenIncorrectConfigFlagWhenParsingCommandLineThenE "ocloc", "compile", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-config", @@ -1135,9 +1163,10 @@ TEST_F(OfflineCompilerTests, givenIncorrectConfigFlagWhenParsingCommandLineThenE MockOfflineCompiler mockOfflineCompiler{}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = mockOfflineCompiler.parseCommandLine(argv.size(), argv); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, result); EXPECT_EQ(mockOfflineCompiler.hwInfoConfig, 0u); @@ -1155,7 +1184,7 @@ TEST_F(OfflineCompilerTests, Given64BitModeFlagWhenParsingThenInternalOptionsCon "ocloc", "compile", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), flag, "-device", gEnvironment->devicePrefix.c_str()}; @@ -1175,7 +1204,7 @@ TEST_F(OfflineCompilerTests, Given32BitModeFlagAnd64BitModeFlagWhenParsingThenEr "ocloc", "compile", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-32", "-64", "-device", @@ -1183,9 +1212,10 @@ TEST_F(OfflineCompilerTests, Given32BitModeFlagAnd64BitModeFlagWhenParsingThenEr MockOfflineCompiler mockOfflineCompiler{}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = mockOfflineCompiler.parseCommandLine(argv.size(), argv); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_NE(OCLOC_SUCCESS, result); @@ -1208,7 +1238,7 @@ TEST_F(OfflineCompilerTests, GivenFlagStringWhenParsingThenInternalBooleanIsSetA "ocloc", "compile", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), flagString, "-device", gEnvironment->devicePrefix.c_str()}; @@ -1251,6 +1281,7 @@ TEST_F(OfflineCompilerTests, givenDeviceAsPvcHexIdAndDeviceOptionsStricteForPvcO } TEST_F(OfflineCompilerTests, givenDeviceHexIdAndDeviceOptionsInGeneralWhenCmdLineParsedThenHexIdIsTranslatedToAcronymAndDeviceOptionsAreApplied) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); struct DeviceIdElementDescriptionType { unsigned short idVal; std::string idStr; @@ -1275,61 +1306,60 @@ TEST_F(OfflineCompilerTests, givenDeviceHexIdAndDeviceOptionsInGeneralWhenCmdLin #undef DEVICE_CONFIG }; - for (auto &deviceIdElement : deviceIdsVec) { - std::transform(deviceIdElement.idStr.begin(), deviceIdElement.idStr.end(), deviceIdElement.idStr.begin(), ::tolower); - for (auto &configRelationElement : configRelationVec) { - if (deviceIdElement.configStr != configRelationElement.configStr || - std::find(configRelationElement.devIdVals.begin(), configRelationElement.devIdVals.end(), deviceIdElement.idVal) == configRelationElement.devIdVals.end()) { - continue; - } - for (auto &acrMapEl : AOT::deviceAcronyms) { - if (acrMapEl.second == configRelationElement.prodIpTypeVal) { - deviceIdElement.acronymsResultants.push_back(acrMapEl.first); - } - } - for (auto &acrMapEl : AOT::rtlIdAcronyms) { - if (acrMapEl.second == configRelationElement.prodIpTypeVal) { - deviceIdElement.acronymsResultants.push_back(acrMapEl.first); - } - } - for (auto &acrMapEl : AOT::genericIdAcronyms) { - if (acrMapEl.second == configRelationElement.prodIpTypeVal) { - deviceIdElement.acronymsResultants.push_back(acrMapEl.first); - } - } - } + if (deviceIdsVec.empty()) { + GTEST_SKIP(); } - for (auto &deviceIdElement : deviceIdsVec) { - if (deviceIdElement.acronymsResultants.empty()) { + auto &deviceIdElement = deviceIdsVec.front(); + std::transform(deviceIdElement.idStr.begin(), deviceIdElement.idStr.end(), deviceIdElement.idStr.begin(), ::tolower); + + for (auto &configRelationElement : configRelationVec) { + if (deviceIdElement.configStr != configRelationElement.configStr || + std::find(configRelationElement.devIdVals.begin(), configRelationElement.devIdVals.end(), deviceIdElement.idVal) == configRelationElement.devIdVals.end()) { continue; } - std::string deviceIdStr = deviceIdElement.idStr, - relevantAcronymStr = deviceIdElement.acronymsResultants.front(), - exampleDevOptionsStr = "any string with options e.g.: (-options)? -ze-opt-large-register-file"; - const std::vector argv = { - "ocloc", - "compile", - "-file", clFiles + "foo.spv", - "-output_no_suffix", - "-spirv_input", - "-device_options", relevantAcronymStr, exampleDevOptionsStr, - "-device", deviceIdStr}; - auto mockOfflineCompiler = std::make_unique(); - ASSERT_NE(nullptr, mockOfflineCompiler); + auto addFirstMatchingAcronym = [&](const std::map &acronymMap) -> bool { + for (const auto &acrMapEl : acronymMap) { + if (acrMapEl.second == configRelationElement.prodIpTypeVal) { + deviceIdElement.acronymsResultants.push_back(acrMapEl.first); + return true; + } + } + return false; + }; - auto allEnabledDeviceAcronyms = mockOfflineCompiler->argHelper->productConfigHelper->getRepresentativeProductAcronyms(); - auto deprecatedAcronyms = mockOfflineCompiler->argHelper->productConfigHelper->getDeprecatedAcronyms(); - if ((allEnabledDeviceAcronyms.empty() || std::find(allEnabledDeviceAcronyms.begin(), allEnabledDeviceAcronyms.end(), relevantAcronymStr) == allEnabledDeviceAcronyms.end()) && (deprecatedAcronyms.empty() || std::find(deprecatedAcronyms.begin(), deprecatedAcronyms.end(), relevantAcronymStr) == deprecatedAcronyms.end())) { - GTEST_SKIP(); + if (addFirstMatchingAcronym(AOT::deviceAcronyms) || + addFirstMatchingAcronym(AOT::rtlIdAcronyms) || + addFirstMatchingAcronym(AOT::genericIdAcronyms)) { + break; } - - const auto result = mockOfflineCompiler->parseCommandLine(argv.size(), argv); - - EXPECT_EQ(OCLOC_SUCCESS, result); - EXPECT_STREQ(mockOfflineCompiler->options.c_str(), exampleDevOptionsStr.c_str()); } + + if (deviceIdElement.acronymsResultants.empty()) { + GTEST_SKIP(); + } + + std::string deviceIdStr = deviceIdElement.idStr; + std::string relevantAcronymStr = deviceIdElement.acronymsResultants.front(); + std::string exampleDevOptionsStr = "any string with options e.g.: (-options)? -ze-opt-large-register-file"; + + const std::vector argv = { + "ocloc", + "compile", + "-file", clFiles + "foo.spv", + "-output_no_suffix", + "-spirv_input", + "-device_options", relevantAcronymStr, exampleDevOptionsStr, + "-device", deviceIdStr}; + + auto mockOfflineCompiler = std::make_unique(); + ASSERT_NE(nullptr, mockOfflineCompiler); + + const auto result = mockOfflineCompiler->parseCommandLine(argv.size(), argv); + EXPECT_EQ(OCLOC_SUCCESS, result); + + EXPECT_STREQ(mockOfflineCompiler->options.c_str(), exampleDevOptionsStr.c_str()); } TEST_F(OfflineCompilerTests, WhenPickingFormatFromCommandLineThenCodeTypeIsSetAccordingly) { @@ -1337,7 +1367,7 @@ TEST_F(OfflineCompilerTests, WhenPickingFormatFromCommandLineThenCodeTypeIsSetAc "ocloc", "compile", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -1394,6 +1424,7 @@ TEST_F(OfflineCompilerTests, GivenArgsWhenQueryIsCalledThenSuccessIsReturned) { "query", "NEO_REVISION"}; + oclocArgHelperWithoutInput->messagePrinter.setSuppressMessages(true); int retVal = OfflineCompiler::query(argv.size(), argv, oclocArgHelperWithoutInput.get()); EXPECT_EQ(OCLOC_SUCCESS, retVal); @@ -1403,7 +1434,7 @@ TEST_F(OfflineCompilerTests, GivenArgsWhenOfflineCompilerIsCreatedThenSuccessIsR std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -1447,16 +1478,17 @@ TEST_F(OfflineCompilerTests, givenProperDeviceIdHexAsDeviceArgumentThenSuccessIs std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", deviceString.str()}; oclocArgHelperWithoutInput->getPrinterRef().setSuppressMessages(false); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); EXPECT_EQ(pOfflineCompiler->getHardwareInfo().platform.usDeviceID, deviceId); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); std::stringstream resString; resString << "Auto-detected target based on " << deviceString.str() << " device id: " << productString.str() << "\n"; @@ -1471,14 +1503,15 @@ TEST_F(OfflineCompilerTests, givenIncorrectDeviceIdHexThenInvalidDeviceIsReturne std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", "0x0"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(nullptr, pOfflineCompiler); EXPECT_STREQ(output.c_str(), "Could not determine device target: 0x0.\nError: Cannot get HW Info for device 0x0.\n"); EXPECT_EQ(CL_INVALID_DEVICE, retVal); @@ -1488,12 +1521,13 @@ TEST_F(OfflineCompilerTests, givenDeviceNumerationWithMissingRevisionValueWhenIn std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", "9.1."}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(nullptr, pOfflineCompiler); EXPECT_STREQ(output.c_str(), "Could not determine device target: 9.1..\nError: Cannot get HW Info for device 9.1..\n"); EXPECT_EQ(CL_INVALID_DEVICE, retVal); @@ -1503,12 +1537,13 @@ TEST_F(OfflineCompilerTests, givenDeviceNumerationWithInvalidPatternThenInvalidD std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", "9.1.."}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(nullptr, pOfflineCompiler); EXPECT_STREQ(output.c_str(), "Could not determine device target: 9.1...\nError: Cannot get HW Info for device 9.1...\n"); EXPECT_EQ(CL_INVALID_DEVICE, retVal); @@ -1518,12 +1553,13 @@ TEST_F(OfflineCompilerTests, givenDeviceNumerationWithMissingMajorValueWhenInval std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", ".1.2"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(nullptr, pOfflineCompiler); EXPECT_STREQ(output.c_str(), "Could not determine device target: .1.2.\nError: Cannot get HW Info for device .1.2.\n"); EXPECT_EQ(CL_INVALID_DEVICE, retVal); @@ -1533,12 +1569,13 @@ TEST_F(OfflineCompilerTests, givenDeviceNumerationWhenInvalidRevisionValueIsPass std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", "9.0.a"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(nullptr, pOfflineCompiler); EXPECT_STREQ(output.c_str(), "Could not determine device target: 9.0.a.\nError: Cannot get HW Info for device 9.0.a.\n"); EXPECT_EQ(CL_INVALID_DEVICE, retVal); @@ -1548,12 +1585,13 @@ TEST_F(OfflineCompilerTests, givenDeviceNumerationWhenInvalidMinorValueIsPassedT std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", "9.a"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(nullptr, pOfflineCompiler); EXPECT_STREQ(output.c_str(), "Could not determine device target: 9.a.\nError: Cannot get HW Info for device 9.a.\n"); EXPECT_EQ(CL_INVALID_DEVICE, retVal); @@ -1563,12 +1601,13 @@ TEST_F(OfflineCompilerTests, givenDeviceNumerationWhenPassedValuesAreOutOfRangeT std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", "256.350"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(nullptr, pOfflineCompiler); EXPECT_STREQ(output.c_str(), "Could not determine device target: 256.350.\nError: Cannot get HW Info for device 256.350.\n"); EXPECT_EQ(CL_INVALID_DEVICE, retVal); @@ -1578,12 +1617,13 @@ TEST_F(OfflineCompilerTests, givenDeviceIpVersionWhenPassedValueNotExistThenInva std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", "1234"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(nullptr, pOfflineCompiler); EXPECT_STREQ(output.c_str(), "Could not determine device target: 1234.\nError: Cannot get HW Info for device 1234.\n"); EXPECT_EQ(CL_INVALID_DEVICE, retVal); @@ -1614,12 +1654,13 @@ TEST_F(OfflineCompilerTests, givenIncorrectDeviceIdWithIncorrectHexPatternThenIn std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", "0xnonexist"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); EXPECT_EQ(nullptr, pOfflineCompiler); EXPECT_STREQ(output.c_str(), "Could not determine device target: 0xnonexist.\nError: Cannot get HW Info for device 0xnonexist.\n"); EXPECT_EQ(CL_INVALID_DEVICE, retVal); @@ -1635,7 +1676,7 @@ TEST_F(OfflineCompilerTests, givenDebugOptionThenInternalOptionShouldNotContainK "-options", "-g", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -1771,7 +1812,7 @@ TEST_F(OfflineCompilerTests, givenDashGInBiggerOptionStringWhenInitializingThenI "-options", "-gNotRealDashGOption", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -1787,7 +1828,7 @@ TEST_F(OfflineCompilerTests, givenExcludeIrFromZebinInternalOptionWhenInitIsPerf std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-internal_options", "-ze-exclude-ir-from-zebin", "-device", @@ -1803,21 +1844,23 @@ TEST_F(OfflineCompilerTests, givenValidArgumentsAndFclInitFailureWhenInitIsPerfo std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; MockOfflineCompiler mockOfflineCompiler{}; mockOfflineCompiler.mockFclFacade->shouldFailLoadingOfFclLib = true; + mockOfflineCompiler.uniqueHelper->filesMap = filesMap; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto initResult = mockOfflineCompiler.initialize(argv.size(), argv); EXPECT_EQ(OCLOC_SUCCESS, initResult); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); - testing::internal::CaptureStdout(); + capture.captureStdout(); const auto buildResult = mockOfflineCompiler.build(); - output = testing::internal::GetCapturedStdout(); + output = capture.getCapturedStdout(); std::stringstream expectedErrorMessage; expectedErrorMessage << "Error! Loading of FCL library has failed! Filename: " << Os::frontEndDllName << "\n" @@ -1831,22 +1874,24 @@ TEST_F(OfflineCompilerTests, givenValidArgumentsAndIgcInitFailureWhenInitIsPerfo std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; MockOfflineCompiler mockOfflineCompiler{}; + mockOfflineCompiler.uniqueHelper->filesMap = filesMap; std::string libName = "invalidigc.so"; auto igcNameGuard = NEO::pushIgcDllName(libName.c_str()); mockOfflineCompiler.mockIgcFacade->shouldFailLoadingOfIgcLib = true; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto initResult = mockOfflineCompiler.initialize(argv.size(), argv); EXPECT_EQ(OCLOC_SUCCESS, initResult); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); - testing::internal::CaptureStdout(); + capture.captureStdout(); const auto buildResult = mockOfflineCompiler.build(); - output = testing::internal::GetCapturedStdout(); + output = capture.getCapturedStdout(); std::stringstream expectedErrorMessage; expectedErrorMessage << "Error! Loading of IGC library has failed! Filename: " << libName << "\n" @@ -1860,7 +1905,7 @@ TEST_F(OfflineCompilerTests, givenExcludeIrArgumentWhenInitIsPerformedThenIrExcl std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-exclude_ir", "-device", gEnvironment->devicePrefix.c_str()}; @@ -1877,7 +1922,7 @@ TEST_F(OfflineCompilerTests, givenExcludeIrArgumentAndExcludeIrFromZebinInternal std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-exclude_ir", "-internal_options", "-ze-exclude-ir-from-zebin", @@ -1908,7 +1953,7 @@ TEST_F(OfflineCompilerTests, givenExcludeIrArgumentWhenGeneratingElfBinaryFromPa std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-exclude_ir", "-device", gEnvironment->devicePrefix.c_str(), @@ -1942,13 +1987,14 @@ TEST_F(OfflineCompilerTests, givenZeroSizeInputFileWhenInitializationIsPerformed std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; MockOfflineCompiler mockOfflineCompiler{}; mockOfflineCompiler.uniqueHelper->callBaseLoadDataFromFile = false; mockOfflineCompiler.uniqueHelper->shouldLoadDataFromFileReturnZeroSize = true; + mockOfflineCompiler.uniqueHelper->messagePrinter.setSuppressMessages(true); const auto initResult = mockOfflineCompiler.initialize(argv.size(), argv); EXPECT_EQ(OCLOC_SUCCESS, initResult); @@ -1964,11 +2010,12 @@ TEST_F(OfflineCompilerTests, givenInvalidIgcOutputWhenCompilingKernelThenOutOfHo std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; MockOfflineCompiler mockOfflineCompiler{}; + mockOfflineCompiler.uniqueHelper->filesMap = filesMap; const auto initResult = mockOfflineCompiler.initialize(argv.size(), argv); EXPECT_EQ(OCLOC_SUCCESS, initResult); @@ -1987,11 +2034,12 @@ TEST_F(OfflineCompilerTests, givenIgcBuildFailureWhenCompilingKernelThenBuildPro std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; MockOfflineCompiler mockOfflineCompiler{}; + mockOfflineCompiler.uniqueHelper->filesMap = filesMap; const auto initResult = mockOfflineCompiler.initialize(argv.size(), argv); EXPECT_EQ(OCLOC_SUCCESS, initResult); @@ -2010,11 +2058,12 @@ TEST_F(OfflineCompilerTests, givenInvalidFclOutputWhenCompilingKernelThenOutOfHo std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; MockOfflineCompiler mockOfflineCompiler{}; + mockOfflineCompiler.uniqueHelper->filesMap = filesMap; const auto initResult = mockOfflineCompiler.initialize(argv.size(), argv); EXPECT_EQ(OCLOC_SUCCESS, initResult); @@ -2033,11 +2082,12 @@ TEST_F(OfflineCompilerTests, givenFclTranslationContextCreationFailureWhenCompil std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; MockOfflineCompiler mockOfflineCompiler{}; + mockOfflineCompiler.uniqueHelper->filesMap = filesMap; const auto initResult = mockOfflineCompiler.initialize(argv.size(), argv); EXPECT_EQ(OCLOC_SUCCESS, initResult); @@ -2057,11 +2107,12 @@ TEST_F(OfflineCompilerTests, givenFclTranslationContextCreationFailureAndErrorMe std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; MockOfflineCompiler mockOfflineCompiler{}; + mockOfflineCompiler.uniqueHelper->filesMap = filesMap; const auto initResult = mockOfflineCompiler.initialize(argv.size(), argv); EXPECT_EQ(OCLOC_SUCCESS, initResult); @@ -2081,7 +2132,7 @@ TEST_F(OfflineCompilerTests, givenVariousClStdValuesWhenCompilingSourceThenCorre std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -2129,7 +2180,7 @@ TEST_F(OfflineCompilerTests, GivenArgsWhenBuildingThenBuildSucceeds) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "--format", @@ -2140,13 +2191,14 @@ TEST_F(OfflineCompilerTests, GivenArgsWhenBuildingThenBuildSucceeds) { EXPECT_NE(nullptr, pOfflineCompiler); EXPECT_EQ(CL_SUCCESS, retVal); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); retVal = pOfflineCompiler->build(); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(CL_SUCCESS, retVal); - EXPECT_TRUE(compilerOutputExists("copybuffer", "bc") || compilerOutputExists("copybuffer", "spv")); - EXPECT_FALSE(compilerOutputExists("copybuffer", "gen")); - EXPECT_TRUE(compilerOutputExists("copybuffer", "bin")); + EXPECT_TRUE(compilerOutputExists("some_kernel", "bc") || compilerOutputExists("some_kernel", "spv")); + EXPECT_FALSE(compilerOutputExists("some_kernel", "gen")); + EXPECT_TRUE(compilerOutputExists("some_kernel", "bin")); std::string buildLog = pOfflineCompiler->getBuildLog(); EXPECT_STREQ(buildLog.c_str(), ""); @@ -2171,7 +2223,7 @@ TEST_F(OfflineCompilerTests, GivenArgsWhenBuildingWithDeviceConfigValueThenBuild std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", configStr, "--format", @@ -2182,13 +2234,14 @@ TEST_F(OfflineCompilerTests, GivenArgsWhenBuildingWithDeviceConfigValueThenBuild EXPECT_NE(nullptr, pOfflineCompiler); EXPECT_EQ(CL_SUCCESS, retVal); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); retVal = pOfflineCompiler->build(); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(CL_SUCCESS, retVal); - EXPECT_TRUE(compilerOutputExists("copybuffer", "bc") || compilerOutputExists("copybuffer", "spv")); - EXPECT_FALSE(compilerOutputExists("copybuffer", "gen")); - EXPECT_TRUE(compilerOutputExists("copybuffer", "bin")); + EXPECT_TRUE(compilerOutputExists("some_kernel", "bc") || compilerOutputExists("some_kernel", "spv")); + EXPECT_FALSE(compilerOutputExists("some_kernel", "gen")); + EXPECT_TRUE(compilerOutputExists("some_kernel", "bin")); std::string buildLog = pOfflineCompiler->getBuildLog(); EXPECT_STREQ(buildLog.c_str(), ""); @@ -2213,7 +2266,7 @@ TEST_F(OfflineCompilerTests, GivenArgsWhenBuildingWithDeviceIpVersionValueThenBu std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", ipVersion.str(), "--format", @@ -2224,13 +2277,14 @@ TEST_F(OfflineCompilerTests, GivenArgsWhenBuildingWithDeviceIpVersionValueThenBu EXPECT_NE(nullptr, pOfflineCompiler); EXPECT_EQ(CL_SUCCESS, retVal); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); retVal = pOfflineCompiler->build(); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(CL_SUCCESS, retVal); - EXPECT_TRUE(compilerOutputExists("copybuffer", "bc") || compilerOutputExists("copybuffer", "spv")); - EXPECT_FALSE(compilerOutputExists("copybuffer", "gen")); - EXPECT_TRUE(compilerOutputExists("copybuffer", "bin")); + EXPECT_TRUE(compilerOutputExists("some_kernel", "bc") || compilerOutputExists("some_kernel", "spv")); + EXPECT_FALSE(compilerOutputExists("some_kernel", "gen")); + EXPECT_TRUE(compilerOutputExists("some_kernel", "bin")); std::string buildLog = pOfflineCompiler->getBuildLog(); EXPECT_STREQ(buildLog.c_str(), ""); @@ -2242,7 +2296,7 @@ TEST_F(OfflineCompilerTests, GivenLlvmTextWhenBuildingThenBuildSucceeds) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-llvm_text", @@ -2256,76 +2310,62 @@ TEST_F(OfflineCompilerTests, GivenLlvmTextWhenBuildingThenBuildSucceeds) { retVal = pOfflineCompiler->build(); EXPECT_EQ(CL_SUCCESS, retVal); - EXPECT_TRUE(compilerOutputExists("copybuffer", "ll")); - EXPECT_FALSE(compilerOutputExists("copybuffer", "gen")); - EXPECT_TRUE(compilerOutputExists("copybuffer", "bin")); + EXPECT_TRUE(compilerOutputExists("some_kernel", "ll")); + EXPECT_FALSE(compilerOutputExists("some_kernel", "gen")); + EXPECT_TRUE(compilerOutputExists("some_kernel", "bin")); delete pOfflineCompiler; } TEST_F(OfflineCompilerTests, WhenGenFileFlagIsNotProvidedThenGenFileIsNotCreated) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "copybuffer.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + VariableBackup mockFseek(&NEO::IoFunctions::fseekPtr); + VariableBackup mockFtell(&NEO::IoFunctions::ftellPtr); + VariableBackup mockFread(&NEO::IoFunctions::freadPtr); + + NEO::IoFunctions::fseekPtr = [](FILE *stream, long int offset, int origin) -> int { + return 0; + }; + NEO::IoFunctions::ftellPtr = [](FILE *stream) -> long int { + std::string kernelSource = "example_kernel(){}"; + std::stringstream fileStream(kernelSource); + fileStream.seekg(0, std::ios::end); + return static_cast(fileStream.tellg()); + }; + NEO::IoFunctions::freadPtr = [](void *ptr, size_t size, size_t count, FILE *stream) -> size_t { + std::string kernelSource = "example_kernel(){}"; + std::stringstream fileStream(kernelSource); + size_t totalBytes = size * count; + fileStream.read(static_cast(ptr), totalBytes); + return static_cast(fileStream.gcount() / size); + }; + uint32_t numOutputs = 0u; uint64_t *lenOutputs = nullptr; uint8_t **dataOutputs = nullptr; char **nameOutputs = nullptr; - std::string filePath = clFiles + "copybuffer.cl"; bool isSpvFile = false; bool isGenFile = false; bool isBinFile = false; - - const char *argv[] = { - "ocloc", - "-q", - "-file", - filePath.c_str(), - "-device", - gEnvironment->devicePrefix.c_str()}; - - unsigned int argc = sizeof(argv) / sizeof(const char *); - int retVal = oclocInvoke(argc, argv, - 0, nullptr, nullptr, nullptr, - 0, nullptr, nullptr, nullptr, - &numOutputs, &dataOutputs, &lenOutputs, &nameOutputs); - - EXPECT_EQ(retVal, CL_SUCCESS); - EXPECT_EQ(numOutputs, 3u); - - for (unsigned int i = 0; i < numOutputs; i++) { - std::string nameOutput(nameOutputs[i]); - if (nameOutput.find(".spv") != std::string::npos) { - isSpvFile = true; - } - if (nameOutput.find(".gen") != std::string::npos) { - isGenFile = true; - } - if (nameOutput.find(".bin") != std::string::npos) { - isBinFile = true; - } - } - - EXPECT_TRUE(isSpvFile); - EXPECT_FALSE(isGenFile); - EXPECT_TRUE(isBinFile); - - oclocFreeOutput(&numOutputs, &dataOutputs, &lenOutputs, &nameOutputs); -} - -TEST_F(OfflineCompilerTests, WhenGenFileFlagIsProvidedThenGenFileIsCreated) { - uint32_t numOutputs = 0u; - uint64_t *lenOutputs = nullptr; - uint8_t **dataOutputs = nullptr; - char **nameOutputs = nullptr; std::string filePath = clFiles + "copybuffer.cl"; - bool isSpvFile = false; - bool isGenFile = false; - bool isBinFile = false; - const char *argv[] = { "ocloc", "-q", - "-gen_file", "-file", filePath.c_str(), "-device", @@ -2353,6 +2393,90 @@ TEST_F(OfflineCompilerTests, WhenGenFileFlagIsProvidedThenGenFileIsCreated) { } } + EXPECT_TRUE(isSpvFile); + EXPECT_FALSE(isGenFile); + EXPECT_TRUE(isBinFile); + + oclocFreeOutput(&numOutputs, &dataOutputs, &lenOutputs, &nameOutputs); +} + +TEST_F(OfflineCompilerTests, WhenGenFileFlagIsProvidedThenGenFileIsCreated) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "copybuffer.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + VariableBackup mockFseek(&NEO::IoFunctions::fseekPtr); + VariableBackup mockFtell(&NEO::IoFunctions::ftellPtr); + VariableBackup mockFread(&NEO::IoFunctions::freadPtr); + + NEO::IoFunctions::fseekPtr = [](FILE *stream, long int offset, int origin) -> int { + return 0; + }; + NEO::IoFunctions::ftellPtr = [](FILE *stream) -> long int { + std::string kernelSource = "example_kernel(){}"; + std::stringstream fileStream(kernelSource); + fileStream.seekg(0, std::ios::end); + return static_cast(fileStream.tellg()); + }; + NEO::IoFunctions::freadPtr = [](void *ptr, size_t size, size_t count, FILE *stream) -> size_t { + std::string kernelSource = "example_kernel(){}"; + std::stringstream fileStream(kernelSource); + size_t totalBytes = size * count; + fileStream.read(static_cast(ptr), totalBytes); + return static_cast(fileStream.gcount() / size); + }; + + uint32_t numOutputs = 0u; + uint64_t *lenOutputs = nullptr; + uint8_t **dataOutputs = nullptr; + char **nameOutputs = nullptr; + std::string filePath = clFiles + "copybuffer.cl"; + + bool isSpvFile = false; + bool isGenFile = false; + bool isBinFile = false; + + const char *argv[] = { + "ocloc", + "-q", + "-gen_file", + "-file", + filePath.c_str(), + "-device", + gEnvironment->devicePrefix.c_str()}; + + unsigned int argc = sizeof(argv) / sizeof(const char *); + int retVal = oclocInvoke(argc, argv, + 0, nullptr, nullptr, nullptr, + 0, nullptr, nullptr, nullptr, + &numOutputs, &dataOutputs, &lenOutputs, &nameOutputs); + + EXPECT_EQ(retVal, CL_SUCCESS); + EXPECT_EQ(numOutputs, 5u); + + for (unsigned int i = 0; i < numOutputs; i++) { + std::string nameOutput(nameOutputs[i]); + if (nameOutput.find(".spv") != std::string::npos) { + isSpvFile = true; + } + if (nameOutput.find(".gen") != std::string::npos) { + isGenFile = true; + } + if (nameOutput.find(".bin") != std::string::npos) { + isBinFile = true; + } + } + EXPECT_TRUE(isSpvFile); EXPECT_TRUE(isGenFile); EXPECT_TRUE(isBinFile); @@ -2364,14 +2488,16 @@ TEST_F(OfflineCompilerTests, WhenFclNotNeededThenDontLoadIt) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-spirv_input"}; MockOfflineCompiler offlineCompiler; + offlineCompiler.uniqueHelper->filesMap = filesMap; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); auto ret = offlineCompiler.initialize(argv.size(), argv, true); EXPECT_EQ(OCLOC_SUCCESS, ret); ret = offlineCompiler.build(); @@ -2379,7 +2505,7 @@ TEST_F(OfflineCompilerTests, WhenFclNotNeededThenDontLoadIt) { EXPECT_FALSE(offlineCompiler.fclFacade->isInitialized()); EXPECT_TRUE(offlineCompiler.igcFacade->isInitialized()); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); auto expectedString = "Compilation from IR - skipping loading of FCL"; EXPECT_TRUE(hasSubstr(output, expectedString)); @@ -2389,7 +2515,7 @@ TEST_F(OfflineCompilerTests, WhenParsingBinToCharArrayThenCorrectFileIsGenerated std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -2423,7 +2549,7 @@ TEST_F(OfflineCompilerTests, GivenCppFileWhenBuildingThenBuildSucceeds) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-cpp_file", @@ -2437,18 +2563,20 @@ TEST_F(OfflineCompilerTests, GivenCppFileWhenBuildingThenBuildSucceeds) { retVal = pOfflineCompiler->build(); EXPECT_EQ(CL_SUCCESS, retVal); - EXPECT_TRUE(compilerOutputExists("copybuffer", "cpp")); - EXPECT_TRUE(compilerOutputExists("copybuffer", "bc") || compilerOutputExists("copybuffer", "spv")); - EXPECT_FALSE(compilerOutputExists("copybuffer", "gen")); - EXPECT_TRUE(compilerOutputExists("copybuffer", "bin")); + EXPECT_TRUE(compilerOutputExists("some_kernel", "cpp")); + EXPECT_TRUE(compilerOutputExists("some_kernel", "bc") || compilerOutputExists("some_kernel", "spv")); + EXPECT_FALSE(compilerOutputExists("some_kernel", "gen")); + EXPECT_TRUE(compilerOutputExists("some_kernel", "bin")); delete pOfflineCompiler; } TEST_F(OfflineCompilerTests, GivenOutputDirWhenBuildingThenBuildSucceeds) { + VariableBackup mockCreateDir(&NEO::IoFunctions::mkdirPtr, [](const char *path) -> int { return 0; }); + std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-out_dir", @@ -2461,9 +2589,9 @@ TEST_F(OfflineCompilerTests, GivenOutputDirWhenBuildingThenBuildSucceeds) { retVal = pOfflineCompiler->build(); EXPECT_EQ(CL_SUCCESS, retVal); - EXPECT_TRUE(compilerOutputExists("offline_compiler_test/copybuffer", "bc") || compilerOutputExists("offline_compiler_test/copybuffer", "spv")); - EXPECT_FALSE(compilerOutputExists("offline_compiler_test/copybuffer", "gen")); - EXPECT_TRUE(compilerOutputExists("offline_compiler_test/copybuffer", "bin")); + EXPECT_TRUE(compilerOutputExists("offline_compiler_test/some_kernel", "bc") || compilerOutputExists("offline_compiler_test/some_kernel", "spv")); + EXPECT_FALSE(compilerOutputExists("offline_compiler_test/some_kernel", "gen")); + EXPECT_TRUE(compilerOutputExists("offline_compiler_test/some_kernel", "bin")); delete pOfflineCompiler; } @@ -2473,6 +2601,7 @@ TEST_F(OfflineCompilerTests, GivenHelpOptionThenBuildDoesNotOccur) { "--help"}; testing::internal::CaptureStdout(); + pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); std::string output = testing::internal::GetCapturedStdout(); EXPECT_STRNE("", output.c_str()); @@ -2489,10 +2618,11 @@ TEST_F(OfflineCompilerTests, GivenInvalidFileWhenBuildingThenInvalidFileErrorIsR "-device", gEnvironment->devicePrefix.c_str()}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); retVal = pOfflineCompiler->build(); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_STRNE(output.c_str(), ""); EXPECT_EQ(OCLOC_INVALID_FILE, retVal); debugManager.flags.PrintDebugMessages.set(false); @@ -2507,9 +2637,10 @@ TEST_F(OfflineCompilerTests, GivenInvalidFlagWhenBuildingThenInvalidCommandLineE "-device", gEnvironment->devicePrefix.c_str()}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_STRNE(output.c_str(), ""); EXPECT_EQ(nullptr, pOfflineCompiler); EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, retVal); @@ -2523,9 +2654,10 @@ TEST_F(OfflineCompilerTests, GivenInvalidOptionsWhenBuildingThenInvalidCommandLi "-file", }; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argvA.size(), argvA, true, retVal, oclocArgHelperWithoutInput.get()); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_STRNE(output.c_str(), ""); EXPECT_EQ(nullptr, pOfflineCompiler); @@ -2538,9 +2670,10 @@ TEST_F(OfflineCompilerTests, GivenInvalidOptionsWhenBuildingThenInvalidCommandLi "-file", clFiles + "ImANaughtyFile.cl", "-device"}; - testing::internal::CaptureStdout(); + + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argvB.size(), argvB, true, retVal, oclocArgHelperWithoutInput.get()); - output = testing::internal::GetCapturedStdout(); + output = capture.getCapturedStdout(); EXPECT_STRNE(output.c_str(), ""); EXPECT_EQ(nullptr, pOfflineCompiler); EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, retVal); @@ -2552,23 +2685,39 @@ TEST_F(OfflineCompilerTests, GivenNonexistantDeviceWhenCompilingThenInvalidDevic std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", "foobar"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); pOfflineCompiler = OfflineCompiler::create(argv.size(), argv, true, retVal, oclocArgHelperWithoutInput.get()); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_STREQ(output.c_str(), "Could not determine device target: foobar.\nError: Cannot get HW Info for device foobar.\n"); EXPECT_EQ(nullptr, pOfflineCompiler); EXPECT_EQ(CL_INVALID_DEVICE, retVal); } TEST_F(OfflineCompilerTests, GivenInvalidKernelWhenBuildingThenBuildProgramFailureErrorIsReturned) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-qq", "-device", gEnvironment->devicePrefix.c_str()}; @@ -2579,12 +2728,13 @@ TEST_F(OfflineCompilerTests, GivenInvalidKernelWhenBuildingThenBuildProgramFailu EXPECT_EQ(CL_SUCCESS, retVal); gEnvironment->SetInputFileName("invalid_file_name"); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); retVal = pOfflineCompiler->build(); EXPECT_EQ(CL_BUILD_PROGRAM_FAILURE, retVal); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_STREQ(output.c_str(), ""); std::string buildLog = pOfflineCompiler->getBuildLog(); @@ -2595,11 +2745,11 @@ TEST_F(OfflineCompilerTests, GivenInvalidKernelWhenBuildingThenBuildProgramFailu delete pOfflineCompiler; } -TEST(OfflineCompilerTest, GivenAllowCachingWhenBuildingThenBinaryIsCached) { +TEST_F(OfflineCompilerTests, GivenAllowCachingWhenBuildingThenBinaryIsCached) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-allow_caching", @@ -2609,6 +2759,7 @@ TEST(OfflineCompilerTest, GivenAllowCachingWhenBuildingThenBinaryIsCached) { auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); mockOfflineCompiler->interceptCreatedDirs = true; + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; auto retVal = mockOfflineCompiler->initialize(argv.size(), argv); EXPECT_EQ(CL_SUCCESS, retVal); @@ -2619,17 +2770,19 @@ TEST(OfflineCompilerTest, GivenAllowCachingWhenBuildingThenBinaryIsCached) { EXPECT_NE(cacheMock->cacheInvoked, 0u); } -TEST(OfflineCompilerTest, GivenCachedBinaryWhenBuildToIrBinaryThenIrBinaryIsLoaded) { +TEST_F(OfflineCompilerTests, GivenCachedBinaryWhenBuildToIrBinaryThenIrBinaryIsLoaded) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-allow_caching"}; auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); + + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; mockOfflineCompiler->interceptCreatedDirs = true; auto retVal = mockOfflineCompiler->initialize(argv.size(), argv); EXPECT_EQ(CL_SUCCESS, retVal); @@ -2643,11 +2796,11 @@ TEST(OfflineCompilerTest, GivenCachedBinaryWhenBuildToIrBinaryThenIrBinaryIsLoad EXPECT_NE(0u, static_cast(mockOfflineCompiler->irBinarySize)); } -TEST(OfflineCompilerTest, GivenCachedBinaryWhenBuildSourceCodeThenSuccessIsReturned) { +TEST_F(OfflineCompilerTests, GivenCachedBinaryWhenBuildSourceCodeThenSuccessIsReturned) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-allow_caching"}; @@ -2655,6 +2808,7 @@ TEST(OfflineCompilerTest, GivenCachedBinaryWhenBuildSourceCodeThenSuccessIsRetur { auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; mockOfflineCompiler->interceptCreatedDirs = true; auto retVal = mockOfflineCompiler->initialize(argv.size(), argv); EXPECT_EQ(CL_SUCCESS, retVal); @@ -2691,6 +2845,7 @@ TEST(OfflineCompilerTest, GivenCachedBinaryWhenBuildSourceCodeThenSuccessIsRetur auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); argv.push_back("-options"); argv.push_back("-g"); + mockOfflineCompiler->interceptCreatedDirs = true; auto retVal = mockOfflineCompiler->initialize(argv.size(), argv); EXPECT_EQ(CL_SUCCESS, retVal); @@ -2705,17 +2860,19 @@ TEST(OfflineCompilerTest, GivenCachedBinaryWhenBuildSourceCodeThenSuccessIsRetur } } -TEST(OfflineCompilerTest, GivenGenBinaryWhenGenerateElfBinaryThenElfIsLoaded) { +TEST_F(OfflineCompilerTests, GivenGenBinaryWhenGenerateElfBinaryThenElfIsLoaded) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-allow_caching"}; auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); + + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; mockOfflineCompiler->interceptCreatedDirs = true; auto retVal = mockOfflineCompiler->initialize(argv.size(), argv); EXPECT_EQ(CL_SUCCESS, retVal); @@ -2731,17 +2888,20 @@ TEST(OfflineCompilerTest, GivenGenBinaryWhenGenerateElfBinaryThenElfIsLoaded) { EXPECT_NE(0u, static_cast(mockOfflineCompiler->elfBinarySize)); } -TEST(OfflineCompilerTest, givenAllowCachingWhenBuildSourceCodeThenGenBinaryIsCachedUsingHashBasedOnNonNullIrBinary) { +TEST_F(OfflineCompilerTests, givenAllowCachingWhenBuildSourceCodeThenGenBinaryIsCachedUsingHashBasedOnNonNullIrBinary) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-allow_caching"}; auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); + + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; + mockOfflineCompiler->interceptCreatedDirs = true; auto retVal = mockOfflineCompiler->initialize(argv.size(), argv); EXPECT_EQ(CL_SUCCESS, retVal); @@ -2777,9 +2937,10 @@ TEST(OfflineCompilerTest, WhenParsingCmdLineThenOptionsAreReadCorrectly) { auto mockOfflineCompiler = std::make_unique(); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); mockOfflineCompiler->parseCommandLine(argv.size(), argv); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); std::string internalOptions = mockOfflineCompiler->internalOptions; size_t found = internalOptions.find(argv.begin()[1]); @@ -2812,11 +2973,12 @@ TEST(OfflineCompilerTest, GivenUnsupportedDeviceWhenInitHardwareInfoThenInvalidD auto deviceName = "unk"; std::stringstream resString; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); auto retVal = mockOfflineCompiler->initHardwareInfo(deviceName); EXPECT_EQ(retVal, OCLOC_INVALID_DEVICE); - auto output = testing::internal::GetCapturedStdout(); + auto output = capture.getCapturedStdout(); resString << "Could not determine device target: " << deviceName << ".\n"; EXPECT_STREQ(output.c_str(), resString.str().c_str()); } @@ -2846,6 +3008,83 @@ TEST(OfflineCompilerTest, givenStatelessToStatefullOptimizationEnabledWhenDebugS } TEST(OfflineCompilerTest, GivenDelimitersWhenGettingStringThenParseIsCorrect) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "copy_buffer_to_buffer.builtin_kernel"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + VariableBackup mockFseek(&NEO::IoFunctions::fseekPtr, [](FILE *stream, long int offset, int origin) -> int { return 0; }); + VariableBackup mockFtell(&NEO::IoFunctions::ftellPtr, [](FILE *stream) -> long int { + std::string kernelSource = R"( + /* + * Copyright (C) 2020-2023 Intel Corporation + * + * SPDX-License-Identifier: MIT + * + */ + + R"===( + #define ALIGNED4(ptr) __builtin_assume(((size_t)ptr&0b11) == 0) + + __kernel void CopyBufferToBufferBytes( + const __global uchar* pSrc, + __global uchar* pDst, + uint srcOffsetInBytes, + uint dstOffsetInBytes, + uint bytesToRead ) + { + ALIGNED4(pSrc); + ALIGNED4(pDst); + pSrc += ( srcOffsetInBytes + get_global_id(0) ); + pDst += ( dstOffsetInBytes + get_global_id(0) ); + pDst[ 0 ] = pSrc[ 0 ]; + } + )===")"; + std::stringstream fileStream(kernelSource); + fileStream.seekg(0, std::ios::end); + return static_cast(fileStream.tellg()); + }); + VariableBackup mockFread(&NEO::IoFunctions::freadPtr, [](void *ptr, size_t size, size_t count, FILE *stream) -> size_t { + std::string kernelSource = R"( + /* + * Copyright (C) 2020-2023 Intel Corporation + * + * SPDX-License-Identifier: MIT + * + */ + + R"===( + #define ALIGNED4(ptr) __builtin_assume(((size_t)ptr&0b11) == 0) + + __kernel void CopyBufferToBufferBytes( + const __global uchar* pSrc, + __global uchar* pDst, + uint srcOffsetInBytes, + uint dstOffsetInBytes, + uint bytesToRead ) + { + ALIGNED4(pSrc); + ALIGNED4(pDst); + pSrc += ( srcOffsetInBytes + get_global_id(0) ); + pDst += ( dstOffsetInBytes + get_global_id(0) ); + pDst[ 0 ] = pSrc[ 0 ]; + } + )===")"; + std::stringstream fileStream(kernelSource); + size_t totalBytes = size * count; + fileStream.read(static_cast(ptr), totalBytes); + return static_cast(fileStream.gcount() / size); + }); + auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); @@ -2896,10 +3135,11 @@ TEST(OfflineCompilerTest, GivenValidParamWhenGettingHardwareInfoThenSuccessIsRet auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); EXPECT_EQ(CL_INVALID_DEVICE, mockOfflineCompiler->initHardwareInfo("invalid")); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(PRODUCT_FAMILY::IGFX_UNKNOWN, mockOfflineCompiler->getHardwareInfo().platform.eProductFamily); EXPECT_EQ(CL_SUCCESS, mockOfflineCompiler->initHardwareInfo(gEnvironment->devicePrefix.c_str())); @@ -2967,17 +3207,18 @@ TEST(OfflineCompilerTest, givenValidSizeAndInvalidLogPointerWhenUpdatingBuildLog EXPECT_TRUE(buildLog.empty()) << buildLog; } -TEST(OfflineCompilerTest, GivenSourceCodeWhenBuildingThenSuccessIsReturned) { +TEST_F(OfflineCompilerTests, GivenSourceCodeWhenBuildingThenSuccessIsReturned) { auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; auto retVal = mockOfflineCompiler->buildSourceCode(); EXPECT_EQ(CL_INVALID_PROGRAM, retVal); std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -2994,11 +3235,11 @@ TEST(OfflineCompilerTest, GivenSourceCodeWhenBuildingThenSuccessIsReturned) { EXPECT_NE(0u, mockOfflineCompiler->genBinarySize); } -TEST(OfflineCompilerTest, givenSpvOnlyOptionPassedWhenCmdLineParsedThenGenerateOnlySpvFile) { +TEST_F(OfflineCompilerTests, givenSpvOnlyOptionPassedWhenCmdLineParsedThenGenerateOnlySpvFile) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-output", "myOutputFileName", "-spv_only", @@ -3008,6 +3249,7 @@ TEST(OfflineCompilerTest, givenSpvOnlyOptionPassedWhenCmdLineParsedThenGenerateO auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; auto retVal = mockOfflineCompiler->initialize(argv.size(), argv); EXPECT_EQ(CL_SUCCESS, retVal); @@ -3023,7 +3265,7 @@ TEST(OfflineCompilerTest, givenSpvOnlyOptionPassedWhenCmdLineParsedThenGenerateO EXPECT_FALSE(compilerOutputExists("myOutputFileName", "gen")); } -TEST(OfflineCompilerTest, GivenKernelWhenNoCharAfterKernelSourceThenBuildWithSuccess) { +TEST_F(OfflineCompilerTests, GivenKernelWhenNoCharAfterKernelSourceThenBuildWithSuccess) { auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); @@ -3263,9 +3505,10 @@ TEST(OfflineCompilerTest, givenLlvmInputOptionPassedWhenCmdLineParsedThenInputFi auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); mockOfflineCompiler->parseCommandLine(argv.size(), argv); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_NE(0u, output.size()); @@ -3286,9 +3529,10 @@ TEST(OfflineCompilerTest, givenSpirvInputOptionPassedWhenCmdLineParsedThenInputF auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); mockOfflineCompiler->parseCommandLine(argv.size(), argv); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_NE(0u, output.size()); EXPECT_TRUE(mockOfflineCompiler->inputFileSpirV()); @@ -3299,7 +3543,7 @@ TEST(OfflineCompilerTest, givenDefaultOfflineCompilerObjectWhenNoOptionsAreChang EXPECT_FALSE(mockOfflineCompiler->inputFileSpirV()); } -TEST(OfflineCompilerTest, givenSpirvRepresentationInputWhenBuildSourceCodeIsCalledThenProperTranslationContextIsUsed) { +TEST_F(OfflineCompilerTests, givenSpirvRepresentationInputWhenBuildSourceCodeIsCalledThenProperTranslationContextIsUsed) { MockOfflineCompiler mockOfflineCompiler; Source source{reinterpret_cast(spirvMagic.data()), spirvMagic.size(), "some_file.spv"}; @@ -3333,7 +3577,7 @@ TEST(OfflineCompilerTest, givenSpirvRepresentationInputWhenBuildSourceCodeIsCall ASSERT_EQ(expectedTranslation, mockIgcOclDeviceCtx->requestedTranslationCtxs[0]); } -TEST(OfflineCompilerTest, givenLlvmBcRepresentationInputWhenBuildSourceCodeIsCalledThenProperTranslationContextIsUsed) { +TEST_F(OfflineCompilerTests, givenLlvmBcRepresentationInputWhenBuildSourceCodeIsCalledThenProperTranslationContextIsUsed) { MockOfflineCompiler mockOfflineCompiler; Source source{reinterpret_cast(llvmBcMagic.data()), llvmBcMagic.size(), "some_file.bc"}; @@ -3373,7 +3617,7 @@ TEST(OfflineCompilerTest, givenLlvmBcRepresentationInputWhenBuildSourceCodeIsCal ASSERT_EQ(expectedTranslation, mockIgcOclDeviceCtx->requestedTranslationCtxs[0]); } -TEST(OfflineCompilerTest, givenUseLlvmBcFlagWhenBuildingIrBinaryThenProperTranslationContextIsUsed) { +TEST_F(OfflineCompilerTests, givenUseLlvmBcFlagWhenBuildingIrBinaryThenProperTranslationContextIsUsed) { MockOfflineCompiler mockOfflineCompiler; std::vector argv = { "ocloc", @@ -3399,7 +3643,7 @@ TEST(OfflineCompilerTest, givenUseLlvmBcFlagWhenBuildingIrBinaryThenProperTransl EXPECT_EQ(expectedTranslation, mockFclOclDeviceCtx->requestedTranslationCtxs[0]); } -TEST(OfflineCompilerTest, givenBinaryInputThenDontTruncateSourceAtFirstZero) { +TEST_F(OfflineCompilerTests, givenBinaryInputThenDontTruncateSourceAtFirstZero) { std::vector argvLlvm = {"ocloc", "-llvm_input", "-file", "binary_with_zeroes", "-qq", "-device", gEnvironment->devicePrefix.c_str()}; auto mockOfflineCompiler = std::make_unique(); @@ -3420,6 +3664,21 @@ TEST(OfflineCompilerTest, givenBinaryInputThenDontTruncateSourceAtFirstZero) { } TEST(OfflineCompilerTest, givenSpirvInputFileWhenCmdLineHasOptionsThenCorrectOptionsArePassedToCompiler) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + char data[] = {1, 2, 3, 4, 5, 6, 7, 8}; MockCompilerDebugVars igcDebugVars(gEnvironment->igcDebugVars); igcDebugVars.binaryToReturn = data; @@ -3452,11 +3711,11 @@ TEST(OfflineCompilerTest, givenSpirvInputFileWhenCmdLineHasOptionsThenCorrectOpt NEO::setIgcDebugVars(gEnvironment->igcDebugVars); } -TEST(OfflineCompilerTest, givenOutputFileOptionWhenSourceIsCompiledThenOutputFileHasCorrectName) { +TEST_F(OfflineCompilerTests, givenOutputFileOptionWhenSourceIsCompiledThenOutputFileHasCorrectName) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-output", "myOutputFileName", "-device", @@ -3465,6 +3724,7 @@ TEST(OfflineCompilerTest, givenOutputFileOptionWhenSourceIsCompiledThenOutputFil auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; int retVal = mockOfflineCompiler->initialize(argv.size(), argv); EXPECT_EQ(CL_SUCCESS, retVal); @@ -3480,11 +3740,11 @@ TEST(OfflineCompilerTest, givenOutputFileOptionWhenSourceIsCompiledThenOutputFil EXPECT_FALSE(compilerOutputExists("myOutputFileName", "gen")); } -TEST(OfflineCompilerTest, givenDebugDataAvailableWhenSourceIsBuiltThenDebugDataFileIsCreated) { +TEST_F(OfflineCompilerTests, givenDebugDataAvailableWhenSourceIsBuiltThenDebugDataFileIsCreated) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-output", "myOutputFileName", "-device", @@ -3500,6 +3760,7 @@ TEST(OfflineCompilerTest, givenDebugDataAvailableWhenSourceIsBuiltThenDebugDataF auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; int retVal = mockOfflineCompiler->initialize(argv.size(), argv); EXPECT_EQ(CL_SUCCESS, retVal); @@ -3528,9 +3789,10 @@ TEST(OfflineCompilerTest, givenInternalOptionsWhenCmdLineParsedThenOptionsAreApp auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); mockOfflineCompiler->parseCommandLine(argv.size(), argv); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_NE(0u, output.size()); @@ -3549,9 +3811,10 @@ TEST(OfflineCompilerTest, givenOptionsWhenCmdLineParsedThenOptionsAreAppendedToO auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); mockOfflineCompiler->parseCommandLine(argv.size(), argv); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_NE(0u, output.size()); @@ -3584,7 +3847,7 @@ TEST(OfflineCompilerTest, givenDeviceOptionsForCompiledDeviceWhenCmdLineParsedTh EXPECT_TRUE(hasSubstr(options, std::string("devOptions"))); } -TEST(OfflineCompilerTest, givenDeviceOptionsWithDeprecatedDeviceAcronymWhenCmdLineParsedThenDeviceNameIsRecognized) { +TEST_F(OfflineCompilerTests, givenDeviceOptionsWithDeprecatedDeviceAcronymWhenCmdLineParsedThenDeviceNameIsRecognized) { auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); @@ -3599,7 +3862,7 @@ TEST(OfflineCompilerTest, givenDeviceOptionsWithDeprecatedDeviceAcronymWhenCmdLi "ocloc", "compile", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", deviceName.c_str(), "-options", @@ -3608,9 +3871,11 @@ TEST(OfflineCompilerTest, givenDeviceOptionsWithDeprecatedDeviceAcronymWhenCmdLi deviceName.c_str(), "devOptions"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; const auto result = mockOfflineCompiler->parseCommandLine(argv.size(), argv); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(0u, output.size()); EXPECT_NE(OCLOC_INVALID_COMMAND_LINE, result); @@ -3620,12 +3885,12 @@ TEST(OfflineCompilerTest, givenDeviceOptionsWithDeprecatedDeviceAcronymWhenCmdLi EXPECT_FALSE(hasSubstr(output, expectedErrorMessage.str())); } -TEST(OfflineCompilerTest, givenUnknownDeviceAcronymInDeviceOptionsWhenParsingCommandLineThenErrorLogIsPrintedAndFailureIsReturned) { +TEST_F(OfflineCompilerTests, givenUnknownDeviceAcronymInDeviceOptionsWhenParsingCommandLineThenErrorLogIsPrintedAndFailureIsReturned) { std::vector argv = { "ocloc", "compile", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-options", @@ -3643,9 +3908,11 @@ TEST(OfflineCompilerTest, givenUnknownDeviceAcronymInDeviceOptionsWhenParsingCom auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); - testing::internal::CaptureStdout(); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; + StdoutCapture capture; + capture.captureStdout(); const auto result = mockOfflineCompiler->parseCommandLine(argv.size(), argv); - const std::string output = testing::internal::GetCapturedStdout(); + const std::string output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, result); @@ -3668,9 +3935,10 @@ TEST(OfflineCompilerTest, givenDeviceOptionsInWrongFormatWhenCmdLineParsedThenDe auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); mockOfflineCompiler->parseCommandLine(argv.size(), argv); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_NE(0u, output.size()); @@ -3840,9 +4108,10 @@ TEST(OfflineCompilerTest, givenDeviceOptionsForMultipleDevicesSeparatedByCommasW productForDeviceOptions1.c_str(), "devOptions2"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = mockOfflineCompiler->parseCommandLine(argv.size(), argv); - const std::string output = testing::internal::GetCapturedStdout(); + const std::string output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, result); EXPECT_NE(0u, output.size()); @@ -3854,11 +4123,11 @@ TEST(OfflineCompilerTest, givenDeviceOptionsForMultipleDevicesSeparatedByCommasW EXPECT_TRUE(hasSubstr(output, expectedErrorMessage.str())); } -TEST(OfflineCompilerTest, givenDashOOptionWhenCmdLineParsedThenBinaryOutputNameIsSet) { +TEST_F(OfflineCompilerTests, givenDashOOptionWhenCmdLineParsedThenBinaryOutputNameIsSet) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-o", "nameOfFile.bin", "-device", @@ -3867,9 +4136,11 @@ TEST(OfflineCompilerTest, givenDashOOptionWhenCmdLineParsedThenBinaryOutputNameI auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); - testing::internal::CaptureStdout(); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; + StdoutCapture capture; + capture.captureStdout(); auto retVal = mockOfflineCompiler->parseCommandLine(argv.size(), argv); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_SUCCESS, retVal); EXPECT_EQ(0u, output.size()); @@ -3877,11 +4148,11 @@ TEST(OfflineCompilerTest, givenDashOOptionWhenCmdLineParsedThenBinaryOutputNameI EXPECT_EQ("nameOfFile.bin", mockOfflineCompiler->binaryOutputFile); } -TEST(OfflineCompilerTest, givenDashOAndOtherInvalidOptionsWhenCmdLineParsedThenErrorReturned) { +TEST_F(OfflineCompilerTests, givenDashOAndOtherInvalidOptionsWhenCmdLineParsedThenErrorReturned) { std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-o", "nameOfFile.bin", "-device", @@ -3898,9 +4169,11 @@ TEST(OfflineCompilerTest, givenDashOAndOtherInvalidOptionsWhenCmdLineParsedThenE auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); - testing::internal::CaptureStdout(); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; + StdoutCapture capture; + capture.captureStdout(); auto retVal = mockOfflineCompiler->parseCommandLine(argv.size(), argv); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, retVal); EXPECT_NE(0u, output.size()); @@ -3911,7 +4184,7 @@ TEST(OfflineCompilerTest, givenDashOAndOtherInvalidOptionsWhenCmdLineParsedThenE std::vector argv2 = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-o", "nameOfFile.bin", "-output", @@ -3922,9 +4195,11 @@ TEST(OfflineCompilerTest, givenDashOAndOtherInvalidOptionsWhenCmdLineParsedThenE auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); - testing::internal::CaptureStdout(); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; + StdoutCapture capture; + capture.captureStdout(); auto retVal = mockOfflineCompiler->parseCommandLine(argv2.size(), argv2); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, retVal); EXPECT_NE(0u, output.size()); @@ -3933,15 +4208,30 @@ TEST(OfflineCompilerTest, givenDashOAndOtherInvalidOptionsWhenCmdLineParsedThenE } TEST(OfflineCompilerTest, givenInputOptionsAndInternalOptionsFilesWhenOfflineCompilerIsInitializedThenCorrectOptionsAreSetAndRemainAfterBuild) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { + std::filesystem::path filePath = filename; + std::string fileNameWithExtension = filePath.filename().string(); + + std::vector expectedtedFiles = { + "some_kernel.cl"}; + + auto itr = std::find(expectedtedFiles.begin(), expectedtedFiles.end(), std::string(fileNameWithExtension)); + if (itr != expectedtedFiles.end()) { + return reinterpret_cast(0x40); + } + return NULL; + }); + VariableBackup mockFclose(&NEO::IoFunctions::fclosePtr, [](FILE *stream) -> int { return 0; }); + auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); const char kernelSource[] = R"===( /* - * Copyright (C) 2018-2021 Intel Corporation - * - * SPDX-License-Identifier: MIT - * - */ +* Copyright (C) 2018-2021 Intel Corporation +* +* SPDX-License-Identifier: MIT +* +*/ __kernel void shouldfail(global ushort *dst) { // idx and dummy are not defined, compiler should fail the build. @@ -3953,11 +4243,11 @@ __kernel void shouldfail(global ushort *dst) { const char internalOptions[] = R"===( /* - * Copyright (C) 2018-2021 Intel Corporation - * - * SPDX-License-Identifier: MIT - * - */ +* Copyright (C) 2018-2021 Intel Corporation +* +* SPDX-License-Identifier: MIT +* +*/ -shouldfailInternalOptions )==="; @@ -3966,11 +4256,11 @@ __kernel void shouldfail(global ushort *dst) { const char options[] = R"===( /* - * Copyright (C) 2018-2021 Intel Corporation - * - * SPDX-License-Identifier: MIT - * - */ +* Copyright (C) 2018-2021 Intel Corporation +* +* SPDX-License-Identifier: MIT +* +*/ -shouldfailOptions )==="; @@ -3985,10 +4275,11 @@ __kernel void shouldfail(global ushort *dst) { "-device", gEnvironment->devicePrefix.c_str()}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); auto retVal = Ocloc::Commands::compile(mockOfflineCompiler->argHelper, args); EXPECT_NE(retVal, OCLOC_SUCCESS); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_FALSE(output.find("Building with options:\n" "-shouldfailOptions") != std::string::npos); @@ -4009,10 +4300,11 @@ __kernel void shouldfail(global ushort *dst) { "-device", gEnvironment->devicePrefix.c_str()}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); auto retVal = Ocloc::Commands::compile(mockOfflineCompiler->argHelper, args); EXPECT_NE(retVal, OCLOC_SUCCESS); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_TRUE(output.find("Building with options:\n" "-shouldfailOptions") != std::string::npos); @@ -4037,10 +4329,11 @@ __kernel void shouldfail(global ushort *dst) { "-device", gEnvironment->devicePrefix.c_str()}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); auto retVal = Ocloc::Commands::compile(mockOfflineCompiler->argHelper, args); EXPECT_NE(retVal, OCLOC_SUCCESS); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_FALSE(output.find("Building with options:\n" "-invalid_options") != std::string::npos); @@ -4053,17 +4346,18 @@ __kernel void shouldfail(global ushort *dst) { } } -TEST(OfflineCompilerTest, givenInputOptionsAndOclockOptionsFileWithForceStosOptWhenOfflineCompilerIsInitializedThenCompilerOptionGreaterThan4gbBuffersRequiredIsNotApplied) { +TEST_F(OfflineCompilerTests, givenInputOptionsAndOclockOptionsFileWithForceStosOptWhenOfflineCompilerIsInitializedThenCompilerOptionGreaterThan4gbBuffersRequiredIsNotApplied) { auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); - ASSERT_TRUE(fileExists(clFiles + "stateful_copy_buffer_ocloc_options.txt")); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; + mockOfflineCompiler->uniqueHelper->filesMap["some_kernel_ocloc_options.txt"] = "-force_stos_opt"; std::vector argv = { "ocloc", "-q", "-file", - clFiles + "stateful_copy_buffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -4184,6 +4478,8 @@ TEST_F(OfflineCompilerBindlessOptionsTests, givenNullReleaseHelperWhenAppendExtr } TEST(OfflineCompilerTest, givenNonExistingFilenameWhenUsedToReadOptionsThenReadOptionsFromFileReturnsFalse) { + VariableBackup mockFopen(&NEO::IoFunctions::fopenPtr, [](const char *filename, const char *mode) -> FILE * { return NULL; }); + std::string options; std::string file("non_existing_file"); ASSERT_FALSE(fileExists(file.c_str())); @@ -4286,9 +4582,10 @@ TEST(OfflineCompilerTest, givenEnabledOptsSuffixWhenGenerateOptsSuffixIsCalledTh EXPECT_STREQ("A_B_C", suffix.c_str()); } -TEST(OfflineCompilerTest, givenCompilerWhenBuildSourceCodeFailsThenGenerateElfBinaryAndWriteOutAllFilesAreCalled) { +TEST_F(OfflineCompilerTests, givenCompilerWhenBuildSourceCodeFailsThenGenerateElfBinaryAndWriteOutAllFilesAreCalled) { MockOfflineCompiler compiler; compiler.overrideBuildSourceCodeStatus = true; + compiler.uniqueHelper->filesMap = filesMap; auto expectedError = OCLOC_BUILD_PROGRAM_FAILURE; compiler.buildSourceCodeStatus = expectedError; @@ -4296,7 +4593,7 @@ TEST(OfflineCompilerTest, givenCompilerWhenBuildSourceCodeFailsThenGenerateElfBi EXPECT_EQ(0u, compiler.generateElfBinaryCalled); EXPECT_EQ(0u, compiler.writeOutAllFilesCalled); - compiler.inputFile = clFiles + "copybuffer.cl"; + compiler.inputFile = clCopybufferFilename.c_str(); auto status = compiler.build(); EXPECT_EQ(expectedError, status); @@ -4313,11 +4610,11 @@ TEST(OfflineCompilerTest, givenDeviceSpecificKernelFileWhenCompilerIsInitialized const char options[] = R"===( /* - * Copyright (C) 2024 Intel Corporation - * - * SPDX-License-Identifier: MIT - * - */ +* Copyright (C) 2024 Intel Corporation +* +* SPDX-License-Identifier: MIT +* +*/ -cl-opt-disable -DDEF_WAS_SPECIFIED=1 -DARGS=", const __global int *arg1, float arg2, const __global int *arg3, float arg4" )==="; @@ -4337,15 +4634,16 @@ TEST(OfflineCompilerTest, givenDeviceSpecificKernelFileWhenCompilerIsInitialized EXPECT_STREQ("-cl-opt-disable -DDEF_WAS_SPECIFIED=1 -DARGS=\", const __global int *arg1, float arg2, const __global int *arg3, float arg4\"", mockOfflineCompiler->options.c_str()); } -TEST(OfflineCompilerTest, givenHexadecimalRevisionIdWhenCompilerIsInitializedThenPassItToHwInfo) { +TEST_F(OfflineCompilerTests, givenHexadecimalRevisionIdWhenCompilerIsInitializedThenPassItToHwInfo) { auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; std::vector argv = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-revision_id", @@ -4356,18 +4654,19 @@ TEST(OfflineCompilerTest, givenHexadecimalRevisionIdWhenCompilerIsInitializedThe EXPECT_EQ(mockOfflineCompiler->hwInfo.platform.usRevId, 17); } -TEST(OfflineCompilerTest, givenDebugVariableSetWhenInitializingThenOverrideRevision) { +TEST_F(OfflineCompilerTests, givenDebugVariableSetWhenInitializingThenOverrideRevision) { DebugManagerStateRestore stateRestore; debugManager.flags.OverrideRevision.set(123); auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; std::vector argv = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-revision_id", @@ -4378,15 +4677,16 @@ TEST(OfflineCompilerTest, givenDebugVariableSetWhenInitializingThenOverrideRevis EXPECT_EQ(mockOfflineCompiler->hwInfo.platform.usRevId, 123); } -TEST(OfflineCompilerTest, givenDecimalRevisionIdWhenCompilerIsInitializedThenPassItToHwInfo) { +TEST_F(OfflineCompilerTests, givenDecimalRevisionIdWhenCompilerIsInitializedThenPassItToHwInfo) { auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; std::vector argv = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-revision_id", @@ -4397,15 +4697,16 @@ TEST(OfflineCompilerTest, givenDecimalRevisionIdWhenCompilerIsInitializedThenPas EXPECT_EQ(mockOfflineCompiler->hwInfo.platform.usRevId, 17); } -TEST(OfflineCompilerTest, givenNoRevisionIdWhenCompilerIsInitializedThenHwInfoHasDefaultRevId) { +TEST_F(OfflineCompilerTests, givenNoRevisionIdWhenCompilerIsInitializedThenHwInfoHasDefaultRevId) { auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; std::vector argv = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -4425,15 +4726,16 @@ TEST(OfflineCompilerTest, givenEmptyDeviceNameWhenInitializingHardwareInfoThenIn EXPECT_EQ(OCLOC_INVALID_DEVICE, result); } -TEST(OfflineCompilerTest, whenDeviceIsSpecifiedThenDefaultConfigFromTheDeviceIsUsed) { +TEST_F(OfflineCompilerTests, whenDeviceIsSpecifiedThenDefaultConfigFromTheDeviceIsUsed) { auto mockOfflineCompiler = std::unique_ptr(new MockOfflineCompiler()); ASSERT_NE(nullptr, mockOfflineCompiler); + mockOfflineCompiler->uniqueHelper->filesMap = filesMap; std::vector argv = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -4458,7 +4760,7 @@ TEST(OfflineCompilerTest, whenDeviceIsSpecifiedThenDefaultConfigFromTheDeviceIsU EXPECT_EQ(euPerSubSliceCount * subSlicePerSliceCount * sliceCount, hwInfo.gtSystemInfo.EUCount); } -TEST(OclocCompile, whenDetectedPotentialInputTypeMismatchThenEmitsWarning) { +TEST_F(OfflineCompilerTests, whenDetectedPotentialInputTypeMismatchThenEmitsWarning) { std::string sourceOclC = "__kernel void k() { }"; std::string sourceLlvmBc = NEO::llvmBcMagic.str(); std::string sourceSpirv = NEO::spirvMagic.str(); @@ -4496,12 +4798,13 @@ TEST(OclocCompile, whenDetectedPotentialInputTypeMismatchThenEmitsWarning) { }; { MockOfflineCompiler ocloc; + ocloc.uniqueHelper->filesMap = filesMap; std::vector argv = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str()}; @@ -4512,7 +4815,8 @@ TEST(OclocCompile, whenDetectedPotentialInputTypeMismatchThenEmitsWarning) { int caseNum = 0; for (auto &c : cases) { - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); ocloc.inputCodeType = IGC::CodeType::oclC; if (c.isLlvm) { @@ -4529,7 +4833,7 @@ TEST(OclocCompile, whenDetectedPotentialInputTypeMismatchThenEmitsWarning) { auto log = ocloc.argHelper->getPrinterRef().getLog().str(); ocloc.clearLog(); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); if (c.expectedWarning.empty()) { for (auto &w : allWarnings) { @@ -4544,14 +4848,15 @@ TEST(OclocCompile, whenDetectedPotentialInputTypeMismatchThenEmitsWarning) { } } -TEST(OclocCompile, givenCommandLineWithoutDeviceWhenCompilingToSpirvThenSucceedsButUsesEmptyExtensionString) { +TEST_F(OfflineCompilerTests, givenCommandLineWithoutDeviceWhenCompilingToSpirvThenSucceedsButUsesEmptyExtensionString) { MockOfflineCompiler ocloc; + ocloc.uniqueHelper->filesMap = filesMap; std::vector argv = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-spv_only"}; int retVal = ocloc.initialize(argv.size(), argv); @@ -4563,14 +4868,15 @@ TEST(OclocCompile, givenCommandLineWithoutDeviceWhenCompilingToSpirvThenSucceeds EXPECT_TRUE(hasSubstr(ocloc.internalOptions, " -D__IMAGE_SUPPORT__=1")); } -TEST(OclocCompile, givenDeviceAndInternalOptionsOptionWhenCompilingToSpirvThenInternalOptionsAreSetCorrectly) { +TEST_F(OfflineCompilerTests, givenDeviceAndInternalOptionsOptionWhenCompilingToSpirvThenInternalOptionsAreSetCorrectly) { MockOfflineCompiler ocloc; + ocloc.uniqueHelper->filesMap = filesMap; std::vector argv = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-internal_options", "-cl-ext=+custom_param", "-device", @@ -4586,14 +4892,15 @@ TEST(OclocCompile, givenDeviceAndInternalOptionsOptionWhenCompilingToSpirvThenIn EXPECT_TRUE(containsRegex(ocloc.internalOptions, regexToMatch)); } -TEST(OclocCompile, givenNoDeviceAndInternalOptionsOptionWhenCompilingToSpirvThenInternalOptionsAreSetCorrectly) { +TEST_F(OfflineCompilerTests, givenNoDeviceAndInternalOptionsOptionWhenCompilingToSpirvThenInternalOptionsAreSetCorrectly) { MockOfflineCompiler ocloc; + ocloc.uniqueHelper->filesMap = filesMap; std::vector argv = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-internal_options", "-cl-ext=+custom_param", "-spv_only"}; @@ -4619,8 +4926,11 @@ TEST(OclocCompile, givenPackedDeviceBinaryFormatWhenGeneratingElfBinaryThenItIsR EXPECT_EQ(0, memcmp(zebin.storage.data(), ocloc.elfBinary.data(), zebin.storage.size())); } -TEST(OclocCompile, givenSpirvInputThenDontGenerateSpirvFile) { +TEST_F(OfflineCompilerTests, givenSpirvInputThenDontGenerateSpirvFile) { + VariableBackup mockCreateDir(&NEO::IoFunctions::mkdirPtr, [](const char *path) -> int { return 0; }); + MockOfflineCompiler ocloc; + ocloc.uniqueHelper->filesMap = filesMap; Source source{reinterpret_cast(spirvMagic.data()), spirvMagic.size(), "some_file.spv"}; static_cast(ocloc.argHelper)->inputs.push_back(source); @@ -4644,14 +4954,15 @@ TEST(OclocCompile, givenSpirvInputThenDontGenerateSpirvFile) { EXPECT_FALSE(compilerOutputExists("offline_compiler_test/some_file", "spv")); } -TEST(OclocCompile, givenFormatFlagWithKnownFormatPassedThenEnforceSpecifiedFormatAccordingly) { +TEST_F(OfflineCompilerTests, givenFormatFlagWithKnownFormatPassedThenEnforceSpecifiedFormatAccordingly) { MockOfflineCompiler ocloc; + ocloc.uniqueHelper->filesMap = filesMap; std::vector argvEnforcedFormatPatchtokens = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-spv_only", "--format", "patchtokens"}; @@ -4660,7 +4971,7 @@ TEST(OclocCompile, givenFormatFlagWithKnownFormatPassedThenEnforceSpecifiedForma "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-spv_only", "--format", "zebin"}; @@ -4675,14 +4986,15 @@ TEST(OclocCompile, givenFormatFlagWithKnownFormatPassedThenEnforceSpecifiedForma EXPECT_TRUE(hasSubstr(ocloc.internalOptions, std::string{CompilerOptions::disableZebin})); } -HWTEST2_F(MockOfflineCompilerTests, givenNoFormatFlagSpecifiedWhenOclocInitializeThenZebinFormatIsEnforcedByDefault, HasOclocZebinFormatEnforced) { +HWTEST2_F(OfflineCompilerTests, givenNoFormatFlagSpecifiedWhenOclocInitializeThenZebinFormatIsEnforcedByDefault, HasOclocZebinFormatEnforced) { MockOfflineCompiler ocloc; + ocloc.uniqueHelper->filesMap = filesMap; std::vector argvNoFormatFlag = { "ocloc", "-q", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-spv_only", "-device", gEnvironment->devicePrefix.c_str()}; @@ -4692,20 +5004,22 @@ HWTEST2_F(MockOfflineCompilerTests, givenNoFormatFlagSpecifiedWhenOclocInitializ EXPECT_FALSE(hasSubstr(ocloc.internalOptions, std::string{CompilerOptions::disableZebin})); } -TEST(OclocCompile, givenFormatFlagWithUnknownFormatPassedThenPrintWarning) { +TEST_F(OfflineCompilerTests, givenFormatFlagWithUnknownFormatPassedThenPrintWarning) { MockOfflineCompiler ocloc; + ocloc.uniqueHelper->filesMap = filesMap; std::vector argvUnknownFormatEnforced = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-spv_only", "--format", "banana"}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = ocloc.initialize(argvUnknownFormatEnforced.size(), argvUnknownFormatEnforced); - const auto output = testing::internal::GetCapturedStdout(); + const auto output = capture.getCapturedStdout(); ASSERT_EQ(0, retVal); const auto expectedOutput{"Invalid format passed: banana. Ignoring.\n"}; @@ -4733,28 +5047,30 @@ TEST(OfflineCompilerTest, GivenDebugFlagWhenSetStatelessToStatefulBufferOffsetFl } } -TEST(OclocCompile, GivenStatefulAddressModeWhenInvalidArgsPAssedThenErrorIsReturned) { +TEST_F(OfflineCompilerTests, GivenStatefulAddressModeWhenInvalidArgsPAssedThenErrorIsReturned) { MockOfflineCompiler ocloc; + ocloc.uniqueHelper->filesMap = filesMap; std::vector argvA = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-stateful_address_mode", "wrong"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = ocloc.initialize(argvA.size(), argvA); ASSERT_EQ(OCLOC_INVALID_COMMAND_LINE, retVal); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_STRNE(output.c_str(), ""); std::vector argvB = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-stateful_address_mode", @@ -4764,58 +5080,63 @@ TEST(OclocCompile, GivenStatefulAddressModeWhenInvalidArgsPAssedThenErrorIsRetur MockOfflineCompiler ocloc2; - testing::internal::CaptureStdout(); + capture.captureStdout(); retVal = ocloc2.initialize(argvB.size(), argvB); ASSERT_EQ(OCLOC_INVALID_COMMAND_LINE, retVal); - output = testing::internal::GetCapturedStdout(); + output = capture.getCapturedStdout(); EXPECT_STRNE(output.c_str(), ""); } -TEST(OclocCompile, GivenInvalidHeaplessModeOptionWhenOclocArgsAreParsedThenErrorIsReturned) { +TEST_F(OfflineCompilerTests, GivenInvalidHeaplessModeOptionWhenOclocArgsAreParsedThenErrorIsReturned) { MockOfflineCompiler ocloc; + ocloc.uniqueHelper->filesMap = filesMap; std::vector args = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-heapless_mode", "invalid"}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = ocloc.parseCommandLine(args.size(), args); EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, retVal); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_STRNE(output.c_str(), ""); } -TEST(OclocCompile, GivenValidHeaplessModeOptionWhenOclocArgsAreParsedThenSuccessIsReturned) { +TEST_F(OfflineCompilerTests, GivenValidHeaplessModeOptionWhenOclocArgsAreParsedThenSuccessIsReturned) { for (auto heaplessMode : {"enable", "disable", "default"}) { MockOfflineCompiler ocloc; + ocloc.uniqueHelper->filesMap = filesMap; std::vector args = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-heapless_mode", heaplessMode}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = ocloc.parseCommandLine(args.size(), args); EXPECT_EQ(OCLOC_SUCCESS, retVal); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_STREQ(output.c_str(), ""); } } -TEST(OclocCompile, GivenStatefulAddressModeSetToBindlessWhenBuildThenBindlessModeInternalOptionsAreAdded) { +TEST_F(OfflineCompilerTests, GivenStatefulAddressModeSetToBindlessWhenBuildThenBindlessModeInternalOptionsAreAdded) { MockOfflineCompiler ocloc; + ocloc.uniqueHelper->filesMap = filesMap; std::vector argv = { "ocloc", "-file", - clFiles + "copybuffer.cl", + clCopybufferFilename.c_str(), "-device", gEnvironment->devicePrefix.c_str(), "-stateful_address_mode", @@ -4844,9 +5165,10 @@ TEST(OclocArgHelperTest, GivenOutputSuppressMessagesAndSaveItToFile) { EXPECT_TRUE(helper->messagePrinter.isSuppressed()); ConstStringRef printMsg = "Hello world!"; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); helper->printf(printMsg.data()); - std::string capturedStdout = testing::internal::GetCapturedStdout(); + std::string capturedStdout = capture.getCapturedStdout(); EXPECT_TRUE(capturedStdout.empty()); helper.reset(); // Delete helper. Destructor saves data to output @@ -4933,9 +5255,10 @@ TEST(OclocArgHelperTest, GivenNoOutputPrintMessages) { nullptr, nullptr, nullptr, nullptr); EXPECT_FALSE(helper.messagePrinter.isSuppressed()); ConstStringRef printMsg = "Hello world!"; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); helper.printf(printMsg.data()); - std::string capturedStdout = testing::internal::GetCapturedStdout(); + std::string capturedStdout = capture.getCapturedStdout(); EXPECT_STREQ(printMsg.data(), capturedStdout.c_str()); } @@ -5245,9 +5568,10 @@ __kernel void CopyBuffer(__global unsigned int *src, __global unsigned int *dst) "-device", gEnvironment->devicePrefix.c_str()}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = mockOfflineCompiler->initialize(argv.size(), argv); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_NE(retVal, OCLOC_SUCCESS); EXPECT_TRUE(output.find("Failed with ocloc options from file:\n" @@ -5296,13 +5620,14 @@ __kernel void CopyBuffer(__global unsigned int *src, __global unsigned int *dst) "-device", gEnvironment->devicePrefix.c_str()}; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); int retVal = mockOfflineCompiler->initialize(argv.size(), argv); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); EXPECT_NE(retVal, OCLOC_SUCCESS); EXPECT_FALSE(output.find("Failed with ocloc options from file:\n" "-invalid_ocloc_option") != std::string::npos); EXPECT_FALSE(output.find("Building with ocloc options:") != std::string::npos); } -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/opencl/test/unit_test/offline_compiler/offline_compiler_tests.h b/opencl/test/unit_test/offline_compiler/offline_compiler_tests.h index bad438dcd2..96c0e9d56e 100644 --- a/opencl/test/unit_test/offline_compiler/offline_compiler_tests.h +++ b/opencl/test/unit_test/offline_compiler/offline_compiler_tests.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018-2023 Intel Corporation + * Copyright (C) 2018-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -10,27 +10,45 @@ #include "shared/offline_compiler/source/multi_command.h" #include "shared/offline_compiler/source/ocloc_api.h" #include "shared/offline_compiler/source/offline_compiler.h" +#include "shared/test/common/helpers/mock_file_io.h" +#include "shared/test/common/helpers/variable_backup.h" +#include "shared/test/common/mocks/mock_io_functions.h" #include "opencl/test/unit_test/offline_compiler/mock/mock_argument_helper.h" +#include "environment.h" #include "gtest/gtest.h" +#include "mock/mock_argument_helper.h" #include #include +extern Environment *gEnvironment; + namespace NEO { class OfflineCompilerTests : public ::testing::Test { public: OfflineCompiler *pOfflineCompiler = nullptr; int retVal = OCLOC_SUCCESS; - std::map filesMap; std::unique_ptr oclocArgHelperWithoutInput = std::make_unique(filesMap); protected: void SetUp() override { - oclocArgHelperWithoutInput->setAllCallBase(true); + std::string spvFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".spv"; + std::string binFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".bin"; + std::string dbgFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".dbg"; + std::vector mockByteArray = {0x01, 0x02, 0x03, 0x04}; + writeDataToFile(spvFile.c_str(), mockByteArray.data(), mockByteArray.size()); + writeDataToFile(binFile.c_str(), mockByteArray.data(), mockByteArray.size()); + writeDataToFile(dbgFile.c_str(), mockByteArray.data(), mockByteArray.size()); + + filesMap[clCopybufferFilename] = OfflineCompilerTests::kernelSources; + oclocArgHelperWithoutInput->setAllCallBase(false); } + MockOclocArgHelper::FilesMap filesMap{}; + std::string kernelSources = "example_kernel(){}"; + const std::string clCopybufferFilename = "some_kernel.cl"; }; class MultiCommandTests : public ::testing::Test { @@ -42,12 +60,23 @@ class MultiCommandTests : public ::testing::Test { std::string nameOfFileWithArgs; std::string outFileList; int retVal = OCLOC_SUCCESS; - std::map filesMap; std::unique_ptr oclocArgHelperWithoutInput = std::make_unique(filesMap); protected: void SetUp() override { - oclocArgHelperWithoutInput->setAllCallBase(true); + std::string spvFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".spv"; + std::string binFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".bin"; + std::string dbgFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".dbg"; + std::vector mockByteArray = {0x01, 0x02, 0x03, 0x04}; + writeDataToFile(spvFile.c_str(), mockByteArray.data(), mockByteArray.size()); + writeDataToFile(binFile.c_str(), mockByteArray.data(), mockByteArray.size()); + writeDataToFile(dbgFile.c_str(), mockByteArray.data(), mockByteArray.size()); + filesMap[clCopybufferFilename] = kernelSources; + oclocArgHelperWithoutInput->setAllCallBase(false); } + + MockOclocArgHelper::FilesMap filesMap{}; + const std::string clCopybufferFilename = "some_kernel.cl"; + std::string kernelSources = "example_kernel(){}"; }; -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/opencl/test/unit_test/offline_compiler/offline_linker_tests.cpp b/opencl/test/unit_test/offline_compiler/offline_linker_tests.cpp index c976dd553c..4ea514b5aa 100644 --- a/opencl/test/unit_test/offline_compiler/offline_linker_tests.cpp +++ b/opencl/test/unit_test/offline_compiler/offline_linker_tests.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2024 Intel Corporation + * Copyright (C) 2022-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -12,6 +12,8 @@ #include "shared/source/device_binary_format/elf/ocl_elf.h" #include "shared/source/helpers/string.h" #include "shared/source/os_interface/os_inc_base.h" +#include "shared/test/common/helpers/mock_file_io.h" +#include "shared/test/common/helpers/stdout_capture.h" #include "shared/test/common/mocks/mock_compilers.h" #include "environment.h" @@ -32,6 +34,13 @@ namespace NEO { using OperationMode = MockOfflineLinker::OperationMode; void OfflineLinkerTest::SetUp() { + std::string spvFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".spv"; + std::string binFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".bin"; + std::string dbgFile = std::string("copybuffer") + "_" + gEnvironment->devicePrefix + ".dbg"; + std::vector mockByteArray = {0x01, 0x02, 0x03, 0x04}; + writeDataToFile(spvFile.c_str(), mockByteArray.data(), mockByteArray.size()); + writeDataToFile(binFile.c_str(), mockByteArray.data(), mockByteArray.size()); + writeDataToFile(dbgFile.c_str(), mockByteArray.data(), mockByteArray.size()); MockCompilerDebugVars igcDebugVars{gEnvironment->igcDebugVars}; igcDebugVars.binaryToReturn = binaryToReturn; igcDebugVars.binaryToReturnSize = sizeof(binaryToReturn); @@ -198,10 +207,11 @@ TEST_F(OfflineLinkerTest, GivenUnknownArgumentWhenParsingThenErrorIsReported) { "link", "-some_new_unknown_command"}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); MockOfflineLinker mockOfflineLinker{&mockArgHelper, std::move(mockOclocIgcFacade)}; const auto result = mockOfflineLinker.initialize(argv.size(), argv); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, result); @@ -222,9 +232,10 @@ TEST_F(OfflineLinkerTest, GivenFlagsWhichRequireMoreArgsWithoutThemWhenParsingTh mockOclocIgcFacade = std::make_unique(&mockArgHelper); MockOfflineLinker mockOfflineLinker{&mockArgHelper, std::move(mockOclocIgcFacade)}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto result = mockOfflineLinker.parseCommand(argv.size(), argv); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, result); @@ -237,9 +248,10 @@ TEST_F(OfflineLinkerTest, GivenCommandWithoutInputFilesWhenVerificationIsPerform MockOfflineLinker mockOfflineLinker{&mockArgHelper, std::move(mockOclocIgcFacade)}; mockOfflineLinker.inputFilenames = {}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto verificationResult = mockOfflineLinker.verifyLinkerCommand(); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, verificationResult); @@ -256,9 +268,10 @@ TEST_F(OfflineLinkerTest, GivenCommandWithEmptyFilenameWhenVerificationIsPerform MockOfflineLinker mockOfflineLinker{&mockArgHelper, std::move(mockOclocIgcFacade)}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto verificationResult = mockOfflineLinker.initialize(argv.size(), argv); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, verificationResult); @@ -279,9 +292,10 @@ TEST_F(OfflineLinkerTest, GivenCommandWithNonexistentInputFileWhenVerificationIs const auto parsingResult = mockOfflineLinker.parseCommand(argv.size(), argv); ASSERT_EQ(OCLOC_SUCCESS, parsingResult); - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto verificationResult = mockOfflineLinker.verifyLinkerCommand(); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_FILE, verificationResult); @@ -304,9 +318,10 @@ TEST_F(OfflineLinkerTest, GivenCommandWithInvalidOutputFormatWhenVerificationIsP const auto parsingResult = mockOfflineLinker.parseCommand(argv.size(), argv); ASSERT_EQ(OCLOC_SUCCESS, parsingResult); - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto verificationResult = mockOfflineLinker.verifyLinkerCommand(); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_COMMAND_LINE, verificationResult); @@ -330,9 +345,10 @@ TEST_F(OfflineLinkerTest, GivenValidCommandWhenVerificationIsPerformedThenSucces const auto parsingResult = mockOfflineLinker.parseCommand(argv.size(), argv); ASSERT_EQ(OCLOC_SUCCESS, parsingResult); - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto verificationResult = mockOfflineLinker.verifyLinkerCommand(); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_SUCCESS, verificationResult); EXPECT_TRUE(output.empty()); @@ -351,9 +367,10 @@ TEST_F(OfflineLinkerTest, GivenEmptyFileWhenLoadingInputFilesThenErrorIsReturned MockOfflineLinker mockOfflineLinker{&mockArgHelper, std::move(mockOclocIgcFacade)}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto initializationResult = mockOfflineLinker.initialize(argv.size(), argv); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; ASSERT_EQ(OCLOC_INVALID_FILE, initializationResult); @@ -370,9 +387,10 @@ TEST_F(OfflineLinkerTest, GivenValidFileWithUnknownFormatWhenLoadingInputFilesTh MockOfflineLinker mockOfflineLinker{&mockArgHelper, std::move(mockOclocIgcFacade)}; mockOfflineLinker.inputFilenames.push_back(filename); - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto readingResult = mockOfflineLinker.loadInputFilesContent(); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; ASSERT_EQ(OCLOC_INVALID_PROGRAM, readingResult); @@ -391,9 +409,10 @@ TEST_F(OfflineLinkerTest, GivenValidFilesWithValidFormatsWhenLoadingInputFilesTh mockOfflineLinker.inputFilenames.push_back(firstFilename); mockOfflineLinker.inputFilenames.push_back(secondFilename); - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto readingResult = mockOfflineLinker.loadInputFilesContent(); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; ASSERT_EQ(OCLOC_SUCCESS, readingResult); EXPECT_TRUE(output.empty()); @@ -430,9 +449,10 @@ TEST_F(OfflineLinkerTest, GivenValidFilesWhenInitializationIsSuccessfulThenLinkM MockOfflineLinker mockOfflineLinker{&mockArgHelper, std::move(mockOclocIgcFacade)}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto initializationResult = mockOfflineLinker.initialize(argv.size(), argv); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_SUCCESS, initializationResult); EXPECT_TRUE(output.empty()); @@ -536,9 +556,10 @@ TEST_F(OfflineLinkerTest, GivenValidInputFileContentsAndFailingIGCWhenLlvmBcOutp mockOfflineLinker.outputFormat = IGC::CodeType::llvmBc; mockOfflineLinker.operationMode = OperationMode::linkFiles; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto linkingResult{mockOfflineLinker.execute()}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; ASSERT_EQ(OCLOC_BUILD_PROGRAM_FAILURE, linkingResult); EXPECT_EQ(0u, mockArgHelper.interceptedFiles.count("linker_output")); @@ -567,9 +588,10 @@ TEST_F(OfflineLinkerTest, GivenValidInputFileContentsAndIGCSignalingSuccessButRe mockOfflineLinker.outputFormat = IGC::CodeType::llvmBc; mockOfflineLinker.operationMode = OperationMode::linkFiles; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto linkingResult{mockOfflineLinker.execute()}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; ASSERT_EQ(OCLOC_BUILD_PROGRAM_FAILURE, linkingResult); EXPECT_EQ(0u, mockArgHelper.interceptedFiles.count("linker_output")); @@ -598,9 +620,10 @@ TEST_F(OfflineLinkerTest, GivenValidInputFileContentsAndInvalidTranslationOutput mockOfflineLinker.outputFormat = IGC::CodeType::llvmBc; mockOfflineLinker.operationMode = OperationMode::linkFiles; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto linkingResult{mockOfflineLinker.execute()}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; ASSERT_EQ(OCLOC_OUT_OF_HOST_MEMORY, linkingResult); EXPECT_EQ(0u, mockArgHelper.interceptedFiles.count("linker_output")); @@ -612,9 +635,10 @@ TEST_F(OfflineLinkerTest, GivenValidInputFileContentsAndInvalidTranslationOutput TEST_F(OfflineLinkerTest, GivenUninitializedLinkerWhenExecuteIsInvokedThenErrorIsIssued) { MockOfflineLinker mockOfflineLinker{&mockArgHelper, std::move(mockOclocIgcFacade)}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto executionResult{mockOfflineLinker.execute()}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; ASSERT_EQ(OCLOC_INVALID_COMMAND_LINE, executionResult); ASSERT_FALSE(output.empty()); @@ -624,9 +648,10 @@ TEST_F(OfflineLinkerTest, GivenHelpRequestWhenExecuteIsInvokedThenHelpIsPrinted) MockOfflineLinker mockOfflineLinker{&mockArgHelper, std::move(mockOclocIgcFacade)}; mockOfflineLinker.operationMode = OperationMode::showHelp; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto executionResult{mockOfflineLinker.execute()}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; ASSERT_EQ(OCLOC_SUCCESS, executionResult); ASSERT_FALSE(output.empty()); @@ -636,9 +661,10 @@ TEST_F(OfflineLinkerTest, GivenInvalidOperationModeWhenExecuteIsInvokedThenError MockOfflineLinker mockOfflineLinker{&mockArgHelper, std::move(mockOclocIgcFacade)}; mockOfflineLinker.operationMode = static_cast(7); // NOLINT(clang-analyzer-optin.core.EnumCastOutOfRange), NEO-12901 - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto executionResult{mockOfflineLinker.execute()}; - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; ASSERT_EQ(OCLOC_INVALID_COMMAND_LINE, executionResult); ASSERT_FALSE(output.empty()); @@ -671,9 +697,10 @@ TEST_F(OfflineLinkerTest, GivenEmptyHwInfoTableWhenInitializationIsPerformedThen MockOfflineLinker mockOfflineLinker{&mockArgHelper, std::move(mockOclocIgcFacade)}; mockOfflineLinker.shouldReturnEmptyHardwareInfoTable = true; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto initializationResult = mockOfflineLinker.initialize(argv.size(), argv); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_INVALID_DEVICE, initializationResult); @@ -699,9 +726,10 @@ TEST_F(OfflineLinkerTest, GivenMissingIgcLibraryWhenInitializationIsPerformedThe mockOclocIgcFacade->shouldFailLoadingOfIgcLib = true; MockOfflineLinker mockOfflineLinker{&mockArgHelper, std::move(mockOclocIgcFacade)}; - ::testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); const auto initializationResult = mockOfflineLinker.initialize(argv.size(), argv); - const auto output{::testing::internal::GetCapturedStdout()}; + const auto output{capture.getCapturedStdout()}; EXPECT_EQ(OCLOC_OUT_OF_HOST_MEMORY, initializationResult); @@ -735,4 +763,4 @@ TEST_F(OfflineLinkerTest, GivenOfflineLinkerWhenStoringInvalidBuildLogThenItIsIg EXPECT_TRUE(buildLog2.empty()); } -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/opencl/test/unit_test/offline_compiler/stdout_capturer.h b/opencl/test/unit_test/offline_compiler/stdout_capturer.h index 544762a1ee..f7a51c502e 100644 --- a/opencl/test/unit_test/offline_compiler/stdout_capturer.h +++ b/opencl/test/unit_test/offline_compiler/stdout_capturer.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Intel Corporation + * Copyright (C) 2022-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -7,6 +7,8 @@ #pragma once +#include "shared/test/common/helpers/stdout_capture.h" + #include namespace NEO { @@ -19,21 +21,22 @@ namespace NEO { class StdoutCapturer { public: StdoutCapturer() { - ::testing::internal::CaptureStdout(); + capture.captureStdout(); } ~StdoutCapturer() { if (!outputAcquired) { - ::testing::internal::GetCapturedStdout(); + capture.getCapturedStdout(); } } std::string acquireOutput() { outputAcquired = true; - return ::testing::internal::GetCapturedStdout(); + return capture.getCapturedStdout(); } private: + StdoutCapture capture; bool outputAcquired{false}; }; diff --git a/opencl/test/unit_test/offline_compiler/xe3_core/ptl/offline_compiler_tests_ptl.cpp b/opencl/test/unit_test/offline_compiler/xe3_core/ptl/offline_compiler_tests_ptl.cpp index 0dddebb4e3..3ac0c38b18 100644 --- a/opencl/test/unit_test/offline_compiler/xe3_core/ptl/offline_compiler_tests_ptl.cpp +++ b/opencl/test/unit_test/offline_compiler/xe3_core/ptl/offline_compiler_tests_ptl.cpp @@ -8,6 +8,7 @@ #include "shared/offline_compiler/source/ocloc_arg_helper.h" #include "shared/source/helpers/product_config_helper.h" #include "shared/source/xe3_core/hw_info_xe3_core.h" +#include "shared/test/common/helpers/stdout_capture.h" #include "shared/test/common/test_macros/header/per_product_test_definitions.h" #include "shared/test/common/test_macros/test.h" @@ -27,9 +28,10 @@ PTLTEST_F(PtlOfflineCompilerTests, givenPtlHDeviceIdValueWhenInitHwInfoThenCorre std::stringstream deviceIDStr, expectedOutput; deviceIDStr << "0x" << std::hex << deviceID; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); mockOfflineCompiler.initHardwareInfo(deviceIDStr.str()); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); expectedOutput << "Auto-detected target based on " << deviceIDStr.str() << " device id: ptl-h-a0\n"; EXPECT_STREQ(output.c_str(), expectedOutput.str().c_str()); @@ -47,13 +49,14 @@ PTLTEST_F(PtlOfflineCompilerTests, givenPtlUDeviceIdValueWhenInitHwInfoThenCorre deviceIDStr << "0x" << std::hex << deviceID; - testing::internal::CaptureStdout(); + StdoutCapture capture; + capture.captureStdout(); mockOfflineCompiler.initHardwareInfo(deviceIDStr.str()); - std::string output = testing::internal::GetCapturedStdout(); + std::string output = capture.getCapturedStdout(); expectedOutput << "Auto-detected target based on " << deviceIDStr.str() << " device id: ptl-u-a0\n"; EXPECT_STREQ(output.c_str(), expectedOutput.str().c_str()); EXPECT_EQ(mockOfflineCompiler.hwInfo.platform.usDeviceID, deviceID); EXPECT_EQ(mockOfflineCompiler.deviceConfig, ptlConfig.value); } -} +} \ No newline at end of file diff --git a/shared/offline_compiler/source/decoder/helper.cpp b/shared/offline_compiler/source/decoder/helper.cpp index e0990fe560..57a588aae4 100644 --- a/shared/offline_compiler/source/decoder/helper.cpp +++ b/shared/offline_compiler/source/decoder/helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018-2024 Intel Corporation + * Copyright (C) 2018-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -9,6 +9,7 @@ #include "shared/offline_compiler/source/decoder/iga_wrapper.h" #include "shared/offline_compiler/source/ocloc_arg_helper.h" +#include "shared/source/helpers/file_io.h" #include "shared/source/helpers/hw_info.h" #include "shared/source/helpers/product_config_helper.h" #include "shared/source/os_interface/os_inc_base.h" @@ -34,14 +35,11 @@ void addSlash(std::string &path) { } std::vector readBinaryFile(const std::string &fileName) { - std::ifstream file(fileName, std::ios_base::binary); - if (file.good()) { - size_t length; - file.seekg(0, file.end); - length = static_cast(file.tellg()); - file.seekg(0, file.beg); - std::vector binary(length); - file.read(binary.data(), length); + size_t length; + std::unique_ptr data = loadDataFromFile(fileName.c_str(), length); + + if (data) { + std::vector binary(data.get(), data.get() + length); return binary; } else { printf("Error! Couldn't open %s\n", fileName.c_str()); @@ -68,8 +66,13 @@ void istreamToVectorOfStrings(std::istream &input, std::vector &lin } void readFileToVectorOfStrings(std::vector &lines, const std::string &fileName, bool replaceTabs) { - std::ifstream file(fileName); - istreamToVectorOfStrings(file, lines, replaceTabs); + size_t fileSize = 0; + std::unique_ptr fileData = loadDataFromFile(fileName.c_str(), fileSize); + + if (fileData && fileSize > 0) { + std::istringstream inputStream(std::string(fileData.get(), fileSize)); + istreamToVectorOfStrings(inputStream, lines, replaceTabs); + } } size_t findPos(const std::vector &lines, const std::string &whatToFind) { @@ -107,4 +110,4 @@ void setProductFamilyForIga(const std::string &device, IgaWrapper *iga, OclocArg } } iga->setProductFamily(productFamily); -} +} \ No newline at end of file diff --git a/shared/offline_compiler/source/offline_compiler.cpp b/shared/offline_compiler/source/offline_compiler.cpp index 40f093d9c5..e0b5353b3b 100644 --- a/shared/offline_compiler/source/offline_compiler.cpp +++ b/shared/offline_compiler/source/offline_compiler.cpp @@ -31,6 +31,7 @@ #include "shared/source/helpers/string.h" #include "shared/source/helpers/validators.h" #include "shared/source/release_helper/release_helper.h" +#include "shared/source/utilities/io_functions.h" #include "offline_compiler_ext.h" #include "platforms.h" @@ -43,11 +44,9 @@ #ifdef _WIN32 #include -#define MakeDirectory _mkdir #define GetCurrentWorkingDirectory _getcwd #else #include -#define MakeDirectory(dir) mkdir(dir, 0777) #define GetCurrentWorkingDirectory getcwd #endif @@ -1646,7 +1645,7 @@ void OfflineCompiler::writeOutAllFiles() { } void OfflineCompiler::createDir(const std::string &path) { - MakeDirectory(path.c_str()); + IoFunctions::mkdirPtr(path.c_str()); } bool OfflineCompiler::readOptionsFromFile(std::string &options, const std::string &file, OclocArgHelper *helper) { @@ -1706,4 +1705,4 @@ std::string generateFilePath(const std::string &directory, const std::string &fi return ret; } -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/shared/source/utilities/io_functions.cpp b/shared/source/utilities/io_functions.cpp index 9ff87aeab8..c049de6c29 100644 --- a/shared/source/utilities/io_functions.cpp +++ b/shared/source/utilities/io_functions.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2023 Intel Corporation + * Copyright (C) 2020-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -19,5 +19,7 @@ rewindFuncPtr rewindPtr = &rewind; freadFuncPtr freadPtr = &fread; fwriteFuncPtr fwritePtr = &fwrite; fflushFuncPtr fflushPtr = &fflush; +mkdirFuncPtr mkdirPtr = &makedir; + } // namespace IoFunctions -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/shared/source/utilities/io_functions.h b/shared/source/utilities/io_functions.h index ed62cdad5c..cc8792659f 100644 --- a/shared/source/utilities/io_functions.h +++ b/shared/source/utilities/io_functions.h @@ -14,18 +14,25 @@ #include #include +#ifdef _WIN32 +#include +#else +#include +#endif + namespace NEO { namespace IoFunctions { using fopenFuncPtr = FILE *(*)(const char *, const char *); using vfprintfFuncPtr = int (*)(FILE *, char const *const formatStr, va_list arg); using fcloseFuncPtr = int (*)(FILE *); using getenvFuncPtr = decltype(&getenv); -using fseekFuncPtr = decltype(&fseek); -using ftellFuncPtr = decltype(&ftell); +using fseekFuncPtr = int (*)(FILE *, long int, int); +using ftellFuncPtr = long int (*)(FILE *); using rewindFuncPtr = decltype(&rewind); -using freadFuncPtr = decltype(&fread); +using freadFuncPtr = size_t (*)(void *, size_t, size_t, FILE *); using fwriteFuncPtr = decltype(&fwrite); using fflushFuncPtr = decltype(&fflush); +using mkdirFuncPtr = int (*)(const char *); extern fopenFuncPtr fopenPtr; extern vfprintfFuncPtr vfprintfPtr; @@ -37,6 +44,7 @@ extern rewindFuncPtr rewindPtr; extern freadFuncPtr freadPtr; extern fwriteFuncPtr fwritePtr; extern fflushFuncPtr fflushPtr; +extern mkdirFuncPtr mkdirPtr; inline int fprintf(FILE *fileDesc, char const *const formatStr, ...) { va_list args; @@ -64,5 +72,15 @@ inline char *getEnvironmentVariable(const char *name) { return nullptr; } +#ifdef _WIN32 +inline int makedir(const char *dirName) { + return _mkdir(dirName); +} +#else +inline int makedir(const char *dirName) { + return mkdir(dirName, 0777); +} +#endif + } // namespace IoFunctions -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/shared/test/common/helpers/stdout_capture.h b/shared/test/common/helpers/stdout_capture.h new file mode 100644 index 0000000000..a51a56a55f --- /dev/null +++ b/shared/test/common/helpers/stdout_capture.h @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2025 Intel Corporation + * + * SPDX-License-Identifier: MIT + * + */ + +#pragma once + +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#else +#include +#include +#include +#endif + +class StdoutCapture { + public: + void captureStdout() { +#ifdef _WIN32 + _pipe(pipefd, 4096, O_TEXT); + fflush(stdout); + saveStdout = _dup(_fileno(stdout)); + _dup2(pipefd[1], _fileno(stdout)); + _close(pipefd[1]); +#else + fflush(stdout); + pipe(pipefd); + saveStdout = dup(fileno(stdout)); + dup2(pipefd[1], fileno(stdout)); + close(pipefd[1]); +#endif + } + + std::string getCapturedStdout() { +#ifdef _WIN32 + fflush(stdout); + _dup2(saveStdout, _fileno(stdout)); + _close(saveStdout); + + char buffer[4096]; + int count = _read(pipefd[0], buffer, sizeof(buffer) - 1); + if (count > 0) { + buffer[count] = '\0'; + return std::string(buffer); + } + return ""; +#else + fflush(stdout); + dup2(saveStdout, fileno(stdout)); + close(saveStdout); + + constexpr size_t bufferSize = 4096; + char buffer[bufferSize]; + ssize_t count = read(pipefd[0], buffer, bufferSize - 1); + if (count > 0) { + buffer[count] = '\0'; + return std::string(buffer); + } + return ""; +#endif + } + + private: + int pipefd[2]; + int saveStdout; +}; \ No newline at end of file diff --git a/shared/test/common/libult/mock_io_functions.cpp b/shared/test/common/libult/mock_io_functions.cpp index ecb14e6349..0c046f8ff2 100644 --- a/shared/test/common/libult/mock_io_functions.cpp +++ b/shared/test/common/libult/mock_io_functions.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2024 Intel Corporation + * Copyright (C) 2020-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -19,6 +19,7 @@ rewindFuncPtr rewindPtr = &mockRewind; freadFuncPtr freadPtr = &mockFread; fwriteFuncPtr fwritePtr = &mockFwrite; fflushFuncPtr fflushPtr = &mockFflush; +mkdirFuncPtr mkdirPtr = &mockMkdir; uint32_t mockFopenCalled = 0; FILE *mockFopenReturned = reinterpret_cast(0x40); @@ -43,4 +44,4 @@ const char *openCLDriverName = "igdrcl.dll"; std::unordered_map *mockableEnvValues = nullptr; } // namespace IoFunctions -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/shared/test/common/mocks/mock_compilers.cpp b/shared/test/common/mocks/mock_compilers.cpp index 3577f89a43..b80ca0bd66 100644 --- a/shared/test/common/mocks/mock_compilers.cpp +++ b/shared/test/common/mocks/mock_compilers.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018-2024 Intel Corporation + * Copyright (C) 2018-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -8,9 +8,9 @@ #include "mock_compilers.h" #include "shared/source/compiler_interface/compiler_options.h" -#include "shared/source/helpers/file_io.h" #include "shared/source/helpers/hw_info.h" #include "shared/source/os_interface/os_inc_base.h" +#include "shared/test/common/helpers/mock_file_io.h" #include "shared/test/common/helpers/test_files.h" #include "shared/test/common/mocks/mock_compiler_interface.h" #include "shared/test/common/mocks/mock_compilers.h" @@ -20,6 +20,7 @@ #include "ocl_igc_interface/fcl_ocl_device_ctx.h" #include "ocl_igc_interface/igc_ocl_device_ctx.h" +#include #include #include namespace NEO { @@ -385,19 +386,25 @@ namespace NEO { template std::unique_ptr loadBinaryFile(StrT &&fileName, size_t &fileSize) { - std::ifstream f{fileName, std::ios::binary | std::ios::in | std::ios::ate}; - auto end = f.tellg(); - f.seekg(0, std::ios::beg); - auto beg = f.tellg(); - auto s = static_cast(end - beg); - if (s == 0) { - fileSize = 0; - return nullptr; + + std::unique_ptr data = loadDataFromFile(fileName.c_str(), fileSize); + return std::unique_ptr(reinterpret_cast(data.release())); +}; + +template +std::unique_ptr loadVirtualBinaryFile(StrT &&fileName, size_t &fileSize) { + std::filesystem::path filePath = std::forward(fileName); + std::string fileNameWithExtension = filePath.filename().string(); + if (!virtualFileExists(fileNameWithExtension)) { + return loadBinaryFile(fileName, fileSize); } - std::unique_ptr data{new unsigned char[s]}; - f.read(reinterpret_cast(data.get()), s); - fileSize = s; - return data; + + std::unique_ptr charData = loadDataFromVirtualFile(fileNameWithExtension.c_str(), fileSize); + + std::unique_ptr ucharData(new unsigned char[fileSize]); + std::memcpy(ucharData.get(), charData.get(), fileSize); + + return ucharData; }; void translate(bool usingIgc, CIF::Builtins::BufferSimple *src, CIF::Builtins::BufferSimple *options, @@ -474,7 +481,7 @@ void translate(bool usingIgc, CIF::Builtins::BufferSimple *src, CIF::Builtins::B out->setOutput(debugVars.binaryToReturn, debugVars.binaryToReturnSize); } else { size_t fileSize = 0; - auto fileData = loadBinaryFile(inputFile, fileSize); + auto fileData = loadVirtualBinaryFile(inputFile, fileSize); out->setOutput(fileData.get(), fileSize); if (fileSize == 0) { @@ -486,7 +493,7 @@ void translate(bool usingIgc, CIF::Builtins::BufferSimple *src, CIF::Builtins::B out->setDebugData(debugVars.debugDataToReturn, debugVars.debugDataToReturnSize); } else { size_t fileSize = 0; - auto fileData = loadBinaryFile(debugFile, fileSize); + auto fileData = loadVirtualBinaryFile(debugFile, fileSize); out->setDebugData(fileData.get(), fileSize); } } else { @@ -735,4 +742,4 @@ std::vector MockCompilerInterface::getDummyGenBinary() { void MockCompilerInterface::releaseDummyGenBinary() { } -} // namespace NEO +} // namespace NEO \ No newline at end of file diff --git a/shared/test/common/mocks/mock_io_functions.h b/shared/test/common/mocks/mock_io_functions.h index 45ae5be9e7..655a43fc5f 100644 --- a/shared/test/common/mocks/mock_io_functions.h +++ b/shared/test/common/mocks/mock_io_functions.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020-2024 Intel Corporation + * Copyright (C) 2020-2025 Intel Corporation * * SPDX-License-Identifier: MIT * @@ -108,5 +108,9 @@ inline int mockFflush(FILE *stream) { return 0; } +inline int mockMkdir(const char *filename) { + return 0; +} + } // namespace IoFunctions -} // namespace NEO +} // namespace NEO \ No newline at end of file