Refactor tests directory

Signed-off-by: Kamil Łepek <kamil.lepek94@gmail.com>
This commit is contained in:
Kamil Łepek
2019-01-17 06:10:09 -06:00
parent 539029375d
commit 92b2fa362e
19 changed files with 29 additions and 48 deletions

View File

@@ -0,0 +1,11 @@
GENERATING NEW TEST
To add new test, run "add_new_test_file.py" with two parameters:
- tested file path (path must be relative to your current working dir)
- tested function name
Generated file name may be changed without any consequences.
Good practise is to use "add_new_test_file.py" script from test directory (not framework),
because it prepend appropriate license header.
RUNNING SINGLE TEST
Executable tests files are stored by default in 'UT_dir/build/sources_to_test_repository/'

View File

@@ -0,0 +1,167 @@
#!/usr/bin/env python2
#
# Copyright(c) 2012-2018 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause-Clear
#
import tests_config
import re
import os
import sys
import textwrap
class TestGenerator(object):
main_UT_dir = ""
main_tested_dir = ""
tested_file_path = ""
tested_function_name = ""
def __init__(self, main_UT_dir, main_tested_dir, file_path, func_name):
self.set_main_UT_dir(main_UT_dir)
self.set_main_tested_dir(main_tested_dir)
self.set_tested_file_path(file_path)
self.tested_function_name = func_name
def create_empty_test_file(self):
dst_dir = os.path.dirname(self.get_tested_file_path()[::-1])[::-1]
self.create_dir_if_not_exist(self.get_main_UT_dir() + dst_dir)
test_file_name = os.path.basename(self.get_tested_file_path())
dst_path = self.get_main_UT_dir() + dst_dir + "/" + test_file_name
no_str = ""
no = 0
while True:
if not os.path.isfile(dst_path.rsplit(".", 1)[0] + no_str + "." + dst_path.rsplit(".", 1)[1]):
break
no += 1
no_str = str(no)
dst_path = dst_path.rsplit(".", 1)[0] + no_str + "." + dst_path.rsplit(".", 1)[1]
buf = self.get_markups()
buf += "#undef static\n\n"
buf += "#undef inline\n\n"
buf += self.get_UT_includes()
buf += self.get_includes(self.get_main_tested_dir() + self.get_tested_file_path())
buf += self.get_empty_test_function()
buf += self.get_test_main()
print dst_path + " generated successfully!"
def get_markups(self):
ret = "/*\n"
ret += " * <tested_file_path>" + self.get_tested_file_path() + "</tested_file_path>\n"
ret += " * <tested_function>" + self.get_tested_function_name() + "</tested_function>\n"
ret += " * <functions_to_leave>\n"
ret += " *\tINSERT HERE LIST OF FUNCTIONS YOU WANT TO LEAVE\n"
ret += " *\tONE FUNCTION PER LINE\n"
ret += " * </functions_to_leave>\n"
ret += " */\n\n"
return ret
def create_dir_if_not_exist(self, path):
if not os.path.isdir(path):
try:
os.makedirs(path)
except Exception:
pass
return True
return None
def get_UT_includes(self):
ret = '''
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "print_desc.h"\n\n'''
return textwrap.dedent(ret)
def get_includes(self, abs_path_to_tested_file):
with open(abs_path_to_tested_file, "r") as f:
code = f.readlines()
ret = [line for line in code if re.search(r'#include', line)]
return "".join(ret) + "\n\n"
def get_empty_test_function(self):
ret = "static void " + self.get_tested_function_name() + "_test01(void **state)\n"
ret += "{\n"
ret += "\tprint_test_description(\"Put test description here\");\n"
ret += "\tassert_int_equal(1,1);\n"
ret += "}\n\n"
return ret
def get_test_main(self):
ret = "int main(void)\n"
ret += "{\n"
ret += "\tconst struct CMUnitTest tests[] = {\n"
ret += "\t\tcmocka_unit_test(" + self.get_tested_function_name() + "_test01)\n"
ret += "\t};\n\n"
ret += "\tprint_message(\"Unit test of " + self.get_tested_file_path() + "\");\n\n"
ret += "\treturn cmocka_run_group_tests(tests, NULL, NULL);\n"
ret += "}"
return ret
def set_tested_file_path(self, path):
call_dir = os.getcwd() + os.sep
p = os.path.normpath(call_dir + path)
if os.path.isfile(p):
self.tested_file_path = p.split(self.get_main_tested_dir(), 1)[1]
return
elif os.path.isfile(self.get_main_tested_dir() + path):
self.tested_file_path = path
return
print self.get_main_tested_dir() + path
print "Given path not exists!"
exit(1)
def set_main_UT_dir(self, path):
p = os.path.dirname(os.path.realpath(__file__)) + os.sep + path
p = os.path.normpath(os.path.dirname(p)) + os.sep
self.main_UT_dir = p
def get_main_UT_dir(self):
return self.main_UT_dir
def set_main_tested_dir(self, path):
p = os.path.dirname(os.path.realpath(__file__)) + os.sep + path
p = os.path.normpath(os.path.dirname(p)) + os.sep
self.main_tested_dir = p
def get_main_tested_dir(self):
return self.main_tested_dir
def get_tested_file_path(self):
return self.tested_file_path
def get_tested_function_name(self):
return self.tested_function_name
def __main__():
if len(sys.argv) < 3:
print "No path to tested file or tested function name given !"
sys.exit(1)
tested_file_path = sys.argv[1]
tested_function_name = sys.argv[2]
generator = TestGenerator(tests_config.MAIN_DIRECTORY_OF_UNIT_TESTS,\
tests_config.MAIN_DIRECTORY_OF_TESTED_PROJECT,\
tested_file_path, tested_function_name)
generator.create_empty_test_file()
if __name__ == "__main__":
__main__()

View File

@@ -0,0 +1,585 @@
#!/usr/bin/env python2
#
# Copyright(c) 2012-2018 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause-Clear
#
import shutil
import sys
import re
import commands
import os.path
from collections import defaultdict
import tests_config
#
# This script purpose is to remove unused functions definitions
# It is giving the opportunity to unit test all functions from OCF.
# As a parameter should be given path to file containing function,
# which is target of testing. However that file has to be after
# preprocessing.
#
# Output file of this script is not ready to make it. Before that,
# has to be given definitions of functions, which are used by
# tested function.
#
# In brief: this script allow wrapping all function calls in UT
#
class UnitTestsSourcesGenerator(object):
script_file_abs_path = ""
script_dir_abs_path = ""
main_UT_dir = ""
main_tested_dir = ""
ctags_path = ""
test_catalouges_list = []
dirs_to_include_list = []
tests_internal_includes_list = []
framework_includes = []
dirs_with_tests_list = []
test_files_paths_list = []
tested_files_paths_list = []
includes_to_copy_dict = {}
preprocessing_repo = ""
sources_to_test_repo = ""
def __init__(self):
self.script_file_abs_path = os.path.realpath(__file__)
self.script_dir_abs_path = os.path.normpath(os.path.dirname(self.script_file_abs_path) + os.sep)
self.set_ctags_path()
self.set_main_UT_dir()
self.set_main_tested_dir()
self.test_catalouges_list = tests_config.DIRECTORIES_WITH_TESTS_LIST
self.set_includes_to_copy_dict(tests_config.INCLUDES_TO_COPY_DICT)
self.set_dirs_to_include()
self.set_tests_internal_includes_list()
self.set_framework_includes()
self.set_files_with_tests_list()
self.set_tested_files_paths_list()
self.set_preprocessing_repo()
self.set_sources_to_test_repo()
def preprocessing(self):
tested_files_list = self.get_tested_files_paths_list()
project_includes = self.get_dirs_to_include_list()
framework_includes = self.get_tests_internal_includes_list()
gcc_flags = " -fno-inline -Dstatic= -Dinline= -E "
gcc_command_template = "gcc "
for path in project_includes:
gcc_command_template += " -I " + path + " "
for path in framework_includes:
gcc_command_template += " -I " + path
gcc_command_template += gcc_flags
for path in tested_files_list:
preprocessing_dst = self.get_preprocessing_repo() +\
self.get_relative_path(path, self.get_main_tested_dir())
preprocessing_dst_dir = os.path.dirname(preprocessing_dst)
self.create_dir_if_not_exist(preprocessing_dst_dir)
gcc_command = gcc_command_template +\
path + " > " + preprocessing_dst
status, output = commands.getstatusoutput(gcc_command)
if status != 0:
print "Generating preprocessing for " + self.get_main_tested_dir() + path \
+ " failed!"
print output
commands.getoutput("rm -f " + preprocessing_dst)
continue
self.remove_hashes(preprocessing_dst)
print "Preprocessed file " + path + " saved to " + preprocessing_dst
def copy_includes(self):
includes_dict = self.get_includes_to_copy_dict()
for dst, src in includes_dict.iteritems():
src_path = os.path.normpath(self.get_main_tested_dir() + src)
if not os.path.isdir(src_path):
print "Directory " + src_path + " given to include does not exists!"
continue
dst_path = os.path.normpath(self.get_main_UT_dir() + dst)
shutil.rmtree(dst_path)
shutil.copytree(src_path, dst_path)
def prepare_sources_for_testing(self):
test_files_paths = self.get_files_with_tests_list()
for test_path in test_files_paths:
path = self.get_tested_file_path(self.get_main_UT_dir() + test_path)
preprocessed_tested_path = self.get_preprocessing_repo() + path
if not os.path.isfile(preprocessed_tested_path):
print "No preprocessed path for " + test_path + " test file."
continue
tested_src = self.get_src_to_test(test_path, preprocessed_tested_path)
self.create_dir_if_not_exist(self.get_sources_to_test_repo() + os.path.dirname(test_path))
with open(self.get_sources_to_test_repo() + test_path, "w") as f:
f.writelines(tested_src)
print "Sources for " + test_path + " saved in " +\
self.get_sources_to_test_repo() + test_path
def create_main_cmake_lists(self):
buf = "cmake_minimum_required(VERSION 2.6.0)\n\n"
buf += "project(OCF_unit_tests C)\n\n"
buf += "enable_testing()\n\n"
buf += "include_directories(\n"
dirs_to_inc = self.get_dirs_to_include_list() + self.get_framework_includes()\
+ self.get_tests_internal_includes_list()
for path in dirs_to_inc:
buf += "\t" + path + "\n"
buf += ")\n\n"
includes = self.get_tests_internal_includes_list()
for path in includes:
buf += "\nadd_subdirectory(" + path + ")"
buf += "\n\n"
test_files = self.get_files_with_tests_list()
test_dirs_to_include = [os.path.dirname(path) for path in test_files]
test_dirs_to_include = self.remove_duplicates_from_list(test_dirs_to_include)
for path in test_dirs_to_include:
buf += "\nadd_subdirectory(" + self.get_sources_to_test_repo() + path + ")"
with open(self.get_main_UT_dir() + "CMakeLists.txt", "w") as f:
f.writelines(buf)
print "Main CMakeLists.txt generated written to " + self.get_main_UT_dir() + "CMakeLists.txt"
def generate_cmakes_for_tests(self):
test_files_paths = self.get_files_with_tests_list()
for test_path in test_files_paths:
tested_file_path = self.get_sources_to_test_repo() + test_path
if not os.path.isfile(tested_file_path):
print "No source to test for " + test_path + " test"
continue
test_file_path = self.get_main_UT_dir() + test_path
cmake_buf = self.generate_test_cmake_buf(test_file_path, tested_file_path)
cmake_path = self.get_sources_to_test_repo() + test_path
cmake_path = os.path.splitext(cmake_path)[0] + ".cmake"
with open(cmake_path, "w") as f:
f.writelines(cmake_buf)
print "cmake file for " + test_path + " written to " + cmake_path
cmake_lists_path = os.path.dirname(cmake_path) + os.sep
self.update_cmakelists(cmake_lists_path, cmake_path)
def generate_test_cmake_buf(self, test_file_path, tested_file_path):
test_file_name = os.path.basename(test_file_path)
target_name = os.path.splitext(test_file_name)[0]
add_executable = "add_executable(" + target_name + " " + test_file_path + " " + tested_file_path + ")\n"
libraries = "target_link_libraries(" + target_name + " libcmocka.so ocf_env)\n"
add_test = "add_test(" + target_name + " ${CMAKE_CURRENT_BINARY_DIR}/" + target_name + ")\n"
tgt_properties = "set_target_properties(" + target_name + "\n" + \
"PROPERTIES\n" + \
"COMPILE_FLAGS \"-fno-inline -Dstatic= -Dinline= -w \"\n"
link_flags = self.generate_cmake_link_flags(test_file_path)
tgt_properties += link_flags + ")"
buf = add_executable + libraries + add_test + tgt_properties
return buf
def generate_cmake_link_flags(self, path):
ret = ""
functions_to_wrap = self.get_functions_to_wrap(path)
for function_name in functions_to_wrap:
ret += ",--wrap=" + function_name
if len(ret) > 0:
ret = "LINK_FLAGS \"-Wl" + ret + "\"\n"
return ret
def update_cmakelists(self, cmake_lists_path, cmake_name):
with open(cmake_lists_path + "CMakeLists.txt", "a+") as f:
f.seek(0, os.SEEK_SET)
new_line = "include(" + os.path.basename(cmake_name) + ")\n"
if not new_line in f.read():
f.write(new_line)
def get_functions_to_wrap(self, path):
functions_list = self.get_functions_list(path)
functions_list = [re.sub(r'__wrap_([\S]+)\s*[\d]+', r'\1', line) for line in functions_list if re.search("__wrap_", line)]
return functions_list
def get_functions_to_leave(self, path):
with open(path) as f:
l = f.readlines()
buf = ''.join(l)
tags_pattern = re.compile("<functions_to_leave>[\s\S]*</functions_to_leave>")
buf = re.findall(tags_pattern, buf)
if not len(buf) > 0:
return []
buf = buf[0]
buf = re.sub(r'<.*>', '', buf)
buf = re.sub(r'[^a-zA-Z0-9_\n]+', '', buf)
ret = buf.split("\n")
ret = [name for name in ret if name]
return ret
def get_functions_list(self, file_path):
ctags_path = self.get_ctags_path()
# find all functions' definitions | put tabs instead of spaces |
# take only columns with function name and line number | sort in descending order
status, output = commands.getstatusoutput(ctags_path + "-x --c-types=f " + file_path + " --language-force=c | \
sed \"s/ \\+/\t/g\" | cut -f 1,3 | sort -nsr -k 2")
# 'output' is string, but it has to be changed to list
output = output.split("\n")
return output
def remove_functions_from_list(self, functions_list, to_remove_list):
ret = functions_list[:]
for function_name in to_remove_list:
ret = [line for line in ret if not re.search(r'\b%s\b' % function_name, line)]
return ret
def get_src_to_test(self, test_path, preprocessed_tested_path):
functions_to_leave = self.get_functions_to_leave(self.get_main_UT_dir() + test_path)
functions_to_leave.append(self.get_tested_function_name(self.get_main_UT_dir() + test_path))
functions_list = self.get_functions_list(preprocessed_tested_path)
functions_list = self.remove_functions_from_list(functions_list, functions_to_leave)
with open(preprocessed_tested_path) as f:
ret = f.readlines()
for function in functions_list:
line = function.split("\t")[1]
line = int(line)
self.remove_function_body(ret, line)
return ret
def set_tested_files_paths_list(self):
test_files_list = self.get_files_with_tests_list()
for f in test_files_list:
self.tested_files_paths_list.append(self.get_main_tested_dir() +\
self.get_tested_file_path(self.get_main_UT_dir() + f))
self.tested_files_paths_list = self.remove_duplicates_from_list(self.tested_files_paths_list)
def get_tested_files_paths_list(self):
return self.tested_files_paths_list
def get_files_with_tests_list(self):
return self.test_files_paths_list
def set_files_with_tests_list(self):
test_catalogues_list = self.get_tests_catalouges_list()
for catalogue in test_catalogues_list:
dir_with_tests_path = self.get_main_UT_dir() + catalogue
for path, dirs, files in os.walk(dir_with_tests_path):
test_files = self.get_test_files_from_dir(path + os.sep)
for test_file_name in test_files:
test_rel_path = os.path.relpath(path + os.sep + test_file_name, self.get_main_UT_dir())
self.test_files_paths_list.append(test_rel_path)
def are_markups_valid(self, path):
file_path = self.get_tested_file_path(path)
function_name = self.get_tested_function_name(path)
if file_path is None:
print path + " file has no tested_file tag!"
return None
elif not os.path.isfile(self.get_main_tested_dir() + file_path):
print "Tested file given in " + path + " not exist!"
return None
if function_name is None:
print path + " file has no tested_function_name tag!"
return None
return True
def create_dir_if_not_exist(self, path):
if not os.path.isdir(path):
try:
os.makedirs(path)
except Exception:
pass
return True
return None
def get_tested_file_path(self, test_file_path):
with open(test_file_path) as f:
buf = f.readlines()
buf = ''.join(buf)
tags_pattern = re.compile("<tested_file_path>[\s\S]*</tested_file_path>")
buf = re.findall(tags_pattern, buf)
if not len(buf) > 0:
return None
buf = buf[0]
buf = re.sub(r'<[^>]*>', '', buf)
buf = re.sub(r'\s+', '', buf)
if len(buf) > 0:
return buf
return None
def get_tested_function_name(self, test_file_path):
with open(test_file_path) as f:
buf = f.readlines()
buf = ''.join(buf)
tags_pattern = re.compile("<tested_function>[\s\S]*</tested_function>")
buf = re.findall(tags_pattern, buf)
if not len(buf) > 0:
return None
buf = buf[0]
buf = re.sub(r'<[^>]*>', '', buf)
buf = re.sub('//', '', buf)
buf = re.sub(r'\s+', '', buf)
if len(buf) > 0:
return buf
return None
def get_test_files_from_dir(self, path):
ret = os.listdir(path)
ret = [name for name in ret if os.path.isfile(path + os.sep + name) and (name.endswith(".c") or name.endswith(".h"))]
ret = [name for name in ret if self.are_markups_valid(path + name)]
return ret
def get_list_of_directories(self, path):
if not os.path.isdir(path):
return []
ret = os.listdir(path)
ret = [name for name in ret if not os.path.isfile(path + os.sep + name)]
ret = [os.path.normpath(name) + os.sep for name in ret]
return ret
def remove_hashes(self, path):
with open(path) as f:
buf = f.readlines()
buf = [l for l in buf if not re.search(r'.*#.*', l)]
with open(path, "w") as f:
f.writelines(buf)
return
for i in range(len(padding)):
try:
padding[i] = padding[i].split("#")[0]
except ValueError:
continue
f = open(path, "w")
f.writelines(padding)
f.close()
def find_function_end(self,code_lines_list, first_line_of_function_index):
brackets_counter = 0
current_line_index = first_line_of_function_index
while True:
if "{" in code_lines_list[current_line_index]:
brackets_counter += code_lines_list[current_line_index].count("{")
brackets_counter -= code_lines_list[current_line_index].count("}")
break
else:
current_line_index += 1
while brackets_counter > 0:
current_line_index += 1
if "{" in code_lines_list[current_line_index]:
brackets_counter += code_lines_list[current_line_index].count("{")
brackets_counter -= code_lines_list[current_line_index].count("}")
elif "}" in code_lines_list[current_line_index]:
brackets_counter -= code_lines_list[current_line_index].count("}")
return current_line_index
def remove_function_body(self, code_lines_list, line_id):
try:
while "{" not in code_lines_list[line_id]:
if ";" in code_lines_list[line_id]:
return
line_id += 1
except IndexError:
return
last_line_id = self.find_function_end(code_lines_list, line_id)
code_lines_list[line_id] = code_lines_list[line_id].split("{")[0]
code_lines_list[line_id] += ";"
del code_lines_list[line_id + 1: last_line_id + 1]
def set_ctags_path(self):
status, output = commands.getstatusoutput("/usr/bin/ctags --version &> /dev/null")
if status == 0:
path = "/usr/bin/ctags "
status, output = commands.getstatusoutput(path + "--c-types=f")
if not re.search("unrecognized option", output, re.IGNORECASE):
self.ctags_path = path
return
status, output = commands.getstatusoutput("/usr/local/bin/ctags --version &> /dev/null")
if status == 0:
path = "/usr/local/bin/ctags "
status, output = commands.getstatusoutput(path + "--c-types=f")
if not re.search("unrecognized option", output, re.IGNORECASE):
self.ctags_path = path
return
print "ERROR: Current ctags version don't support \"--c-types=f\" parameter!"
exit(1)
def get_ctags_path(self):
return self.ctags_path
def get_tests_catalouges_list(self):
return self.test_catalouges_list
def get_relative_path(self, original_path, part_to_remove):
return original_path.split(part_to_remove, 1)[1]
def get_dirs_to_include_list(self):
return self.dirs_to_include_list
def set_dirs_to_include(self):
self.dirs_to_include_list = [self.get_main_tested_dir() + name\
for name in tests_config.DIRECTORIES_TO_INCLUDE_FROM_PROJECT_LIST]
def set_tests_internal_includes_list(self):
self.tests_internal_includes_list = [self.get_main_UT_dir() + name\
for name in tests_config.DIRECTORIES_TO_INCLUDE_FROM_UT_LIST]
def set_preprocessing_repo(self):
self.preprocessing_repo = self.get_main_UT_dir() +\
tests_config.PREPROCESSED_SOURCES_REPOSITORY
def set_sources_to_test_repo(self):
self.sources_to_test_repo = self.get_main_UT_dir() +\
tests_config.SOURCES_TO_TEST_REPOSITORY
def get_sources_to_test_repo(self):
return self.sources_to_test_repo
def get_preprocessing_repo(self):
return self.preprocessing_repo
def get_tests_internal_includes_list(self):
return self.tests_internal_includes_list
def get_script_dir_path(self):
return os.path.normpath(self.script_dir_abs_path) + os.sep
def get_main_UT_dir(self):
return os.path.normpath(self.main_UT_dir) + os.sep
def get_main_tested_dir(self):
return os.path.normpath(self.main_tested_dir) + os.sep
def remove_duplicates_from_list(self, l):
return list(set(l))
def set_framework_includes(self):
self.framework_includes = tests_config.FRAMEWORK_DIRECTORIES_TO_INCLUDE_LIST
def get_framework_includes(self):
return self.framework_includes
def set_includes_to_copy_dict(self, files_to_copy_dict):
self.includes_to_copy_dict = files_to_copy_dict
def get_includes_to_copy_dict(self):
return self.includes_to_copy_dict
def set_main_UT_dir(self):
main_UT_dir = os.path.normpath(os.path.normpath(self.get_script_dir_path()\
+ os.sep + tests_config.MAIN_DIRECTORY_OF_UNIT_TESTS))
if not os.path.isdir(main_UT_dir):
print "Given path to main UT directory is wrong!"
sys.exit(1)
self.main_UT_dir = main_UT_dir
def set_main_tested_dir(self):
main_tested_dir = os.path.normpath(os.path.normpath(self.get_script_dir_path()\
+ os.sep + tests_config.MAIN_DIRECTORY_OF_TESTED_PROJECT))
if not os.path.isdir(main_tested_dir):
print "Given path to main tested directory is wrong!"
sys.exit(1)
self.main_tested_dir = main_tested_dir
def __main__():
generator = UnitTestsSourcesGenerator()
generator.copy_includes()
generator.preprocessing()
generator.prepare_sources_for_testing()
generator.create_main_cmake_lists()
generator.generate_cmakes_for_tests()
print "Files for testing generated!"
if __name__ == "__main__":
__main__()

View File

@@ -0,0 +1,46 @@
#!/usr/bin/env python2
#
# Copyright(c) 2012-2018 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause-Clear
#
import tests_config
import os
import commands
script_path = os.path.dirname(os.path.realpath(__file__))
main_UT_dir = os.path.normpath(script_path + os.sep\
+ tests_config.MAIN_DIRECTORY_OF_UNIT_TESTS) + os.sep
main_tested_dir = os.path.normpath(script_path + os.sep\
+ tests_config.MAIN_DIRECTORY_OF_TESTED_PROJECT) + os.sep
if not os.path.isdir(main_UT_dir + "ocf_env" + os.sep + "ocf"):
try:
os.makedirs(main_UT_dir + "ocf_env" + os.sep + "ocf")
except Exception:
print "Cannot crate ocf_env/ocf directory!"
status, output = commands.getstatusoutput("cp " + main_tested_dir +\
"inc" + os.sep + "*" + " " + main_UT_dir + "ocf_env" + os.sep + "ocf")
if os.system(script_path + os.sep + "prepare_sources_for_testing.py") != 0:
print "Preparing sources for testing failed!"
exit()
build_dir = main_UT_dir + "build" + os.sep
if not os.path.isdir(build_dir):
try:
os.makedirs(build_dir)
except Exception:
print "Cannot crate build directory!"
status, output = commands.getstatusoutput("cd " + build_dir + " && cmake .. && make && make test")
print output

View File

@@ -0,0 +1,35 @@
#!/usr/bin/env python2
#
# Copyright(c) 2012-2018 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause-Clear
#
# ALL PATHS SHOULD BE ENDED WITH "/" CHARACTER
MAIN_DIRECTORY_OF_TESTED_PROJECT = "../../../"
MAIN_DIRECTORY_OF_UNIT_TESTS = "../tests/"
# Paths to all directories, in which tests are stored. All paths should be relative to MAIN_DIRECTORY_OF_UNIT_TESTS
DIRECTORIES_WITH_TESTS_LIST = ["cleaning/", "metadata/", "mngt/", "concurrency/", "engine/", "eviction/", "utils/"]
# Paths to all directories containing files with sources. All paths should be relative to MAIN_DIRECTORY_OF_TESTED_PROJECT
DIRECTORIES_TO_INCLUDE_FROM_PROJECT_LIST = ["src/", "src/cleaning/", "src/engine/", "src/metadata/", "src/eviction/", "src/mngt/", "src/concurrency/", "src/utils/", "inc/"]
# Paths to all directories from directory with tests, which should also be included
DIRECTORIES_TO_INCLUDE_FROM_UT_LIST = ["ocf_env/"]
# Paths to include, required by cmake, cmocka, cunit
FRAMEWORK_DIRECTORIES_TO_INCLUDE_LIST = ["${CMOCKA_PUBLIC_INCLUDE_DIRS}" ,"${CMAKE_BINARY_DIR}", "${CMAKE_CURRENT_SOURCE_DIR}"]
# Path to directory containing all sources after preprocessing. Should be relative to MAIN_DIRECTORY_OF_UNIT_TESTS
PREPROCESSED_SOURCES_REPOSITORY = "preprocessed_sources_repository/"
# Path to directory containing all sources after removing unneeded functions and cmake files for tests
SOURCES_TO_TEST_REPOSITORY = "sources_to_test_repository/"
# List of includes. Directories will be recursively copied to given destinations in directory with tests.
# key - destination in dir with tests
# value - path in tested project to dir which should be copied
INCLUDES_TO_COPY_DICT = { 'ocf_env/ocf/' : "inc/" }

View File

@@ -0,0 +1,30 @@
#!/usr/bin/env python2
#
# Copyright(c) 2012-2018 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause-Clear
#
import commands
import sys
import os
args = ' '.join(sys.argv[1:])
script_path = os.path.dirname(os.path.realpath(__file__))
framework_script_path = script_path + os.sep + "../framework/add_new_test_file.py"
framework_script_path = os.path.normpath(framework_script_path)
status, output = commands.getstatusoutput(framework_script_path + " " + args)
print output
if status == 0:
path = output.split(" ", 1)[0]
with open(script_path + os.sep + "header.c", "r") as header_file:
with open(path, "r+") as source_file:
source = source_file.readlines()
source_file.seek(0, os.SEEK_SET)
source_file.truncate()
source_file.writelines(header_file.readlines())
source_file.writelines(source)

View File

@@ -0,0 +1,122 @@
/*
* Copyright(c) 2012-2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause-Clear
*/
/*
<tested_file_path>src/cleaning/alru.c</tested_file_path>
<tested_function>cleaning_policy_alru_initialize_part</tested_function>
<functions_to_leave>
</functions_to_leave>
*/
#undef static
#undef inline
/*
* This headers must be in test source file. It's important that cmocka.h is
* last.
*/
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "print_desc.h"
/*
* Headers from tested target.
*/
#include "ocf/ocf.h"
#include "../ocf_cache_priv.h"
#include "cleaning.h"
#include "alru.h"
#include "../metadata/metadata.h"
#include "../utils/utils_cleaner.h"
#include "../utils/utils_part.h"
#include "../utils/utils_allocator.h"
#include "../concurrency/ocf_cache_concurrency.h"
#include "../ocf_def_priv.h"
void _alru_rebuild(struct ocf_cache *cache)
{
}
static void cleaning_policy_alru_initialize_test01(void **state)
{
int result;
struct ocf_cache cache;
ocf_part_id_t part_id = 0;
int collision_table_entries = 900729;
print_test_description("Check if all variables are set correctly");
cache.user_parts[part_id].runtime = test_malloc(sizeof(struct ocf_user_part_runtime));
cache.device = test_malloc(sizeof(struct ocf_cache_device));
cache.device->runtime_meta = test_malloc(sizeof(struct ocf_superblock_runtime));
cache.device->collision_table_entries = collision_table_entries;
result = cleaning_policy_alru_initialize_part(&cache, &cache.user_parts[part_id], 1, 1);
assert_int_equal(result, 0);
assert_int_equal(cache.user_parts[part_id].runtime->cleaning.policy.alru.size, 0);
assert_int_equal(cache.user_parts[part_id].runtime->cleaning.policy.alru.lru_head, collision_table_entries);
assert_int_equal(cache.user_parts[part_id].runtime->cleaning.policy.alru.lru_tail, collision_table_entries);
assert_int_equal(cache.device->runtime_meta->cleaning_thread_access, 0);
test_free(cache.device->runtime_meta);
test_free(cache.device);
test_free(cache.user_parts[part_id].runtime);
}
static void cleaning_policy_alru_initialize_test02(void **state)
{
int result;
struct ocf_cache cache;
ocf_part_id_t part_id = 0;
uint32_t collision_table_entries = 900729;
print_test_description("Check if only appropirate variables are changed");
cache.user_parts[part_id].runtime = test_malloc(sizeof(struct ocf_user_part_runtime));
cache.device = test_malloc(sizeof(struct ocf_cache_device));
cache.device->runtime_meta = test_malloc(sizeof(struct ocf_superblock_runtime));
cache.user_parts[part_id].runtime->cleaning.policy.alru.size = 1;
cache.user_parts[part_id].runtime->cleaning.policy.alru.lru_head = -collision_table_entries;
cache.user_parts[part_id].runtime->cleaning.policy.alru.lru_tail = -collision_table_entries;
result = cleaning_policy_alru_initialize_part(&cache, &cache.user_parts[part_id], 0, 0);
assert_int_equal(result, 0);
assert_int_equal(cache.user_parts[part_id].runtime->cleaning.policy.alru.size, 1);
assert_int_equal(cache.user_parts[part_id].runtime->cleaning.policy.alru.lru_head, -collision_table_entries);
assert_int_equal(cache.user_parts[part_id].runtime->cleaning.policy.alru.lru_tail, -collision_table_entries);
assert_int_equal(cache.device->runtime_meta->cleaning_thread_access, 0);
test_free(cache.device->runtime_meta);
test_free(cache.device);
test_free(cache.user_parts[part_id].runtime);
}
/*
* Main function. It runs tests.
*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(cleaning_policy_alru_initialize_test01),
cmocka_unit_test(cleaning_policy_alru_initialize_test02)
};
print_message("Unit test of alru.c\n");
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -0,0 +1,258 @@
/*
* Copyright(c) 2012-2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause-Clear
*/
/*
* This headers must be in test source file. It's important that cmocka.h is
* last.
*/
#undef static
#undef inline
//<tested_file_path>src/cleaning/cleaning.c</tested_file_path>
//<tested_function>ocf_cleaner_run</tested_function>
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "print_desc.h"
/*
* Headers from tested target.
*/
#include "cleaning.h"
#include "alru.h"
#include "acp.h"
#include "../ocf_cache_priv.h"
#include "../ocf_ctx_priv.h"
#include "../mngt/ocf_mngt_common.h"
#include "../metadata/metadata.h"
/*
* Mocked functions. Here we must deliver functions definitions which are not
* in tested source file.
*/
void __wrap_cleaning_policy_alru_setup(struct ocf_cache *cache)
{}
int __wrap_cleaning_policy_alru_set_cleaning_param(struct ocf_cache *cache,
uint32_t param_id, uint32_t param_value)
{
}
int __wrap_cleaning_policy_alru_get_cleaning_param(struct ocf_cache *cache,
uint32_t param_id, uint32_t *param_value)
{
}
int __wrap_cleaning_policy_acp_initialize(struct ocf_cache *cache,
int init_metadata, int init_params){}
void __wrap_cleaning_policy_acp_deinitialize(struct ocf_cache *cache){}
int __wrap_cleaning_policy_acp_perform_cleaning(struct ocf_cache *cache,
uint32_t io_queue){}
void __wrap_cleaning_policy_acp_init_cache_block(struct ocf_cache *cache,
uint32_t cache_line){}
void __wrap_cleaning_policy_acp_set_hot_cache_line(struct ocf_cache *cache,
uint32_t cache_line){}
void __wrap_cleaning_policy_acp_purge_block(struct ocf_cache *cache,
uint32_t cache_line){}
int __wrap_cleaning_policy_acp_purge_range(struct ocf_cache *cache,
int core_id, uint64_t start_byte, uint64_t end_byte){}
int __wrap_cleaning_policy_acp_add_core(ocf_cache_t cache, ocf_core_id_t core_id){}
int __wrap_cleaning_policy_acp_remove_core(ocf_cache_t cache,
ocf_core_id_t core_id){}
void __wrap_cleaning_policy_acp_request_pending(struct ocf_request *req){
}
void cleaning_policy_acp_setup(struct ocf_cache *cache)
{
}
int cleaning_policy_acp_set_cleaning_param(struct ocf_cache *cache,
uint32_t param_id, uint32_t param_value)
{
}
int cleaning_policy_acp_get_cleaning_param(struct ocf_cache *cache,
uint32_t param_id, uint32_t *param_value)
{
}
int __wrap_cleaning_policy_acp_set_cleaning_parameters(
struct ocf_cache *cache, struct ocf_cleaning_params *params)
{
}
void __wrap_cleaning_policy_acp_get_cleaning_parameters(
struct ocf_cache *cache, struct ocf_cleaning_params *params)
{
}
void __wrap_cleaning_policy_alru_init_cache_block(struct ocf_cache *cache,
uint32_t cache_line)
{
}
void __wrap_cleaning_policy_alru_purge_cache_block(struct ocf_cache *cache,
uint32_t cache_line)
{
}
int __wrap_cleaning_policy_alru_purge_range(struct ocf_cache *cache,
int partition_id, int core_id, uint64_t start_byte,
uint64_t end_byte)
{
}
void __wrap_cleaning_policy_alru_set_hot_cache_line(struct ocf_cache *cache,
uint32_t cache_line)
{
}
int __wrap_cleaning_policy_alru_initialize(struct ocf_cache *cache, int partition_id,
int init_metadata)
{
}
int __wrap_cleaning_policy_alru_flush_block(struct ocf_cache *cache,
uint32_t io_queue, uint32_t count, uint32_t *cache_lines,
int partition_id, int core_id, uint8_t do_lock)
{
}
int __wrap_cleaning_policy_alru_set_cleaning_parameters(ocf_cache_t cache,
ocf_part_id_t part_id, struct ocf_cleaning_params *params)
{
}
void __wrap_cleaning_policy_alru_get_cleaning_parameters(ocf_cache_t cache,
ocf_part_id_t part_id, struct ocf_cleaning_params *params)
{
}
int __wrap_cleaning_alru_perform_cleaning(struct ocf_cache *cache, uint32_t io_queue)
{
function_called();
return mock();
}
ocf_cache_t __wrap_ocf_cleaner_get_cache(ocf_cleaner_t c)
{
function_called();
return mock_ptr_type(struct ocf_cache*);
}
bool __wrap_ocf_mngt_is_cache_locked(ocf_cache_t cache)
{
function_called();
return mock();
}
int __wrap__ocf_cleaner_run_check_dirty_inactive(struct ocf_cache *cache)
{
function_called();
return mock();
}
int __wrap_env_bit_test(int nr, const void *addr)
{
function_called();
return mock();
}
int __wrap_env_rwsem_down_write_trylock(env_rwsem *s)
{
function_called();
return mock();
}
void __wrap_env_rwsem_up_write(env_rwsem *s)
{
function_called();
}
/*
* Tests of functions. Every test name must be written to tests array in main().
* Declarations always look the same: static void test_name(void **state);
*/
static void ocf_cleaner_run_test01(void **state)
{
struct ocf_cache cache;
ocf_part_id_t part_id;
uint32_t io_queue;
int result;
//Initialize needed structures.
cache.conf_meta = test_malloc(sizeof(struct ocf_superblock_config));
cache.conf_meta->cleaning_policy_type = ocf_cleaning_alru;
print_test_description("Parts are ready for cleaning - should perform cleaning"
" for each part");
expect_function_call(__wrap_ocf_cleaner_get_cache);
will_return(__wrap_ocf_cleaner_get_cache, &cache);
expect_function_call(__wrap_env_bit_test);
will_return(__wrap_env_bit_test, 1);
expect_function_call(__wrap_ocf_mngt_is_cache_locked);
will_return(__wrap_ocf_mngt_is_cache_locked, 0);
expect_function_call(__wrap_env_rwsem_down_write_trylock);
will_return(__wrap_env_rwsem_down_write_trylock, 1);
expect_function_call(__wrap__ocf_cleaner_run_check_dirty_inactive);
will_return(__wrap__ocf_cleaner_run_check_dirty_inactive, 0);
expect_function_call(__wrap_cleaning_alru_perform_cleaning);
will_return(__wrap_cleaning_alru_perform_cleaning, 0);
expect_function_call(__wrap_env_rwsem_up_write);
result = ocf_cleaner_run(&cache.cleaner, io_queue);
assert_int_equal(result, 0);
/* Release allocated memory if allocated with test_* functions */
test_free(cache.conf_meta);
}
/*
* Main function. It runs tests.
*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(ocf_cleaner_run_test01)
};
print_message("Unit test of cleaning.c\n");
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -0,0 +1,5 @@
/*
* Copyright(c) 2012-2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause-Clear
*/

View File

@@ -0,0 +1,105 @@
/*
* Copyright(c) 2012-2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause-Clear
*/
//<tested_file_path>src/metadata/metadata_io.c</tested_file_path>
//<tested_function>metadata_io</tested_function>
#undef static
#undef inline
/*
* This headers must be in test source file. It's important that cmocka.h is
* last.
*/
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "print_desc.h"
/*
* Headers from tested target.
*/
#include "metadata.h"
#include "metadata_io.h"
#include "../engine/cache_engine.h"
#include "../engine/engine_common.h"
#include "../engine/engine_bf.h"
#include "../utils/utils_cache_line.h"
#include "../utils/utils_io.h"
#include "../utils/utils_allocator.h"
#include "../ocf_def_priv.h"
uint32_t __wrap_metadata_io_max_page(struct ocf_cache *cache)
{
function_called();
return mock();
}
void __wrap_env_cond_resched(void)
{
}
void __wrap_ocf_engine_push_req_front(struct ocf_request *req)
{
}
int __wrap_ocf_realloc(void **mem, size_t size, size_t count, size_t *limit)
{
}
int __wrap_ocf_realloc_cp(void **mem, size_t size, size_t count, size_t *limit)
{
}
ocf_ctx_t __wrap_ocf_cache_get_ctx(ocf_cache_t cache)
{
}
int __wrap_ocf_log_raw(const struct ocf_logger *logger, ocf_logger_lvl_t lvl,
const char *fmt, ...)
{
}
int __wrap_metadata_submit_io(
struct ocf_cache *cache,
struct metadata_io *mio,
uint32_t count,
uint32_t written)
{
}
int __wrap_ocf_restart_meta_io(struct ocf_request *req)
{
}
static void metadata_io_test01(void **state)
{
int result;
struct metadata_io mio;
struct ocf_cache cache;
print_test_description("Check error no. when invalid operation is given");
mio.dir = -1;
mio.cache = &cache;
expect_function_call(__wrap_metadata_io_max_page);
will_return(__wrap_metadata_io_max_page, 256);
result = metadata_io(&mio);
assert_int_equal(result, -EINVAL);
}
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(metadata_io_test01)
};
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -0,0 +1,245 @@
/*
* Copyright(c) 2012-2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause-Clear
*/
//<tested_file_path>src/metadata/metadata_io.c</tested_file_path>
//<tested_function>metadata_submit_io</tested_function>
#undef static
#undef inline
/*
* This headers must be in test source file. It's important that cmocka.h is
* last.
*/
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "print_desc.h"
/*
* Headers from tested target.
*/
#include "metadata.h"
#include "metadata_io.h"
#include "../engine/cache_engine.h"
#include "../engine/engine_common.h"
#include "../engine/engine_bf.h"
#include "../utils/utils_cache_line.h"
#include "../utils/utils_allocator.h"
#include "../ocf_def_priv.h"
struct ocf_io *__wrap_ocf_new_cache_io(struct ocf_cache *cache)
{
function_called();
return mock_ptr_type(struct ocf_io *);
}
int __wrap_metadata_io_write_fill(struct ocf_cache *cache,
ctx_data_t *data, uint32_t page, void *context)
{
function_called();
return mock();
}
void *__wrap_ctx_data_alloc(ocf_ctx_t ctx, uint32_t pages)
{
function_called();
return mock_ptr_type(void*);
}
void __wrap_ocf_io_configure(struct ocf_io *io, uint64_t addr,
uint32_t bytes, uint32_t dir, uint32_t class, uint64_t flags)
{
function_called();
}
void __wrap_metadata_io_end(struct ocf_io *io, int error)
{
}
void __wrap_ocf_io_set_cmpl(struct ocf_io *io, void *context,
void *context2, ocf_end_io_t fn)
{
function_called();
}
int __wrap_ocf_io_set_data(struct ocf_io *io, ctx_data_t *data,
uint32_t offset)
{
function_called();
return mock();
}
void __wrap_ocf_dobj_submit_io(struct ocf_io *io)
{
function_called();
}
void __wrap_ctx_data_free(ocf_ctx_t ctx, ctx_data_t *data)
{
function_called();
}
void __wrap_ocf_io_put(struct ocf_io *io)
{
function_called();
}
int __wrap_ocf_restart_meta_io(struct ocf_request *req)
{
}
void __wrap_env_atomic_inc(env_atomic *a)
{
function_called();
}
static void metadata_submit_io_test01(void **state)
{
int result;
struct metadata_io mio;
struct ocf_cache cache;
uint32_t count;
uint32_t written;
print_test_description("Couldn't allocate new IO");
expect_function_call(__wrap_ocf_new_cache_io);
will_return(__wrap_ocf_new_cache_io, 0);
result = metadata_submit_io(&cache, &mio, count, written);
assert_int_equal(result, -ENOMEM);
assert_int_equal(mio.error, -ENOMEM);
}
static void metadata_submit_io_test02(void **state)
{
int result;
struct metadata_io mio;
struct ocf_cache cache;
uint32_t count;
uint32_t written;
print_test_description("Couldn't allocate data buffer for IO");
expect_function_call(__wrap_ocf_new_cache_io);
will_return(__wrap_ocf_new_cache_io, 1);
expect_function_call(__wrap_ctx_data_alloc);
will_return(__wrap_ctx_data_alloc, 0);
expect_function_call(__wrap_ocf_io_put);
result = metadata_submit_io(&cache, &mio, count, written);
assert_int_equal(result, -ENOMEM);
assert_int_equal(mio.error, -ENOMEM);
}
static void metadata_submit_io_test03(void **state)
{
int result;
struct metadata_io mio;
struct ocf_cache cache;
uint32_t count;
uint32_t written;
int mio_err = 0;
print_test_description("Write operation is performed successfully");
mio.hndl_fn = __wrap_metadata_io_write_fill;
mio.dir = OCF_WRITE;
mio.error = mio_err;
count = 1;
expect_function_call(__wrap_ocf_new_cache_io);
will_return(__wrap_ocf_new_cache_io, 1);
expect_function_call(__wrap_ctx_data_alloc);
will_return(__wrap_ctx_data_alloc, 1);
expect_function_call(__wrap_metadata_io_write_fill);
will_return(__wrap_metadata_io_write_fill, 0);
expect_function_call(__wrap_ocf_io_configure);
expect_function_call(__wrap_ocf_io_set_cmpl);
expect_function_call(__wrap_ocf_io_set_data);
will_return(__wrap_ocf_io_set_data, 0);
expect_function_call(__wrap_env_atomic_inc);
expect_function_call(__wrap_ocf_dobj_submit_io);
result = metadata_submit_io(&cache, &mio, count, written);
assert_int_equal(result, 0);
assert_int_equal(mio.error, mio_err);
}
static void metadata_submit_io_test04(void **state)
{
int result;
int i;
int interations_before_fail;
struct metadata_io mio;
struct ocf_cache cache;
uint32_t count;
uint32_t written;
print_test_description("Write operation is performed, but if fails at 3rd iteration");
mio.hndl_fn = __wrap_metadata_io_write_fill;
mio.dir = OCF_WRITE;
count = 3;
interations_before_fail = 2;
expect_function_call(__wrap_ocf_new_cache_io);
will_return(__wrap_ocf_new_cache_io, 1);
expect_function_call(__wrap_ctx_data_alloc);
will_return(__wrap_ctx_data_alloc, 1);
for (i = 0; i < interations_before_fail; i++) {
expect_function_call(__wrap_metadata_io_write_fill);
will_return(__wrap_metadata_io_write_fill, 0);
}
expect_function_call(__wrap_metadata_io_write_fill);
will_return(__wrap_metadata_io_write_fill, 1);
expect_function_call(__wrap_ctx_data_free);
expect_function_call(__wrap_ocf_io_put);
result = metadata_submit_io(&cache, &mio, count, written);
assert_int_equal(result, 1);
assert_int_equal(mio.error, 1);
}
/*
* Main function. It runs tests.
*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(metadata_submit_io_test01),
cmocka_unit_test(metadata_submit_io_test02),
cmocka_unit_test(metadata_submit_io_test03),
cmocka_unit_test(metadata_submit_io_test04)
};
print_message("Example template for tests\n");
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -0,0 +1,370 @@
/*
* Copyright(c) 2012-2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause-Clear
*/
//<tested_file_path>src/mngt/ocf_mngt_cache.c</tested_file_path>
//<tested_function>_cache_mng_set_cache_mode</tested_function>
/*
<functions_to_leave>
</functions_to_leave>
*/
#undef static
#undef inline
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "print_desc.h"
/*
* Headers from tested target.
*/
#include "ocf/ocf.h"
#include "ocf_mngt_common.h"
#include "../ocf_core_priv.h"
#include "../ocf_queue_priv.h"
#include "../metadata/metadata.h"
#include "../engine/cache_engine.h"
#include "../utils/utils_part.h"
#include "../utils/utils_cache_line.h"
#include "../utils/utils_device.h"
#include "../utils/utils_io.h"
#include "../utils/utils_cache_line.h"
#include "../ocf_utils.h"
#include "../concurrency/ocf_concurrency.h"
#include "../eviction/ops.h"
#include "../ocf_ctx_priv.h"
#include "../cleaning/cleaning.h"
/*
* Mocked functions
*/
bool __wrap_ocf_cache_mode_is_valid(ocf_cache_mode_t mode)
{
function_called();
return mock();
}
const char *__wrap_ocf_get_io_iface_name(ocf_cache_mode_t cache_mode)
{
}
ocf_ctx_t __wrap_ocf_cache_get_ctx(ocf_cache_t cache)
{
return cache->owner;
}
int __wrap_ocf_log_raw(const struct ocf_logger *logger, ocf_logger_lvl_t lvl,
const char *fmt, ...)
{
function_called();
return mock();
}
int __wrap_ocf_mngt_cache_flush_nolock(ocf_cache_t cache, bool interruption)
{
function_called();
return mock();
}
int __wrap_ocf_metadata_flush_superblock(struct ocf_cache *cache)
{
function_called();
return mock();
}
bool __wrap_env_bit_test(int nr, const volatile unsigned long *addr)
{
function_called();
return mock();
}
void __wrap_env_atomic_set(env_atomic *a, int i)
{
function_called();
}
int __wrap_env_atomic_read(const env_atomic *a)
{
function_called();
return mock();
}
int __wrap_ocf_mngt_cache_reset_fallback_pt_error_counter(ocf_cache_t cache)
{
function_called();
return mock();
}
char *__wrap_ocf_cache_get_name(ocf_cache_t cache)
{
}
static void _cache_mng_set_cache_mode_test01(void **state)
{
ocf_cache_mode_t mode_old = -20;
ocf_cache_mode_t mode_new = ocf_cache_mode_none;
struct ocf_ctx ctx = {
.logger = 0x1, /* Just not NULL, we don't care. */
};
struct ocf_superblock_config sb_config = {
.cache_mode = mode_old,
};
struct ocf_cache cache = {
.owner = &ctx,
.conf_meta = &sb_config,
};
uint8_t flush = 0;
int result;
print_test_description("Invalid new mode produces appropirate error code");
expect_function_call(__wrap_ocf_cache_mode_is_valid);
will_return(__wrap_ocf_cache_mode_is_valid, 0);
result = _cache_mng_set_cache_mode(&cache, mode_new, flush);
assert_int_equal(result, -OCF_ERR_INVAL);
assert_int_equal(cache.conf_meta->cache_mode, mode_old);
}
static void _cache_mng_set_cache_mode_test02(void **state)
{
ocf_cache_mode_t mode_old = ocf_cache_mode_wt;
ocf_cache_mode_t mode_new = ocf_cache_mode_wt;
struct ocf_ctx ctx = {
.logger = 0x1, /* Just not NULL, we don't care. */
};
struct ocf_superblock_config sb_config = {
.cache_mode = mode_old,
};
struct ocf_cache cache = {
.owner = &ctx,
.conf_meta = &sb_config,
};
uint8_t flush = 0;
int result;
print_test_description("Attempt to set mode the same as previous");
expect_function_call(__wrap_ocf_cache_mode_is_valid);
will_return(__wrap_ocf_cache_mode_is_valid, 1);
expect_function_call(__wrap_ocf_log_raw);
will_return(__wrap_ocf_log_raw, 0);
result = _cache_mng_set_cache_mode(&cache, mode_new, flush);
assert_int_equal(result, 0);
assert_int_equal(cache.conf_meta->cache_mode, mode_old);
}
static void _cache_mng_set_cache_mode_test03(void **state)
{
ocf_cache_mode_t mode_old = ocf_cache_mode_wt;
ocf_cache_mode_t mode_new = ocf_cache_mode_pt;
struct ocf_ctx ctx = {
.logger = 0x1, /* Just not NULL, we don't care. */
};
struct ocf_superblock_config sb_config = {
.cache_mode = mode_old,
};
struct ocf_cache cache = {
.owner = &ctx,
.conf_meta = &sb_config,
};
uint8_t flush = 1;
int result;
print_test_description("Flush flag is set, but operation failed -"
" check if error code is correct");
expect_function_call(__wrap_ocf_cache_mode_is_valid);
will_return(__wrap_ocf_cache_mode_is_valid, 1);
expect_function_call(__wrap_ocf_mngt_cache_flush_nolock);
will_return(__wrap_ocf_mngt_cache_flush_nolock, -OCF_ERR_NO_MEM);
result = _cache_mng_set_cache_mode(&cache, mode_new, flush);
assert_int_equal(result, -OCF_ERR_NO_MEM);
assert_int_equal(cache.conf_meta->cache_mode, mode_old);
}
static void _cache_mng_set_cache_mode_test04(void **state)
{
ocf_cache_mode_t mode_old = ocf_cache_mode_wb;
ocf_cache_mode_t mode_new = ocf_cache_mode_wa;
struct ocf_ctx ctx = {
.logger = 0x1, /* Just not NULL, we don't care. */
};
struct ocf_superblock_config sb_config = {
.cache_mode = mode_old,
};
struct ocf_cache cache = {
.owner = &ctx,
.conf_meta = &sb_config,
};
uint8_t flush = 0;
int result;
int i;
print_test_description("Flush flag is not set, "
"old cache mode is write back. "
"Setting new cache mode is succesfull");
expect_function_call(__wrap_ocf_cache_mode_is_valid);
will_return(__wrap_ocf_cache_mode_is_valid, 1);
for(i = 0; i != OCF_CORE_MAX; ++i) {
expect_function_call(__wrap_env_bit_test);
will_return(__wrap_env_bit_test, 1);
expect_function_call(__wrap_env_atomic_read);
will_return(__wrap_env_atomic_read, 1);
expect_function_call(__wrap_env_atomic_set);
}
expect_function_call(__wrap_ocf_metadata_flush_superblock);
will_return(__wrap_ocf_metadata_flush_superblock, 0);
expect_function_call(__wrap_ocf_log_raw);
will_return(__wrap_ocf_log_raw, 0);
result = _cache_mng_set_cache_mode(&cache, mode_new, flush);
assert_int_equal(result, 0);
assert_int_equal(cache.conf_meta->cache_mode, mode_new);
}
static void _cache_mng_set_cache_mode_test05(void **state)
{
ocf_cache_mode_t mode_old = ocf_cache_mode_wt;
ocf_cache_mode_t mode_new = ocf_cache_mode_wa;
struct ocf_ctx ctx = {
.logger = 0x1, /* Just not NULL, we don't care. */
};
struct ocf_superblock_config sb_config = {
.cache_mode = mode_old,
};
struct ocf_cache cache = {
.owner = &ctx,
.conf_meta = &sb_config,
};
uint8_t flush = 0;
int result;
int i;
print_test_description("Flush flag is not set, "
"flushing metadata superblock fails");
expect_function_call(__wrap_ocf_cache_mode_is_valid);
will_return(__wrap_ocf_cache_mode_is_valid, 1);
expect_function_call(__wrap_ocf_metadata_flush_superblock);
will_return(__wrap_ocf_metadata_flush_superblock, 1);
expect_function_call(__wrap_ocf_log_raw);
will_return(__wrap_ocf_log_raw, 0);
result = _cache_mng_set_cache_mode(&cache, mode_new, flush);
assert_int_equal(result, -OCF_ERR_WRITE_CACHE);
assert_int_equal(cache.conf_meta->cache_mode, mode_old);
}
static void _cache_mng_set_cache_mode_test06(void **state)
{
ocf_cache_mode_t mode_old = ocf_cache_mode_wt;
ocf_cache_mode_t mode_new = ocf_cache_mode_wa;
struct ocf_ctx ctx = {
.logger = 0x1, /* Just not NULL, we don't care. */
};
struct ocf_superblock_config sb_config = {
.cache_mode = mode_old,
};
struct ocf_cache cache = {
.owner = &ctx,
.conf_meta = &sb_config,
};
uint8_t flush = 0;
int result;
int i;
print_test_description("No flush, mode changed successfully");
expect_function_call(__wrap_ocf_cache_mode_is_valid);
will_return(__wrap_ocf_cache_mode_is_valid, 1);
expect_function_call(__wrap_ocf_metadata_flush_superblock);
will_return(__wrap_ocf_metadata_flush_superblock, 0);
expect_function_call(__wrap_ocf_log_raw);
will_return(__wrap_ocf_log_raw, 0);
result = _cache_mng_set_cache_mode(&cache, mode_new, flush);
assert_int_equal(result, 0);
assert_int_equal(cache.conf_meta->cache_mode, mode_new);
}
static void _cache_mng_set_cache_mode_test07(void **state)
{
ocf_cache_mode_t mode_old = ocf_cache_mode_wt;
ocf_cache_mode_t mode_new = ocf_cache_mode_wa;
struct ocf_ctx ctx = {
.logger = 0x1, /* Just not NULL, we don't care. */
};
struct ocf_superblock_config sb_config = {
.cache_mode = mode_old,
};
struct ocf_cache cache = {
.owner = &ctx,
.conf_meta = &sb_config,
};
uint8_t flush = 1;
int result;
print_test_description("Flush performed, mode changed successfully");
expect_function_call(__wrap_ocf_cache_mode_is_valid);
will_return(__wrap_ocf_cache_mode_is_valid, 1);
expect_function_call(__wrap_ocf_mngt_cache_flush_nolock);
will_return(__wrap_ocf_mngt_cache_flush_nolock, 0);
expect_function_call(__wrap_ocf_metadata_flush_superblock);
will_return(__wrap_ocf_metadata_flush_superblock, 0);
expect_function_call(__wrap_ocf_log_raw);
will_return(__wrap_ocf_log_raw, 0);
result = _cache_mng_set_cache_mode(&cache, mode_new, flush);
assert_int_equal(result, 0);
assert_int_equal(cache.conf_meta->cache_mode, mode_new);
}
/*
* Main function. It runs tests.
*/
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(_cache_mng_set_cache_mode_test01),
cmocka_unit_test(_cache_mng_set_cache_mode_test02),
cmocka_unit_test(_cache_mng_set_cache_mode_test03),
cmocka_unit_test(_cache_mng_set_cache_mode_test04),
cmocka_unit_test(_cache_mng_set_cache_mode_test05),
cmocka_unit_test(_cache_mng_set_cache_mode_test06),
cmocka_unit_test(_cache_mng_set_cache_mode_test07)
};
print_message("Unit test of _cache_mng_set_cache_mode\n");
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -0,0 +1,180 @@
/*
*<tested_file_path>src/mngt/ocf_mngt_cache.c</tested_file_path>
* <tested_function>ocf_mngt_cache_set_fallback_pt_error_threshold</tested_function>
* <functions_to_leave>
* INSERT HERE LIST OF FUNCTIONS YOU WANT TO LEAVE
* ONE FUNCTION PER LINE
*</functions_to_leave>
*/
#undef static
#undef inline
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "print_desc.h"
#include "ocf/ocf.h"
#include "ocf_mngt_common.h"
#include "../ocf_core_priv.h"
#include "../ocf_queue_priv.h"
#include "../metadata/metadata.h"
#include "../engine/cache_engine.h"
#include "../utils/utils_part.h"
#include "../utils/utils_cache_line.h"
#include "../utils/utils_device.h"
#include "../utils/utils_io.h"
#include "../utils/utils_cache_line.h"
#include "../ocf_utils.h"
#include "../concurrency/ocf_concurrency.h"
#include "../eviction/ops.h"
#include "../ocf_ctx_priv.h"
#include "../cleaning/cleaning.h"
int __wrap_ocf_log_raw(const struct ocf_logger *logger, ocf_logger_lvl_t lvl,
const char *fmt, ...)
{
function_called();
}
ocf_ctx_t __wrap_ocf_cache_get_ctx(ocf_cache_t cache)
{
function_called();
}
int __wrap_ocf_mng_cache_set_fallback_pt(ocf_cache_t cache)
{
function_called();
}
bool __wrap_ocf_fallback_pt_is_on(ocf_cache_t cache)
{
}
char *__wrap_ocf_cache_get_name(ocf_cache_t cache)
{
}
static void ocf_mngt_cache_set_fallback_pt_error_threshold_test01(void **state)
{
struct ocf_cache cache;
int new_threshold;
int result;
print_test_description("Appropriate error code on invalid threshold value");
new_threshold = -1;
result = ocf_mngt_cache_set_fallback_pt_error_threshold(&cache, new_threshold);
assert_int_equal(result, -OCF_ERR_INVAL);
new_threshold = 10000001;
result = ocf_mngt_cache_set_fallback_pt_error_threshold(&cache, new_threshold);
assert_int_equal(result, -OCF_ERR_INVAL);
}
static void ocf_mngt_cache_set_fallback_pt_error_threshold_test02(void **state)
{
struct ocf_cache cache;
int new_threshold;
int old_threshold;
print_test_description("Invalid new threshold value doesn't change current threshold");
new_threshold = -1;
old_threshold = cache.fallback_pt_error_threshold = 1000;
ocf_mngt_cache_set_fallback_pt_error_threshold(&cache, new_threshold);
assert_int_equal(cache.fallback_pt_error_threshold, old_threshold);
new_threshold = 10000001;
old_threshold = cache.fallback_pt_error_threshold = 1000;
ocf_mngt_cache_set_fallback_pt_error_threshold(&cache, new_threshold);
assert_int_equal(cache.fallback_pt_error_threshold, old_threshold);
}
static void ocf_mngt_cache_set_fallback_pt_error_threshold_test03(void **state)
{
struct ocf_cache cache;
int new_threshold, old_threshold;
print_test_description("Setting new threshold value");
new_threshold = 5000;
old_threshold = cache.fallback_pt_error_threshold = 1000;
ocf_mngt_cache_set_fallback_pt_error_threshold(&cache, new_threshold);
assert_int_equal(cache.fallback_pt_error_threshold, new_threshold);
new_threshold = 1000000;
old_threshold = cache.fallback_pt_error_threshold = 1000;
ocf_mngt_cache_set_fallback_pt_error_threshold(&cache, new_threshold);
assert_int_equal(cache.fallback_pt_error_threshold, new_threshold);
new_threshold = 0;
old_threshold = cache.fallback_pt_error_threshold = 1000;
ocf_mngt_cache_set_fallback_pt_error_threshold(&cache, new_threshold);
assert_int_equal(cache.fallback_pt_error_threshold, new_threshold);
}
static void ocf_mngt_cache_set_fallback_pt_error_threshold_test04(void **state)
{
struct ocf_cache cache;
int new_threshold;
int result;
print_test_description("Return appropriate value on success");
new_threshold = 5000;
result = ocf_mngt_cache_set_fallback_pt_error_threshold(&cache, new_threshold);
assert_int_equal(result, 0);
new_threshold = 1000000;
result = ocf_mngt_cache_set_fallback_pt_error_threshold(&cache, new_threshold);
assert_int_equal(cache.fallback_pt_error_threshold, new_threshold);
new_threshold = 0;
result = ocf_mngt_cache_set_fallback_pt_error_threshold(&cache, new_threshold);
assert_int_equal(result, 0);
}
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(ocf_mngt_cache_set_fallback_pt_error_threshold_test01),
cmocka_unit_test(ocf_mngt_cache_set_fallback_pt_error_threshold_test02),
cmocka_unit_test(ocf_mngt_cache_set_fallback_pt_error_threshold_test03),
cmocka_unit_test(ocf_mngt_cache_set_fallback_pt_error_threshold_test04)
};
print_message("Unit test of src/mngt/ocf_mngt_cache.c");
return cmocka_run_group_tests(tests, NULL, NULL);
}

View File

@@ -0,0 +1,2 @@
add_library(ocf_env ocf_env.c)
target_link_libraries(ocf_env pthread)

View File

@@ -0,0 +1,611 @@
/*
* Copyright(c) 2012-2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause-Clear
*/
#include "ocf_env.h"
#include <sys/types.h>
#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
void bug_on(int cond)
{
/* Wrap this to use your implementation */
assert_false(cond);
}
void *env_malloc(size_t size, int flags)
{
return malloc(size);
}
void *env_zalloc(size_t size, int flags)
{
return calloc(1, size);
}
void env_free(const void *ptr)
{
return free((void *) ptr);
}
void *env_vmalloc(size_t size)
{
return malloc(size);
}
void *env_vzalloc(size_t size)
{
return calloc(1, size);
}
void env_vfree(const void *ptr)
{
return free((void *) ptr);
}
uint64_t env_get_free_memory(void)
{
return sysconf(_SC_PAGESIZE) * sysconf(_SC_AVPHYS_PAGES);
}
/* *** ALLOCATOR *** */
struct _env_allocator {
/*!< Memory pool ID unique name */
char *name;
/*!< Size of specific item of memory pool */
uint32_t item_size;
/*!< Number of currently allocated items in pool */
env_atomic count;
};
size_t env_allocator_align(size_t size)
{
if (size <= 2)
return size;
return (1ULL << 32) >> __builtin_clz(size - 1);
}
struct _env_allocator_item {
uint32_t flags;
uint32_t cpu;
char data[];
};
void *env_allocator_new(env_allocator *allocator)
{
struct _env_allocator_item *item = NULL;
item = calloc(1, allocator->item_size);
if (item) {
item->cpu = 0;
env_atomic_inc(&allocator->count);
}
return &item->data;
}
env_allocator *env_allocator_create(uint32_t size, const char *name)
{
env_allocator *allocator = calloc(1, sizeof(*allocator));
allocator->item_size = size + sizeof(struct _env_allocator_item);
allocator->name = strdup(name);
return allocator;
}
void env_allocator_del(env_allocator *allocator, void *obj)
{
struct _env_allocator_item *item;
item = container_of(obj, struct _env_allocator_item, data);
env_atomic_dec(&allocator->count);
free(item);
}
void env_allocator_destroy(env_allocator *allocator)
{
if (allocator) {
if (env_atomic_read(&allocator->count)) {
fprintf(stderr, "Not all object deallocated\n");
ENV_WARN(true, "Cleanup problem\n");
}
free(allocator->name);
free(allocator);
}
}
uint32_t env_allocator_item_count(env_allocator *allocator)
{
return env_atomic_read(&allocator->count);
}
/* *** COMPLETION *** */
void env_completion_init(env_completion *completion)
{
function_called();
check_expected_ptr(completion);
}
void env_completion_wait(env_completion *completion)
{
function_called();
check_expected_ptr(completion);
}
void env_completion_complete(env_completion *completion)
{
function_called();
check_expected_ptr(completion);
}
int env_mutex_init(env_mutex *mutex)
{
function_called();
check_expected_ptr(mutex);
return mock();
}
void env_mutex_lock(env_mutex *mutex)
{
function_called();
check_expected_ptr(mutex);
}
int env_mutex_lock_interruptible(env_mutex *mutex)
{
function_called();
check_expected_ptr(mutex);
return mock();
}
int env_mutex_trylock(env_mutex *mutex)
{
function_called();
check_expected_ptr(mutex);
return mock();
}
void env_mutex_unlock(env_mutex *mutex)
{
function_called();
check_expected_ptr(mutex);
}
int env_mutex_is_locked(env_mutex *mutex)
{
function_called();
check_expected_ptr(mutex);
return mock();
}
int env_rmutex_init(env_rmutex *rmutex)
{
function_called();
check_expected_ptr(rmutex);
return mock();
}
void env_rmutex_lock(env_rmutex *rmutex)
{
function_called();
check_expected_ptr(rmutex);
}
int env_rmutex_lock_interruptible(env_rmutex *rmutex)
{
function_called();
check_expected_ptr(rmutex);
return mock();
}
int env_rmutex_trylock(env_rmutex *rmutex)
{
function_called();
check_expected_ptr(rmutex);
return mock();
}
void env_rmutex_unlock(env_rmutex *rmutex)
{
function_called();
check_expected_ptr(rmutex);
}
int env_rmutex_is_locked(env_rmutex *rmutex)
{
function_called();
check_expected_ptr(rmutex);
return mock();
}
int env_rwsem_init(env_rwsem *s)
{
function_called();
check_expected_ptr(s);
return mock();
}
void env_rwsem_up_read(env_rwsem *s)
{
function_called();
check_expected_ptr(s);
}
void env_rwsem_down_read(env_rwsem *s)
{
function_called();
check_expected_ptr(s);
}
int env_rwsem_down_read_trylock(env_rwsem *s)
{
function_called();
check_expected_ptr(s);
return mock();
}
void env_rwsem_up_write(env_rwsem *s)
{
function_called();
check_expected_ptr(s);
}
void env_rwsem_down_write(env_rwsem *s)
{
function_called();
check_expected_ptr(s);
}
int env_rwsem_down_write_trylock(env_rwsem *s)
{
function_called();
check_expected_ptr(s);
return mock();
}
int env_atomic_read(const env_atomic *a)
{
return *a;
}
void env_atomic_set(env_atomic *a, int i)
{
*a = i;
}
void env_atomic_add(int i, env_atomic *a)
{
*a += i;
}
void env_atomic_sub(int i, env_atomic *a)
{
*a -= i;
}
bool env_atomic_sub_and_test(int i, env_atomic *a)
{
return *a-=i == 0;
}
void env_atomic_inc(env_atomic *a)
{
++*a;
}
void env_atomic_dec(env_atomic *a)
{
--*a;
}
bool env_atomic_dec_and_test(env_atomic *a)
{
return --*a == 0;
}
bool env_atomic_inc_and_test(env_atomic *a)
{
return ++*a == 0;
}
int env_atomic_add_return(int i, env_atomic *a)
{
return *a+=i;
}
int env_atomic_sub_return(int i, env_atomic *a)
{
return *a-=i;
}
int env_atomic_inc_return(env_atomic *a)
{
return ++*a;
}
int env_atomic_dec_return(env_atomic *a)
{
return --*a;
}
int env_atomic_cmpxchg(env_atomic *a, int old, int new_value)
{
int oldval = *a;
if (oldval == old)
*a = new_value;
return oldval;
}
int env_atomic_add_unless(env_atomic *a, int i, int u)
{
int c, old;
c = *a;
for (;;) {
if (c == (u))
break;
old = env_atomic_cmpxchg((a), c, c + (i));
if (old == c)
break;
c = old;
}
return c != (u);
}
long env_atomic64_read(const env_atomic64 *a)
{
return *a;
}
void env_atomic64_set(env_atomic64 *a, long i)
{
*a=i;
}
void env_atomic64_add(long i, env_atomic64 *a)
{
*a += i;
}
void env_atomic64_sub(long i, env_atomic64 *a)
{
*a -= i;
}
void env_atomic64_inc(env_atomic64 *a)
{
++*a;
}
void env_atomic64_dec(env_atomic64 *a)
{
--*a;
}
long env_atomic64_cmpxchg(env_atomic64 *a, long old, long new)
{
long oldval = *a;
if (oldval == old)
*a = new;
return oldval;
}
void env_spinlock_init(env_spinlock *l)
{
function_called();
check_expected_ptr(l);
}
void env_spinlock_lock(env_spinlock *l)
{
function_called();
check_expected_ptr(l);
}
void env_spinlock_unlock(env_spinlock *l)
{
function_called();
check_expected_ptr(l);
}
void env_spinlock_lock_irq(env_spinlock *l)
{
function_called();
check_expected_ptr(l);
}
void env_spinlock_unlock_irq(env_spinlock *l)
{
function_called();
check_expected_ptr(l);
}
void env_rwlock_init(env_rwlock *l)
{
function_called();
check_expected_ptr(l);
}
void env_rwlock_read_lock(env_rwlock *l)
{
function_called();
check_expected_ptr(l);
}
void env_rwlock_read_unlock(env_rwlock *l)
{
function_called();
check_expected_ptr(l);
}
void env_rwlock_write_lock(env_rwlock *l)
{
function_called();
check_expected_ptr(l);
}
void env_rwlock_write_unlock(env_rwlock *l)
{
function_called();
check_expected_ptr(l);
}
void env_waitqueue_init(env_waitqueue *w)
{
w->completed = false;
w->waiting = false;
w->co = NULL;
}
void env_waitqueue_wake_up(env_waitqueue *w)
{
w->completed = true;
if (!w->waiting || !w->co)
return;
}
void env_bit_set(int nr, volatile void *addr)
{
char *byte = (char *) addr + (nr >> 3);
char mask = 1 << (nr & 7);
__sync_or_and_fetch(byte, mask);
}
void env_bit_clear(int nr, volatile void *addr)
{
char *byte = (char *) addr + (nr >> 3);
char mask = 1 << (nr & 7);
mask = ~mask;
__sync_and_and_fetch(byte, mask);
}
bool env_bit_test(int nr, const volatile unsigned long *addr)
{
const char *byte = (char *) addr + (nr >> 3);
char mask = 1 << (nr & 7);
return !!(*byte & mask);
}
/* *** SCHEDULING *** */
void env_touch_softlockup_wd(void)
{
function_called();
}
void env_schedule(void)
{
function_called();
}
int env_in_interrupt(void)
{
function_called();
return mock();
}
uint64_t env_get_tick_count(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
uint64_t env_ticks_to_msecs(uint64_t j)
{
return j;
}
uint64_t env_ticks_to_secs(uint64_t j)
{
return j / 1000;
}
uint64_t env_secs_to_ticks(uint64_t j)
{
return j * 1000;
}
int env_memset(void *dest, size_t count, int ch)
{
memset(dest, ch, count);
return 0;
}
int env_memcpy(void *dest, size_t destsz, const void * src, size_t count)
{
if (destsz < count)
memcpy(dest, src, destsz);
else
memcpy(dest, src, count);
return 0;
}
int env_memcmp(const void *str1, size_t n1, const void *str2, size_t n2,
int *diff)
{
size_t n = n1 > n2 ? n2 : n1;
*diff = memcmp(str1, str2, n);
return 0;
}
int env_strncpy(char * dest, size_t destsz, const char *src, size_t count)
{
if (destsz < count)
strncpy(dest, src, destsz);
else
strncpy(dest, src, count);
return 0;
}
size_t env_strnlen(const char *str, size_t strsz)
{
return strlen(str);
}
void env_sort(void *base, size_t num, size_t size,
int (*cmp_fn)(const void *, const void *),
void (*swap_fn)(void *, void *, int size))
{
qsort(base, num, size, cmp_fn);
}
int env_strncmp(const char * str1, const char * str2, size_t num)
{
return strncmp(str1, str2, num);
}
void env_msleep(uint64_t n)
{
}
/* *** CRC *** */
uint32_t env_crc32(uint32_t crc, uint8_t const *data, size_t len)
{
function_called();
check_expected(crc);
check_expected(len);
check_expected_ptr(data);
return mock();
}

View File

@@ -0,0 +1,356 @@
/*
* Copyright(c) 2012-2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause-Clear
*/
#ifndef __LIBOCF_ENV_H__
#define __LIBOCF_ENV_H__
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#ifndef __USE_GNU
#define __USE_GNU
#endif
#include <linux/limits.h>
#include <linux/stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <pthread.h>
#include <assert.h>
#include <semaphore.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <sys/time.h>
#include "ocf_env_list.h"
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef uint64_t sector_t;
#define ENV_PRIu64 "lu"
#define __packed __attribute__((packed))
#define __aligned(x) __attribute__((aligned(x)))
/* linux sector 512-bytes */
#define ENV_SECTOR_SHIFT 9
#define PAGE_SIZE 4096
#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
/* *** MEMORY MANAGEMENT *** */
#define ENV_MEM_NORMAL 0
#define ENV_MEM_NOIO 1
#define ENV_MEM_ATOMIC 2
#define ENV_WARN(cond, fmt, args...) ({})
#define ENV_WARN_ON(cond) ({ \
if (unlikely(cond)) \
fprintf(stderr, "WARNING (%s:%d)\n", \
__FILE__, __LINE__); \
})
#define ENV_BUG() ({ \
fprintf(stderr, "BUG (%s:%d)\n", \
__FILE__, __LINE__); \
assert(0); \
abort(); \
})
#define ENV_BUG_ON(cond) bug_on((int)cond);
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type, member) );})
/* ATOMICS */
#ifndef atomic_read
#define atomic_read(ptr) (*(__typeof__(*ptr) *volatile) (ptr))
#endif
#ifndef atomic_set
#define atomic_set(ptr, i) ((*(__typeof__(*ptr) *volatile) (ptr)) = (i))
#endif
#define likely(x) (x)
#define unlikely(x) (x)
/*
* Bug on for testing
*/
void bug_on(int cond);
void *env_malloc(size_t size, int flags);
void *env_zalloc(size_t size, int flags);
void env_free(const void *ptr);
void *env_vmalloc(size_t size);
void *env_vzalloc(size_t size);
void env_vfree(const void *ptr);
uint64_t env_get_free_memory(void);
/* *** ALLOCATOR *** */
typedef struct _env_allocator env_allocator;
env_allocator *env_allocator_create(uint32_t size, const char *name);
void env_allocator_destroy(env_allocator *allocator);
void *env_allocator_new(env_allocator *allocator);
void env_allocator_del(env_allocator *allocator, void *item);
uint32_t env_allocator_item_count(env_allocator *allocator);
/* *** MUTEX *** */
typedef struct {
pthread_mutex_t m;
} env_mutex;
int env_mutex_init(env_mutex *mutex);
void env_mutex_lock(env_mutex *mutex);
int env_mutex_lock_interruptible(env_mutex *mutex);
int env_mutex_trylock(env_mutex *mutex);
void env_mutex_unlock(env_mutex *mutex);
int env_mutex_is_locked(env_mutex *mutex);
/* *** RECURSIVE MUTEX *** */
typedef env_mutex env_rmutex;
int env_rmutex_init(env_rmutex *rmutex);
void env_rmutex_lock(env_rmutex *rmutex);
int env_rmutex_lock_interruptible(env_rmutex *rmutex);
int env_rmutex_trylock(env_rmutex *rmutex);
void env_rmutex_unlock(env_rmutex *rmutex);
int env_rmutex_is_locked(env_rmutex *rmutex);
/* *** RW SEMAPHORE *** */
typedef struct {
pthread_rwlock_t lock;
} env_rwsem;
int env_rwsem_init(env_rwsem *s);
void env_rwsem_up_read(env_rwsem *s);
void env_rwsem_down_read(env_rwsem *s);
int env_rwsem_down_read_trylock(env_rwsem *s);
void env_rwsem_up_write(env_rwsem *s);
void env_rwsem_down_write(env_rwsem *s);
int env_rwsem_down_write_trylock(env_rwsem *s);
int env_rwsem_is_locked(env_rwsem *s);
/* *** ATOMIC VARIABLES *** */
typedef int env_atomic;
typedef long env_atomic64;
int env_atomic_read(const env_atomic *a);
void env_atomic_set(env_atomic *a, int i);
void env_atomic_add(int i, env_atomic *a);
void env_atomic_sub(int i, env_atomic *a);
bool env_atomic_sub_and_test(int i, env_atomic *a);
void env_atomic_inc(env_atomic *a);
void env_atomic_dec(env_atomic *a);
bool env_atomic_dec_and_test(env_atomic *a);
bool env_atomic_inc_and_test(env_atomic *a);
int env_atomic_add_return(int i, env_atomic *a);
int env_atomic_sub_return(int i, env_atomic *a);
int env_atomic_inc_return(env_atomic *a);
int env_atomic_dec_return(env_atomic *a);
int env_atomic_cmpxchg(env_atomic *a, int old, int new_value);
int env_atomic_add_unless(env_atomic *a, int i, int u);
long env_atomic64_read(const env_atomic64 *a);
void env_atomic64_set(env_atomic64 *a, long i);
void env_atomic64_add(long i, env_atomic64 *a);
void env_atomic64_sub(long i, env_atomic64 *a);
void env_atomic64_inc(env_atomic64 *a);
void env_atomic64_dec(env_atomic64 *a);
long env_atomic64_cmpxchg(env_atomic64 *a, long old, long new);
typedef int Coroutine;
/* *** COMPLETION *** */
struct completion {
bool completed;
bool waiting;
Coroutine *co;
};
typedef struct completion env_completion;
void env_completion_init(env_completion *completion);
void env_completion_wait(env_completion *completion);
void env_completion_complete(env_completion *completion);
/* *** SPIN LOCKS *** */
typedef struct {
} env_spinlock;
void env_spinlock_init(env_spinlock *l);
void env_spinlock_lock(env_spinlock *l);
void env_spinlock_unlock(env_spinlock *l);
void env_spinlock_lock_irq(env_spinlock *l);
void env_spinlock_unlock_irq(env_spinlock *l);
#define env_spinlock_lock_irqsave(l, flags) \
env_spinlock_lock(l); (void)flags;
#define env_spinlock_unlock_irqrestore(l, flags) \
env_spinlock_unlock(l); (void)flags;
/* *** RW LOCKS *** */
typedef struct {
} env_rwlock;
void env_rwlock_init(env_rwlock *l);
void env_rwlock_read_lock(env_rwlock *l);
void env_rwlock_read_unlock(env_rwlock *l);
void env_rwlock_write_lock(env_rwlock *l);
void env_rwlock_write_unlock(env_rwlock *l);
/* *** WAITQUEUE *** */
typedef struct {
bool waiting;
bool completed;
Coroutine *co;
} env_waitqueue;
void env_waitqueue_init(env_waitqueue *w);
void env_waitqueue_wake_up(env_waitqueue *w);
#define env_waitqueue_wait(w, condition) \
({ \
int __ret = 0; \
if (!(condition) && !w.completed) { \
w.waiting = true; \
} \
w.co = NULL; \
w.waiting = false; \
w.completed = false; \
__ret = __ret; \
})
/* *** BIT OPERATIONS *** */
void env_bit_set(int nr, volatile void *addr);
void env_bit_clear(int nr, volatile void *addr);
bool env_bit_test(int nr, const volatile unsigned long *addr);
/* *** SCHEDULING *** */
void env_touch_softlockup_wd(void);
void env_schedule(void);
int env_in_interrupt(void);
uint64_t env_get_tick_count(void);
uint64_t env_ticks_to_msecs(uint64_t j);
uint64_t env_ticks_to_secs(uint64_t j);
uint64_t env_secs_to_ticks(uint64_t j);
/* *** STRING OPERATIONS *** */
int env_memset(void *dest, size_t count, int ch);
int env_memcpy(void *dest, size_t destsz, const void * src, size_t count);
int env_memcmp(const void *str1, size_t n1, const void *str2, size_t n2,
int *diff);
int env_strncpy(char * dest, size_t destsz, const char *src, size_t srcsz);
size_t env_strnlen(const char *str, size_t strsz);
int env_strncmp(const char * str1, const char * str2, size_t num);
/* *** SORTING *** */
void env_sort(void *base, size_t num, size_t size,
int (*cmp_fn)(const void *, const void *),
void (*swap_fn)(void *, void *, int size));
void env_msleep(uint64_t n);
/* *** CRC *** */
uint32_t env_crc32(uint32_t crc, uint8_t const *data, size_t len);
#endif /* __OCF_ENV_H__ */

View File

@@ -0,0 +1,13 @@
/*
* Copyright(c) 2012-2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause-Clear
*/
#ifndef __OCF_ENV_HEADERS_H__
#define __OCF_ENV_HEADERS_H__
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#endif /* __OCF_ENV_HEADERS_H__ */

View File

@@ -0,0 +1,146 @@
/*
* Copyright(c) 2012-2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause-Clear
*/
#ifndef __OCF_LIST_H__
#define __OCF_LIST_H__
#define LIST_POISON1 ((void *)0x101)
#define LIST_POISON2 ((void *)0x202)
/**
* List entry structure mimicking linux kernel based one.
*/
struct list_head {
struct list_head *next;
struct list_head *prev;
};
/**
* start an empty list
*/
#define INIT_LIST_HEAD(l) { (l)->prev = l; (l)->next = l; }
/**
* Add item to list head.
* @param it list entry to be added
* @param l1 list main node (head)
*/
static inline void list_add(struct list_head *it, struct list_head *l1)
{
it->prev = l1;
it->next = l1->next;
l1->next->prev = it;
l1->next = it;
}
/**
* Add item it to tail.
* @param it list entry to be added
* @param l1 list main node (head)
*/
static inline void list_add_tail(struct list_head *it, struct list_head *l1)
{
it->prev = l1->prev;
it->next = l1;
l1->prev->next = it;
l1->prev = it;
}
/**
* check if a list is empty (return true)
* @param l1 list main node (head)
*/
static inline int list_empty(struct list_head *l1)
{
return l1->next == l1;
}
/**
* delete an entry from a list
* @param it list entry to be deleted
*/
static inline void list_del(struct list_head *it)
{
it->next->prev = it->prev;
it->prev->next = it->next;
}
/**
* Extract an entry.
* @param list_head_i list head item, from which entry is extracted
* @param item_type type (struct) of list entry
* @param field_name name of list_head field within item_type
*/
#define list_entry(list_head_i, item_type, field_name) \
(item_type *)(((void*)(list_head_i)) - offsetof(item_type, field_name))
#define list_first_entry(list_head_i, item_type, field_name) \
list_entry((list_head_i)->next, item_type, field_name)
/**
* @param iterator uninitialized list_head pointer, to be used as iterator
* @param plist list head (main node)
*/
#define list_for_each(iterator, plist) \
for (iterator = (plist)->next; \
(iterator)->next != (plist)->next; \
iterator = (iterator)->next)
/**
* Safe version of list_for_each which works even if entries are deleted during
* loop.
* @param iterator uninitialized list_head pointer, to be used as iterator
* @param q another uninitialized list_head, used as helper
* @param plist list head (main node)
*/
/*
* Algorithm handles situation, where q is deleted.
* consider in example 3 element list with header h:
*
* h -> 1 -> 2 -> 3 ->
*1. i q
*
*2. i q
*
*3. q i
*/
#define list_for_each_safe(iterator, q, plist) \
for (iterator = (q = (plist)->next->next)->prev; \
(q) != (plist)->next; \
iterator = (q = (q)->next)->prev)
#define _list_entry_helper(item, head, field_name) \
list_entry(head, typeof(*item), field_name)
/**
* Iterate over list entries.
* @param list pointer to list item (iterator)
* @param plist pointer to list_head item
* @param field_name name of list_head field in list entry
*/
#define list_for_each_entry(item, plist, field_name) \
for (item = _list_entry_helper(item, (plist)->next, field_name); \
_list_entry_helper(item, (item)->field_name.next, field_name) !=\
_list_entry_helper(item, (plist)->next, field_name); \
item = _list_entry_helper(item, (item)->field_name.next, field_name))
/**
* Safe version of list_for_each_entry which works even if entries are deleted
* during loop.
* @param list pointer to list item (iterator)
* @param q another pointer to list item, used as helper
* @param plist pointer to list_head item
* @param field_name name of list_head field in list entry
*/
#define list_for_each_entry_safe(item, q, plist, field_name) \
for (item = _list_entry_helper(item, (plist)->next, field_name), \
q = _list_entry_helper(item, (item)->field_name.next, field_name); \
_list_entry_helper(item, (item)->field_name.next, field_name) != \
_list_entry_helper(item, (plist)->next, field_name); \
item = q, q = _list_entry_helper(q, (q)->field_name.next, field_name))
#endif

View File

@@ -0,0 +1,6 @@
/*
* Copyright(c) 2012-2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause-Clear
*/
#define print_test_description(description) print_message("[ DESC ] %s\n", description);