repo_name
stringclasses 10
values | file_path
stringlengths 29
222
| content
stringlengths 24
926k
| extention
stringclasses 5
values |
---|---|---|---|
fprime | data/projects/fprime/Os/Stub/File.hpp | // ======================================================================
// \title Os/Stub/File.hpp
// \brief stub file definitions for Os::File
// ======================================================================
#include "Os/File.hpp"
#ifndef OS_STUB_FILE_HPP
#define OS_STUB_FILE_HPP
namespace Os {
namespace Stub {
namespace File {
struct StubFileHandle : public FileHandle {};
//! \brief stub implementation of Os::File
//!
//! Stub implementation of `FileInterface` for use as a delegate class handling error-only file operations.
//!
class StubFile : public FileInterface {
public:
//! \brief constructor
//!
StubFile() = default;
//! \brief destructor
//!
~StubFile() override = default;
// ------------------------------------
// Functions overrides
// ------------------------------------
//! \brief open file with supplied path and mode
//!
//! This implementation does nothing but return NOT_IMPLEMENTED.
//!
//! It is invalid to send `nullptr` as the path.
//! It is invalid to supply `mode` as a non-enumerated value.
//! It is invalid to supply `overwrite` as a non-enumerated value.
//!
//! \param path: c-string of path to open
//! \param mode: file operation mode
//! \param overwrite: overwrite existing file on create
//! \return: NOT_IMPLEMENTED
//!
Os::FileInterface::Status open(const char *path, Mode mode, OverwriteType overwrite) override;
//! \brief close the file, if not opened then do nothing
//!
//! This implementation does nothing.
//!
void close() override;
//! \brief get size of currently open file
//!
//! This implementation does nothing but return NOT_IMPLEMENTED.
//! \param size: output parameter for size.
//! \return NOT_IMPLEMENTED
//!
Status size(FwSignedSizeType &size_result) override;
//! \brief get file pointer position of the currently open file
//!
//! This implementation does nothing but return NOT_IMPLEMENTED.
//! \param position: output parameter for size.
//! \return NOT_IMPLEMENTED
//!
Status position(FwSignedSizeType &position_result) override;
//! \brief pre-allocate file storage
//!
//! This implementation does nothing but return NOT_IMPLEMENTED.
//!
//! It is invalid to pass a negative `offset`.
//! It is invalid to pass a negative `length`.
//!
//! \param offset: offset into file
//! \param length: length after offset to preallocate
//! \return NOT_IMPLEMENTED
//!
Status preallocate(FwSignedSizeType offset, FwSignedSizeType length) override;
//! \brief seek the file pointer to the given offset
//!
//! This implementation does nothing but return NOT_IMPLEMENTED.
//!
//! \param offset: offset to seek to
//! \param seekType: `ABSOLUTE` for seeking from beginning of file, `CURRENT` to use current position.
//! \return NOT_IMPLEMENTED
//!
Status seek(FwSignedSizeType offset, SeekType seekType) override;
//! \brief flush file contents to storage
//!
//! This implementation does nothing but return NOT_IMPLEMENTED.
//!
//! \return NOT_IMPLEMENTED
//!
Status flush() override;
//! \brief read data from this file into supplied buffer bounded by size
//!
//! This implementation does nothing but return NOT_IMPLEMENTED.
//!
//! It is invalid to pass `nullptr` to this function call.
//! It is invalid to pass a negative `size`.
//! It is invalid to supply wait as a non-enumerated value.
//!
//! \param buffer: memory location to store data read from file
//! \param size: size of data to read
//! \param wait: `WAIT` to wait for data, `NO_WAIT` to return what is currently available
//! \return NOT_IMPLEMENTED
//!
Status read(U8 *buffer, FwSignedSizeType &size, WaitType wait) override;
//! \brief read data from this file into supplied buffer bounded by size
//!
//! This implementation does nothing but return NOT_IMPLEMENTED.
//!
//! It is invalid to pass `nullptr` to this function call.
//! It is invalid to pass a negative `size`.
//! It is invalid to supply wait as a non-enumerated value.
//!
//! \param buffer: memory location to store data read from file
//! \param size: size of data to read
//! \param wait: `WAIT` to wait for data to write to disk, `NO_WAIT` to return what is currently available
//! \return NOT_IMPLEMENTED
//!
Status write(const U8 *buffer, FwSignedSizeType &size, WaitType wait) override;
//! \brief returns the raw file handle
//!
//! Gets the raw file handle from the implementation. Note: users must include the implementation specific
//! header to make any real use of this handle. Otherwise it//!must* be passed as an opaque type.
//!
//! \return raw file handle
//!
FileHandle *getHandle() override;
private:
//! File handle for PosixFile
StubFileHandle m_handle;
};
} // namespace File
} // namespace Stub
} // namespace Os
#endif // OS_STUB_FILE_HPP
| hpp |
fprime | data/projects/fprime/Os/Stub/DefaultFile.cpp | // ======================================================================
// \title Os/Stub/DefaultFile.cpp
// \brief sets default Os::File to no-op stub implementation via linker
// ======================================================================
#include "Os/Stub/File.hpp"
#include "Fw/Types/Assert.hpp"
#include <new>
namespace Os {
//! \brief get implementation file interface for use as delegate
//!
//! Added via linker to ensure that the no-op stub implementation of Os::File is the default.
//!
//! \param aligned_placement_new_memory: memory to placement-new into
//! \return FileInterface pointer result of placement new
//!
FileInterface *FileInterface::getDelegate(U8 *aligned_placement_new_memory, const FileInterface* to_copy) {
FW_ASSERT(aligned_placement_new_memory != nullptr);
const Os::Stub::File::StubFile* copy_me = reinterpret_cast<const Os::Stub::File::StubFile*>(to_copy);
// Placement-new the file handle into the opaque file-handle storage
static_assert(sizeof(Os::Stub::File::StubFile) <= sizeof Os::File::m_handle_storage, "Handle size not large enough");
static_assert((FW_HANDLE_ALIGNMENT % alignof(Os::Stub::File::StubFile)) == 0, "Handle alignment invalid");
Os::Stub::File::StubFile *interface = nullptr;
if (to_copy == nullptr) {
interface = new(aligned_placement_new_memory) Os::Stub::File::StubFile;
} else {
interface = new(aligned_placement_new_memory) Os::Stub::File::StubFile(*copy_me);
}
FW_ASSERT(interface != nullptr);
return interface;
}
}
| cpp |
fprime | data/projects/fprime/Os/Stub/test/File.cpp | #include "Os/Stub/test/File.hpp"
#include "Os/File.hpp"
#include <new>
namespace Os {
namespace Stub {
namespace File {
namespace Test {
StaticData StaticData::data;
void StaticData::setNextStatus(Os::File::Status status) {
StaticData::data.nextStatus = status;
}
void StaticData::setSizeResult(FwSignedSizeType size) {
StaticData::data.sizeResult = size;
}
void StaticData::setPositionResult(FwSignedSizeType position) {
StaticData::data.positionResult = position;
}
void StaticData::setReadResult(U8 *buffer, FwSignedSizeType size) {
StaticData::data.readResult = buffer;
StaticData::data.readResultSize = size;
}
void StaticData::setReadSize(FwSignedSizeType size) {
StaticData::data.readSizeResult = size;
}
void StaticData::setWriteResult(U8 *buffer, FwSignedSizeType size) {
StaticData::data.writeResult = buffer;
StaticData::data.writeResultSize = size;
}
void StaticData::setWriteSize(FwSignedSizeType size) {
StaticData::data.writeSizeResult = size;
}
TestFile::TestFile() {
StaticData::data.lastCalled = StaticData::CONSTRUCT_FN;
}
TestFile::~TestFile() {
StaticData::data.lastCalled = StaticData::DESTRUCT_FN;
}
FileInterface::Status TestFile::open(const char *filepath, Mode open_mode, OverwriteType overwrite) {
StaticData::data.openPath = filepath;
StaticData::data.openMode = open_mode;
StaticData::data.openOverwrite = overwrite;
StaticData::data.lastCalled = StaticData::OPEN_FN;
StaticData::data.pointer = 0;
return StaticData::data.nextStatus;
}
void TestFile::close() {
StaticData::data.lastCalled = StaticData::CLOSE_FN;
}
FileInterface::Status TestFile::size(FwSignedSizeType& size_result) {
StaticData::data.lastCalled = StaticData::SIZE_FN;
size_result = StaticData::data.sizeResult;
return StaticData::data.nextStatus;
}
FileInterface::Status TestFile::position(FwSignedSizeType& position_result) {
StaticData::data.lastCalled = StaticData::POSITION_FN;
position_result = StaticData::data.positionResult;
return StaticData::data.nextStatus;
}
FileInterface::Status TestFile::preallocate(FwSignedSizeType offset, FwSignedSizeType length) {
StaticData::data.preallocateOffset = offset;
StaticData::data.preallocateLength = length;
StaticData::data.lastCalled = StaticData::PREALLOCATE_FN;
return StaticData::data.nextStatus;
}
FileInterface::Status TestFile::seek(FwSignedSizeType offset, SeekType seekType) {
StaticData::data.seekOffset = offset;
StaticData::data.seekType = seekType;
StaticData::data.lastCalled = StaticData::SEEK_FN;
return StaticData::data.nextStatus;
}
FileInterface::Status TestFile::flush() {
StaticData::data.lastCalled = StaticData::FLUSH_FN;
return StaticData::data.nextStatus;
}
FileInterface::Status TestFile::read(U8 *buffer, FwSignedSizeType &size, WaitType wait) {
StaticData::data.readBuffer = buffer;
StaticData::data.readSize = size;
StaticData::data.readWait = wait;
StaticData::data.lastCalled = StaticData::READ_FN;
// Copy read data if set
if (nullptr != StaticData::data.readResult) {
size = FW_MIN(size, StaticData::data.readResultSize - StaticData::data.pointer);
(void) ::memcpy(buffer, StaticData::data.readResult + StaticData::data.pointer, size);
StaticData::data.pointer += size;
} else {
size = StaticData::data.readSizeResult;
}
return StaticData::data.nextStatus;
}
FileInterface::Status TestFile::write(const U8* buffer, FwSignedSizeType &size, WaitType wait) {
StaticData::data.writeBuffer = buffer;
StaticData::data.writeSize = size;
StaticData::data.writeWait = wait;
StaticData::data.lastCalled = StaticData::WRITE_FN;
// Copy read data if set
if (nullptr != StaticData::data.writeResult) {
size = FW_MIN(size, StaticData::data.writeResultSize - StaticData::data.pointer);
(void) ::memcpy(StaticData::data.writeResult + StaticData::data.pointer, buffer, size);
StaticData::data.pointer += size;
} else {
size = StaticData::data.writeSizeResult;
}
return StaticData::data.nextStatus;
}
FileHandle* TestFile::getHandle() {
return &this->m_handle;
}
} // namespace Test
} // namespace File
} // namespace Stub
} // namespace Os
| cpp |
fprime | data/projects/fprime/Os/Stub/test/File.hpp | #include "Os/File.hpp"
#include <string.h>
#ifndef OS_STUB_FILE_TEST_HPP
#define OS_STUB_FILE_TEST_HPP
namespace Os {
namespace Stub {
namespace File {
namespace Test {
//! Data that supports the stubbed File implementation.
//!/
struct StaticData {
//! Enumeration of last function called
//!
enum LastFn {
NONE_FN,
CONSTRUCT_FN,
DESTRUCT_FN,
OPEN_FN,
CLOSE_FN,
SIZE_FN,
POSITION_FN,
PREALLOCATE_FN,
SEEK_FN,
FLUSH_FN,
READ_FN,
WRITE_FN
};
//! Last function called
LastFn lastCalled = NONE_FN;
//! Path of last open call
const char *openPath = nullptr;
//! Mode of last open call
Os::File::Mode openMode = Os::File::MAX_OPEN_MODE;
//! Overwrite of last open call
Os::File::OverwriteType openOverwrite = Os::File::OverwriteType::NO_OVERWRITE;
//! Offset of last preallocate call
FwSignedSizeType preallocateOffset = -1;
//! Length of last preallocate call
FwSignedSizeType preallocateLength = -1;
//! Offset of last seek call
FwSignedSizeType seekOffset = -1;
//! Absolute of last seek call
Os::File::SeekType seekType = Os::File::SeekType::ABSOLUTE;
//! Buffer of last read call
U8 *readBuffer = nullptr;
//! Size of last read call
FwSignedSizeType readSize = -1;
//! Wait of last read call
Os::File::WaitType readWait = Os::File::WaitType::NO_WAIT;
//! Buffer of last write call
const void *writeBuffer = nullptr;
//! Size of last write call
FwSignedSizeType writeSize = -1;
//! Wait of last write call
Os::File::WaitType writeWait = Os::File::WaitType::NO_WAIT;
//! File pointer
FwSignedSizeType pointer = 0;
//! Next status to be returned
Os::File::Status nextStatus = Os::File::Status::OTHER_ERROR;
//! Return of next size call
FwSignedSizeType sizeResult = -1;
//! Return of next position call
FwSignedSizeType positionResult = 0;
//! Result of next read call
U8 *readResult = nullptr;
//! Size result of next read data
FwSignedSizeType readResultSize = -1;
//! Size result of next read call
FwSignedSizeType readSizeResult = -1;
//! Result holding buffer of next write call
U8 *writeResult = nullptr;
//! Size result of next write data
FwSignedSizeType writeResultSize = -1;
//! Size result of next read call
FwSignedSizeType writeSizeResult = -1;
// Singleton data
static StaticData data;
//! Set next status to return
static void setNextStatus(Os::File::Status status);
//! Set next size to result
static void setSizeResult(FwSignedSizeType size);
//! Set next position to result
static void setPositionResult(FwSignedSizeType position);
//! Set next read result
static void setReadResult(U8 *buffer, FwSignedSizeType size);
//! Set next read size result
static void setReadSize(FwSignedSizeType size);
//! Set next write result
static void setWriteResult(U8 *buffer, FwSignedSizeType size);
//! Set next write size result
static void setWriteSize(FwSignedSizeType size);
};
class TestFileHandle : public FileHandle {};
//! \brief tracking implementation of Os::File
//!
//! Tracking implementation of `FileInterface` for use as a delegate class handling test file operations. Posix files use
//! standard `open`, `read`, and `write` posix calls. The handle is represented as a `PosixFileHandle` which wraps a
//! single `int` type file descriptor used in those API calls.
//!
class TestFile : public FileInterface {
public:
//! \brief constructor
//!
TestFile();
//! \brief destructor
//!
~TestFile() override;
// ------------------------------------
// Functions overrides
// ------------------------------------
//! \brief open file with supplied path and mode
//!
//! Open the file passed in with the given mode. If overwrite is set to OVERWRITE, then opening files in
//! OPEN_CREATE mode will clobber existing files. Set overwrite to NO_OVERWRITE to preserve existing files.
//! The status of the open request is returned from the function call. Delegates to the chosen
//! implementation's `open` function.
//!
//! It is invalid to send `nullptr` as the path.
//! It is invalid to supply `mode` as a non-enumerated value.
//! It is invalid to supply `overwrite` as a non-enumerated value.
//!
//! \param path: c-string of path to open
//! \param mode: file operation mode
//! \param overwrite: overwrite existing file on create
//! \return: status of the open
//!
Os::FileInterface::Status open(const char *path, Mode mode, OverwriteType overwrite) override;
//! \brief close the file, if not opened then do nothing
//!
//! Closes the file, if open. Otherwise this function does nothing. Delegates to the chosen implementation's
//! `closeInternal` function. `mode` is set to `OPEN_NO_MODE`.
//!
void close() override;
//! \brief get size of currently open file
//!
//! Get the size of the currently open file and fill the size parameter. Return status of the operation.
//! \param size: output parameter for size.
//! \return OP_OK on success otherwise error status
//!
Status size(FwSignedSizeType &size_result) override;
//! \brief get file pointer position of the currently open file
//!
//! Get the current position of the read/write pointer of the open file.
//! \param position: output parameter for size.
//! \return OP_OK on success otherwise error status
//!
Status position(FwSignedSizeType &position_result) override;
//! \brief pre-allocate file storage
//!
//! Pre-allocates file storage with at least `length` storage starting at `offset`. No-op on implementations
//! that cannot pre-allocate.
//!
//! It is invalid to pass a negative `offset`.
//! It is invalid to pass a negative `length`.
//!
//! \param offset: offset into file
//! \param length: length after offset to preallocate
//! \return OP_OK on success otherwise error status
//!
Status preallocate(FwSignedSizeType offset, FwSignedSizeType length) override;
//! \brief seek the file pointer to the given offset
//!
//! Seek the file pointer to the given `offset`. If `seekType` is set to `ABSOLUTE` then the offset is calculated
//! from the start of the file, and if it is set to `CURRENT` it is calculated from the current position.
//!
//! \param offset: offset to seek to
//! \param seekType: `ABSOLUTE` for seeking from beginning of file, `CURRENT` to use current position.
//! \return OP_OK on success otherwise error status
//!
Status seek(FwSignedSizeType offset, SeekType seekType) override;
//! \brief flush file contents to storage
//!
//! Flushes the file contents to storage (i.e. out of the OS cache to disk). Does nothing in implementations
//! that do not support flushing.
//!
//! \return OP_OK on success otherwise error status
//!
Status flush() override;
//! \brief read data from this file into supplied buffer bounded by size
//!
//! Read data from this file up to the `size` and store it in `buffer`. When `wait` is set to `WAIT`, this
//! will block until the requested size has been read successfully read or the end of the file has been
//! reached. When `wait` is set to `NO_WAIT` it will return whatever data is currently available.
//!
//! `size` will be updated to the count of bytes actually read. Status will reflect the success/failure of
//! the read operation.
//!
//! It is invalid to pass `nullptr` to this function call.
//! It is invalid to pass a negative `size`.
//! It is invalid to supply wait as a non-enumerated value.
//!
//! \param buffer: memory location to store data read from file
//! \param size: size of data to read
//! \param wait: `WAIT` to wait for data, `NO_WAIT` to return what is currently available
//! \return OP_OK on success otherwise error status
//!
Status read(U8 *buffer, FwSignedSizeType &size, WaitType wait) override;
//! \brief read data from this file into supplied buffer bounded by size
//!
//! Write data to this file up to the `size` from the `buffer`. When `wait` is set to `WAIT`, this
//! will block until the requested size has been written successfully to disk. When `wait` is set to
//! `NO_WAIT` it will return once the data is sent to the OS.
//!
//! `size` will be updated to the count of bytes actually written. Status will reflect the success/failure of
//! the read operation.
//!
//! It is invalid to pass `nullptr` to this function call.
//! It is invalid to pass a negative `size`.
//! It is invalid to supply wait as a non-enumerated value.
//!
//! \param buffer: memory location to store data read from file
//! \param size: size of data to read
//! \param wait: `WAIT` to wait for data to write to disk, `NO_WAIT` to return what is currently available
//! \return OP_OK on success otherwise error status
//!
Status write(const U8 *buffer, FwSignedSizeType &size, WaitType wait) override;
//! \brief returns the raw file handle
//!
//! Gets the raw file handle from the implementation. Note: users must include the implementation specific
//! header to make any real use of this handle. Otherwise it//!must* be passed as an opaque type.
//!
//! \return raw file handle
//!
FileHandle *getHandle() override;
private:
//! File handle for PosixFile
TestFileHandle m_handle;
};
} // namespace Test
} // namespace File
} // namespace Stub
} // namespace Os
#endif // OS_STUB_FILE_TEST_HPP
| hpp |
fprime | data/projects/fprime/Os/Stub/test/DefaultFile.cpp | // ======================================================================
// \title Os/Stub/test/DefaultFile.cpp
// \brief sets default Os::File to test stub implementation via linker
// ======================================================================
#include "Os/Stub/test/File.hpp"
#include "Fw/Types/Assert.hpp"
#include <new>
namespace Os {
//! \brief get implementation file interface for use as delegate
//!
//! Added via linker to ensure that the tracking test stub implementation of Os::File is the default.
//!
//! \param aligned_placement_new_memory: memory to placement-new into
//! \return FileInterface pointer result of placement new
//!
FileInterface *FileInterface::getDelegate(U8 *aligned_placement_new_memory, const FileInterface* to_copy) {
FW_ASSERT(aligned_placement_new_memory != nullptr);
const Os::Stub::File::Test::TestFile* copy_me = reinterpret_cast<const Os::Stub::File::Test::TestFile*>(to_copy);
// Placement-new the file handle into the opaque file-handle storage
static_assert(sizeof(Os::Stub::File::Test::TestFile) <= sizeof Os::File::m_handle_storage,
"Handle size not large enough");
static_assert((FW_HANDLE_ALIGNMENT % alignof(Os::Stub::File::Test::TestFile)) == 0, "Handle alignment invalid");
Os::Stub::File::Test::TestFile *interface = nullptr;
if (to_copy == nullptr) {
interface = new(aligned_placement_new_memory) Os::Stub::File::Test::TestFile;
} else {
interface = new(aligned_placement_new_memory) Os::Stub::File::Test::TestFile(*copy_me);
}
FW_ASSERT(interface != nullptr);
return interface;
}
}
| cpp |
fprime | data/projects/fprime/Os/Stub/test/ut/StubFileTests.cpp | // ======================================================================
// \title Os/Stub/test/ut/StubFileTests.cpp
// \brief tests using stub implementation for Os::File interface testing
// ======================================================================
#include <gtest/gtest.h>
#include "Os/File.hpp"
#include "Os/Models/Models.hpp"
#include "Os/test/ut/file/CommonTests.hpp"
#include "Os/test/ut/file/RulesHeaders.hpp"
#include "Os/Stub/test/File.hpp"
namespace Os {
namespace Test {
namespace File {
//! Set up for the test ensures that the test can run at all
//!
void setUp(bool requires_io) {
if (requires_io) {
GTEST_SKIP() << "Cannot run tests requiring functional i/o";
}
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OP_OK);
Os::Stub::File::Test::StaticData::setPositionResult(0);
}
std::vector<std::shared_ptr<const std::string> > FILES;
//! Tear down for the tests cleans up the test file used
//!
void tearDown() {}
class StubsTester : public Tester {
//! Check if the test file exists.
//! \return true if it exists, false otherwise.
//!
bool exists(const std::string &filename) const override {
for (size_t i = 0; i < FILES.size(); i++) {
if (filename == *FILES.at(i)) {
return true;
}
}
return false;
}
//! Get a filename, randomly if random is true, otherwise use a basic filename.
//! \param random: true if filename should be random, false if predictable
//! \return: filename to use for testing
//!
std::shared_ptr<const std::string> get_filename(bool random) const override {
std::shared_ptr<const std::string> filename = std::shared_ptr<const std::string>(new std::string("DOES-NOT-MATTER"), std::default_delete<std::string>());
FILES.push_back(filename);
return filename;
}
//! Posix tester is fully functional
//! \return true
//!
bool functional() const override {
return false;
}
};
std::unique_ptr<Os::Test::File::Tester> get_tester_implementation() {
return std::unique_ptr<Os::Test::File::Tester>(new Os::Test::File::StubsTester());
}
} // namespace File
} // namespace Test
} // namespace Os
// Ensure that Os::File properly routes constructor calls to the `constructInternal` function.
TEST_F(Interface, Construction) {
Os::File file;
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.lastCalled, Os::Stub::File::Test::StaticData::CONSTRUCT_FN);
}
// Ensure that Os::File properly routes destructor calls to the `destructInternal` function.
TEST_F(Interface, Destruction) {
delete (new Os::File);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.lastCalled, Os::Stub::File::Test::StaticData::DESTRUCT_FN);
}
// Ensure that Os::File properly routes open calls to the `openInternal` function.
TEST_F(Interface, Open) {
const char* path = "/does/not/matter";
Os::File file;
ASSERT_EQ(file.open(path, Os::File::OPEN_CREATE, Os::File::OverwriteType::OVERWRITE), Os::File::Status::OP_OK);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.lastCalled, Os::Stub::File::Test::StaticData::OPEN_FN);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.openPath, path);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.openMode, Os::File::OPEN_CREATE);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.openOverwrite, Os::File::OverwriteType::OVERWRITE);
}
// Ensure that Os::File properly routes close calls to the `closeInternal` function.
TEST_F(Interface, Close) {
Os::File file;
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OP_OK);
ASSERT_EQ(file.open("/does/not/matter", Os::File::OPEN_CREATE, Os::File::OverwriteType::OVERWRITE), Os::File::OP_OK);
file.close();
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.lastCalled, Os::Stub::File::Test::StaticData::CLOSE_FN);
}
// Ensure that Os::File properly routes close calls to the `sizeInternal` function.
TEST_F(Interface, Size) {
FwSignedSizeType sizeResult = -1;
Os::File file;
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OP_OK);
ASSERT_EQ(file.open("/does/not/matter", Os::File::OPEN_CREATE, Os::File::OverwriteType::OVERWRITE), Os::File::OP_OK);
Os::Stub::File::Test::StaticData::setSizeResult(30);
ASSERT_EQ(file.size(sizeResult), Os::File::OP_OK);
ASSERT_EQ(sizeResult, 30);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.lastCalled, Os::Stub::File::Test::StaticData::SIZE_FN);
}
// Ensure that Os::File properly routes close calls to the `positionInternal` function.
TEST_F(Interface, Position) {
FwSignedSizeType positionResult = -1;
Os::File file;
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OP_OK);
ASSERT_EQ(file.open("/does/not/matter", Os::File::OPEN_CREATE, Os::File::OverwriteType::OVERWRITE), Os::File::OP_OK);
Os::Stub::File::Test::StaticData::setPositionResult(50);
ASSERT_EQ(file.position(positionResult), Os::File::OP_OK);
ASSERT_EQ(positionResult, 50);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.lastCalled, Os::Stub::File::Test::StaticData::POSITION_FN);
}
// Ensure that Os::File properly routes preallocate calls to the `preallocateInternal` function.
TEST_F(Interface, Preallocate) {
Os::File file;
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OP_OK);
ASSERT_EQ(file.open("/does/not/matter", Os::File::OPEN_CREATE, Os::File::OverwriteType::OVERWRITE), Os::File::OP_OK);
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OTHER_ERROR);
ASSERT_EQ(file.preallocate(0, 0), Os::File::Status::OTHER_ERROR);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.lastCalled, Os::Stub::File::Test::StaticData::PREALLOCATE_FN);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.preallocateOffset, 0);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.preallocateLength, 0);
}
// Ensure that Os::File properly routes seek calls to the `seekInternal` function.
TEST_F(Interface, Seek) {
Os::File file;
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OP_OK);
ASSERT_EQ(file.open("/does/not/matter", Os::File::OPEN_CREATE, Os::File::OverwriteType::OVERWRITE), Os::File::OP_OK);
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OTHER_ERROR);
ASSERT_EQ(file.seek(0, Os::File::SeekType::ABSOLUTE), Os::File::Status::OTHER_ERROR);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.lastCalled, Os::Stub::File::Test::StaticData::SEEK_FN);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.seekOffset, 0);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.seekType, Os::File::SeekType::ABSOLUTE);
}
// Ensure that Os::File properly routes flush calls to the `flushInternal` function.
TEST_F(Interface, Flush) {
Os::File file;
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OP_OK);
ASSERT_EQ(file.open("/does/not/matter", Os::File::OPEN_CREATE, Os::File::OverwriteType::OVERWRITE), Os::File::OP_OK);
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OTHER_ERROR);
ASSERT_EQ(file.flush(), Os::File::Status::OTHER_ERROR);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.lastCalled, Os::Stub::File::Test::StaticData::FLUSH_FN);
}
// Ensure that Os::File properly routes flush calls to the `flushInternal` function.
TEST_F(Interface, Read) {
U8 buffer[] = {0xab, 0xcd, 0xef};
FwSignedSizeType size = static_cast<FwSignedSizeType>(sizeof buffer);
FwSignedSizeType original_size = size;
Os::File file;
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OP_OK);
ASSERT_EQ(file.open("/does/not/matter", Os::File::OPEN_READ, Os::File::OverwriteType::OVERWRITE), Os::File::OP_OK);
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OTHER_ERROR);
ASSERT_EQ(file.read(buffer, size, Os::File::WaitType::WAIT), Os::File::Status::OTHER_ERROR);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.lastCalled, Os::Stub::File::Test::StaticData::READ_FN);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.readBuffer, buffer);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.readSize, original_size);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.readWait, Os::File::WaitType::WAIT);
}
// Ensure that Os::File properly routes statuses returned from the `flushInternal` function back to the caller.
TEST_F(Interface, Write) {
U8 buffer[] = {0xab, 0xcd, 0xef};
FwSignedSizeType size = static_cast<FwSignedSizeType>(sizeof buffer);
FwSignedSizeType original_size = size;
Os::File file;
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OP_OK);
ASSERT_EQ(file.open("/does/not/matter", Os::File::OPEN_WRITE, Os::File::OverwriteType::OVERWRITE), Os::File::OP_OK);
Os::Stub::File::Test::StaticData::setNextStatus(Os::File::OTHER_ERROR);
ASSERT_EQ(file.write(buffer, size, Os::File::WaitType::WAIT), Os::File::Status::OTHER_ERROR);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.lastCalled, Os::Stub::File::Test::StaticData::WRITE_FN);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.writeBuffer, buffer);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.writeSize, original_size);
ASSERT_EQ(Os::Stub::File::Test::StaticData::data.writeWait, Os::File::WaitType::WAIT);
}
// Ensure that FPP shadow enumeration matches
TEST(FppTypes, FileStatusEnum) {
for (FwIndexType i = static_cast<FwIndexType>(Os::File::Status::OP_OK); i < static_cast<FwIndexType>(Os::File::Status::MAX_STATUS); i++){
Os::File::Status status = static_cast<Os::File::Status>(i);
Os::FileStatus fpp_status = static_cast<Os::FileStatus::T>(status);
ASSERT_TRUE(fpp_status.isValid());
}
}
// Ensure that FPP shadow enumeration matches
TEST(FppTypes, FileModeEnum) {
for (FwIndexType i = static_cast<FwIndexType>(Os::File::Mode::OPEN_CREATE); i < static_cast<FwIndexType>(Os::File::Mode::MAX_OPEN_MODE); i++){
Os::File::Mode mode = static_cast<Os::File::Mode>(i);
Os::FileMode fpp_mode = static_cast<Os::FileMode::T>(mode);
ASSERT_TRUE(fpp_mode.isValid());
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Os/test/ut/OsFileSystemTest.cpp | #include <gtest/gtest.h>
#include <Os/FileSystem.hpp>
#include <Os/File.hpp>
#include <Fw/Types/Assert.hpp>
#include <Fw/Types/String.hpp>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
void testTestFileSystem() {
Os::FileSystem::Status file_sys_status;
Os::File::Status file_status;
Os::File test_file = Os::File();
const char test_file_name1[] = "test_file1";
const char test_file_name2[] = "test_file2";
const char test_dir1[] = "./test_dir1";
const char test_dir2[] = "./test_dir2";
const char up_dir[] = "../";
const char cur_dir[] = ".";
struct stat info;
FwSignedSizeType file_size = 42;
U32 file_count = 0;
const U8 test_string[] = "This is a test file.";
FwSignedSizeType test_string_len = 0;
printf("Creating %s directory\n", test_dir1);
if ((file_sys_status = Os::FileSystem::createDirectory(test_dir1)) != Os::FileSystem::OP_OK) {
printf("\tFailed to create directory: %s\n", test_dir1);
printf("\tReturn status: %d\n", file_sys_status);
ASSERT_TRUE(0);
}
ASSERT_EQ(stat(test_dir1, &info),0);
// Check directory file count
printf("Checking directory file count of %s is 0.\n", test_dir1);
if ((file_sys_status = Os::FileSystem::getFileCount(test_dir1, file_count)) != Os::FileSystem::OP_OK) {
printf("\tFailed to get file count of %s\n", test_dir1);
printf("\tReturn status: %d\n", file_sys_status);
ASSERT_TRUE(0);
}
ASSERT_EQ(file_count,0);
printf("Moving directory (%s) to (%s).\n", test_dir1, test_dir2);
if ((file_sys_status = Os::FileSystem::moveFile(test_dir1, test_dir2)) != Os::FileSystem::OP_OK) {
printf("\tFailed to move directory (%s) to (%s).\n", test_dir1, test_dir2);
printf("\tReturn status: %d\n", file_sys_status);
ASSERT_TRUE(0);
}
ASSERT_EQ(stat(test_dir1, &info),-1);
ASSERT_EQ(stat(test_dir2, &info),0);
printf("Trying to copy directory (%s) to (%s).\n", test_dir2, test_dir1);
if ((file_sys_status = Os::FileSystem::copyFile(test_dir2, test_dir1)) == Os::FileSystem::OP_OK) {
printf("\tShould not have been able to copy a directory %s to %s.\n", test_dir2, test_dir1);
printf("\tReturn status: %d\n", file_sys_status);
ASSERT_TRUE(0);
}
ASSERT_EQ(stat(test_dir1, &info),-1);
ASSERT_EQ(stat(test_dir2, &info),0);
printf("Removing directory %s\n", test_dir2);
if ((file_sys_status = Os::FileSystem::removeDirectory(test_dir2)) != Os::FileSystem::OP_OK) {
printf("\tFailed to remove directory: %s\n", test_dir2);
printf("\tReturn status: %d\n", file_sys_status);
ASSERT_TRUE(0);
}
ASSERT_EQ(stat(test_dir2, &info),-1);
//Create a file
printf("Creating test file (%s)\n", test_file_name1);
if ((file_status = test_file.open(test_file_name1, Os::File::OPEN_WRITE)) != Os::File::OP_OK) {
printf("\tFailed to create file: %s\n", test_file_name1);
printf("\tReturn status: %d\n", file_status);
ASSERT_TRUE(0);
}
test_string_len = sizeof(test_string);
printf("Writing to test file (%s) for testing.\n", test_file_name1);
if((file_status = test_file.write(test_string, test_string_len, Os::File::WaitType::WAIT)) != Os::File::OP_OK) {
printf("\tFailed to write to file: %s\n.", test_file_name1);
printf("\tReturn status: %d\n", file_status);
ASSERT_TRUE(0);
}
//Close test file
test_file.close();
file_size = 42;
//Get file size
printf("Checking file size of %s.\n", test_file_name1);
if ((file_sys_status = Os::FileSystem::getFileSize(test_file_name1, file_size)) != Os::FileSystem::OP_OK) {
printf("\tFailed to get file size of %s\n", test_file_name1);
printf("\tReturn status: %d\n", file_sys_status);
ASSERT_TRUE(0);
}
ASSERT_EQ(file_size,sizeof(test_string));
printf("Copying file (%s) to (%s).\n", test_file_name1, test_file_name2);
if ((file_sys_status = Os::FileSystem::copyFile(test_file_name1, test_file_name2)) != Os::FileSystem::OP_OK) {
printf("\tFailed to copy file (%s) to (%s)\n", test_file_name1, test_file_name2);
printf("\tReturn status: %d\n", file_sys_status);
ASSERT_TRUE(0);
}
ASSERT_EQ(stat(test_file_name1, &info),0);
ASSERT_EQ(stat(test_file_name2, &info),0);
unsigned char file_buf1[64];
unsigned char file_buf2[64];
// Read the two files and make sure they are the same
test_string_len = sizeof(test_string);
test_file.open(test_file_name1, Os::File::OPEN_READ);
test_file.read(file_buf1, test_string_len, Os::File::WaitType::NO_WAIT);
test_file.close();
test_string_len = sizeof(test_string);
test_file.open(test_file_name2, Os::File::OPEN_READ);
test_file.read(file_buf2, test_string_len, Os::File::WaitType::NO_WAIT);
test_file.close();
ASSERT_EQ(::strcmp(reinterpret_cast<const char*>(file_buf1), reinterpret_cast<const char*>(file_buf2)),0);
printf("Removing test file 1 (%s)\n", test_file_name1);
if ((file_sys_status = Os::FileSystem::removeFile(test_file_name1)) != Os::FileSystem::OP_OK) {
printf("\tFailed to remove file (%s)\n", test_file_name1);
printf("\tReturn status: %d\n", file_sys_status);
ASSERT_TRUE(0);
}
ASSERT_EQ(stat(test_file_name1, &info),-1);
printf("Removing test file 2 (%s)\n", test_file_name2);
if ((file_sys_status = Os::FileSystem::removeFile(test_file_name2)) != Os::FileSystem::OP_OK) {
printf("\tFailed to remove file (%s)\n", test_file_name2);
printf("\tReturn status: %d\n", file_sys_status);
ASSERT_TRUE(0);
}
ASSERT_EQ(stat(test_file_name2, &info),-1);
printf("Getting the number of files in (%s)\n", cur_dir);
if ((file_sys_status = Os::FileSystem::getFileCount(cur_dir, file_count)) != Os::FileSystem::OP_OK) {
printf("\tFailed to get number of files in (%s)\n", cur_dir);
printf("\tReturn status: %d\n", file_sys_status);
ASSERT_TRUE(0);
}
ASSERT_TRUE(file_count > 0);
printf("Reading the files in (%s)\n", cur_dir);
const int num_str = 5;
U32 num_2 = num_str;
Fw::String str_array[num_str];
if ((file_sys_status = Os::FileSystem::readDirectory(cur_dir, num_str, str_array, num_2)) != Os::FileSystem::OP_OK) {
printf("\tFailed to read files in (%s)\n", cur_dir);
printf("\tReturn status: %d\n", file_sys_status);
ASSERT_TRUE(0);
}
else {
for (int i = 0; i < num_str; ++i) {
printf("%s\n",str_array[i].toChar());
}
}
printf("Changing working directory to (%s)\n", up_dir);
if ((file_sys_status = Os::FileSystem::changeWorkingDirectory(up_dir)) != Os::FileSystem::OP_OK) {
printf("\tFailed to change working directory to: %s\n", up_dir);
printf("\tReturn status: %d\n", file_sys_status);
ASSERT_TRUE(0);
}
printf("Checking current working directory is (%s)\n", up_dir);
char dir_buff[256];
getcwd(dir_buff, 256);
printf("Current dir: %s\n", dir_buff);
//Create a file in OPEN_CREATE mode
printf("Creating test file (%s)\n", test_file_name1);
if ((file_status = test_file.open(test_file_name1, Os::File::OPEN_CREATE)) != Os::File::OP_OK) {
printf("\tFailed to OPEN_CREATE file: %s\n", test_file_name1);
printf("\tReturn status: %d\n", file_status);
ASSERT_TRUE(0);
}
//Close test file
test_file.close();
//Should not be able to OPEN_CREATE file since it already exist and we have
//include_excl enabled
printf("Creating test file (%s)\n", test_file_name1);
if ((file_status = test_file.open(test_file_name1, Os::File::OPEN_CREATE)) != Os::File::FILE_EXISTS) {
printf("\tFailed to not to overwrite existing file: %s\n", test_file_name1);
printf("\tReturn status: %d\n", file_status);
ASSERT_TRUE(0);
}
printf("Removing test file 1 (%s)\n", test_file_name1);
if ((file_sys_status = Os::FileSystem::removeFile(test_file_name1)) != Os::FileSystem::OP_OK) {
printf("\tFailed to remove file (%s)\n", test_file_name1);
printf("\tReturn status: %d\n", file_sys_status);
ASSERT_TRUE(0);
}
ASSERT_EQ(stat(test_file_name1, &info),-1);
}
extern "C" {
void fileSystemTest();
}
void fileSystemTest() {
testTestFileSystem();
}
| cpp |
fprime | data/projects/fprime/Os/test/ut/OsTestMain.cpp | #include "gtest/gtest.h"
#include <cstdlib>
#include <unistd.h>
#include <cstdio>
extern "C" {
void startTestTask();
void qtest_block_receive();
void qtest_nonblock_receive();
void qtest_nonblock_send();
void qtest_block_send();
void qtest_performance();
void qtest_concurrent();
void intervalTimerTest();
void fileSystemTest();
void validateFileTest(const char* filename);
void systemResourcesTest();
void mutexBasicLockableTest();
}
const char* filename;
TEST(Nominal, StartTestTask) {
startTestTask();
}
TEST(Nominal, QTestBlockRecv) {
qtest_block_receive();
}
TEST(Nominal, QTestNonBlockRecv) {
qtest_nonblock_receive();
}
TEST(Nominal, QTestNonBlockSend) {
qtest_nonblock_send();
}
TEST(Nominal, QTestBlockSend) {
qtest_block_send();
}
TEST(Nominal, QTestPerformance) {
qtest_performance();
}
TEST(Nominal, QTestConcurrentTest) {
qtest_concurrent();
}
// The interval timer unit test is timed off a 1 sec thread delay. Mac OS allows a large amount of
// scheduling jitter to conserve energy, which rarely causes this sleep to be slightly shorter
// (~0.99 s) or longer (~10 sec) than requested, causing the test to fail. The interval timer should
// be rewritten to not directly utilize the OS clock, but in the mean time disabling this test on
// Mac OS prevents intermittent unit test failures.
TEST(Nominal, DISABLED_IntervalTimerTest) {
intervalTimerTest();
}
TEST(Nominal, FileSystemTest) {
fileSystemTest();
}
TEST(Nominal, ValidateFileTest) {
validateFileTest(filename);
}
TEST(Nominal, SystemResourcesTest) {
systemResourcesTest();
}
TEST(Nominal, MutexBasicLockableTest) {
mutexBasicLockableTest();
}
int main(int argc, char* argv[]) {
filename = argv[0];
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Os/test/ut/IntervalTimerTest.cpp | #include "gtest/gtest.h"
#include <Os/IntervalTimer.hpp>
#include <Os/Task.hpp>
#include <cstdio>
extern "C" {
void intervalTimerTest();
}
void intervalTimerTest() {
Os::IntervalTimer timer;
timer.start();
Os::Task::delay(1000);
timer.stop();
ASSERT_GE(timer.getDiffUsec(), 1000000);
ASSERT_LT(timer.getDiffUsec(), 1005000);
}
| cpp |
fprime | data/projects/fprime/Os/test/ut/OsSystemResourcesTest.cpp | #include <gtest/gtest.h>
#include <Os/SystemResources.hpp>
#include <Fw/Types/Assert.hpp>
#include <Fw/Types/String.hpp>
void testTestSystemResources() {
Os::SystemResources::SystemResourcesStatus sys_res_status;
Os::SystemResources::CpuTicks cpuUtil;
U32 cpuCount;
U32 cpuIndex;
sys_res_status = Os::SystemResources::getCpuCount(cpuCount);
ASSERT_EQ(sys_res_status, Os::SystemResources::SystemResourcesStatus::SYSTEM_RESOURCES_OK);
cpuIndex = 0;
sys_res_status = Os::SystemResources::getCpuTicks(cpuUtil, cpuIndex);
ASSERT_EQ(sys_res_status, Os::SystemResources::SystemResourcesStatus::SYSTEM_RESOURCES_OK);
cpuIndex = 1000;
sys_res_status = Os::SystemResources::getCpuTicks(cpuUtil, cpuIndex);
ASSERT_EQ(sys_res_status, Os::SystemResources::SystemResourcesStatus::SYSTEM_RESOURCES_ERROR);
}
extern "C" {
void systemResourcesTest(void);
}
void systemResourcesTest(void) {
testTestSystemResources();
}
| cpp |
fprime | data/projects/fprime/Os/test/ut/OsQueueTest.cpp | #include "gtest/gtest.h"
#include <Os/Queue.hpp>
#include <cstdio>
#include <cstring>
#include <Fw/Types/Assert.hpp>
#include <unistd.h>
#include <csignal>
#include <pthread.h>
#if defined TGT_OS_TYPE_LINUX
#include <ctime>
#endif
#if defined TGT_OS_TYPE_DARWIN
#include <sys/time.h>
#endif
// Set this to 1 if testing a priority queue
// Set this to 0 if testing a fifo queue
#define PRIORITY_QUEUE 1
enum {
SER_BUFFER_SIZE = 100,
QUEUE_SIZE = 10
};
class MyTestSerializedBuffer : public Fw::SerializeBufferBase {
public:
MyTestSerializedBuffer() { memset(m_someBuffer, 0, sizeof(m_someBuffer)); }
~MyTestSerializedBuffer() {}
NATIVE_UINT_TYPE getBuffCapacity() const { return sizeof(this->m_someBuffer); }
U8* getBuffAddr() { return m_someBuffer;}
const U8* getBuffAddr() const {return m_someBuffer;}
private:
U8 m_someBuffer[SER_BUFFER_SIZE];
};
Os::Queue* createTestQueue(const char *name, U32 size, I32 depth) {
Os::Queue* testQueue = new Os::Queue();
Os::Queue::QueueStatus stat = testQueue->create(Os::QueueString(name), depth, size);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
// Make sure the queue is of the correct size:
NATIVE_INT_TYPE num;
num = testQueue->getNumMsgs(); //!< get the number of messages in the queue
EXPECT_EQ(num, 0);
num = testQueue->getMaxMsgs(); //!< get the maximum number of messages (high watermark)
EXPECT_EQ(num, 0);
num = testQueue->getQueueSize(); //!< get the queue depth (maximum number of messages queue can hold)
EXPECT_EQ(num, depth);
num = testQueue->getMsgSize(); //!< get the message size (maximum message size queue can hold)
EXPECT_EQ(num, static_cast<I32>(size));
return testQueue;
}
MyTestSerializedBuffer getSendBuffer(I32 startByte) {
Fw::SerializeStatus serStat;
MyTestSerializedBuffer sendBuff;
NATIVE_UINT_TYPE size = sendBuff.getBuffCapacity() - sizeof(NATIVE_UINT_TYPE);
// Fill serialized buffer with data:
U8 sendDataBuff[SER_BUFFER_SIZE];
I32 count = startByte;
for (U32 byte = 0; byte < size; byte++) {
sendDataBuff[byte] = count;
count++;
}
serStat = sendBuff.serialize(sendDataBuff, size);
EXPECT_EQ(serStat,Fw::FW_SERIALIZE_OK);
return sendBuff;
}
void compareBuffers(MyTestSerializedBuffer& a, MyTestSerializedBuffer& b) {
NATIVE_UINT_TYPE size = a.getBuffCapacity() - sizeof(NATIVE_UINT_TYPE);
Fw::SerializeStatus serStat;
U8 aBuff[SER_BUFFER_SIZE];
serStat = a.deserialize(aBuff, size);
EXPECT_EQ(serStat,Fw::FW_SERIALIZE_OK);
U8 bBuff[SER_BUFFER_SIZE];
serStat = b.deserialize(bBuff, size);
EXPECT_EQ(serStat,Fw::FW_SERIALIZE_OK);
for (U32 ii = 0; ii < size; ii++) {
if (aBuff[ii] != bBuff[ii]) {
printf("Byte %u mismatch. A: %d B: %d\n", ii, aBuff[ii], bBuff[ii]);
EXPECT_TRUE(0);
}
}
}
void fillQueue(Os::Queue* queue) {
// Fill the queue.
// Note this loop should only need to go to QUEUE_SIZE,
// but the SysV queues don't actually have a size, so
// instead we loop until we get a queue full response:
MyTestSerializedBuffer sendBuff = getSendBuffer(0);
Os::Queue::QueueStatus stat;
for( NATIVE_INT_TYPE ii = 0; ii < QUEUE_SIZE*100; ii++ ) {
stat = queue->send(sendBuff, 0, Os::Queue::QUEUE_NONBLOCKING);
if(stat == Os::Queue::QUEUE_FULL)
break;
EXPECT_EQ(stat, Os::Queue::QUEUE_OK);
}
}
void drainQueue(Os::Queue* queue) {
// Fill the queue.
// Note this loop should only need to go to QUEUE_SIZE,
// but the SysV queues don't actually have a size, so
// instead we loop until we get a queue full response:
MyTestSerializedBuffer recvBuff;
I32 prio;
Os::Queue::QueueStatus stat;
while (queue->getNumMsgs() > 0) {
stat = queue->receive(recvBuff, prio, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat, Os::Queue::QUEUE_OK);
}
}
extern "C" {
void qtest_block_receive();
void qtest_nonblock_receive();
void qtest_performance();
void qtest_nonblock_send();
void qtest_block_send();
void qtest_concurrent();
}
// Alarm signal handler for waking up a blocked queue:
Os::Queue* globalQueue = nullptr;
void alarm_send_block(int sig)
{
MyTestSerializedBuffer sendBuff = getSendBuffer(0);
Os::Queue::QueueStatus stat;
stat = globalQueue->send(sendBuff, 0, Os::Queue::QUEUE_BLOCKING);
EXPECT_EQ(stat, Os::Queue::QUEUE_OK);
}
void alarm_send_nonblock(int sig)
{
MyTestSerializedBuffer sendBuff = getSendBuffer(0);
Os::Queue::QueueStatus stat;
stat = globalQueue->send(sendBuff, 0, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat, Os::Queue::QUEUE_OK);
}
void alarm_receive_block(int sig)
{
MyTestSerializedBuffer recvBuff;
Os::Queue::QueueStatus stat;
I32 prio;
stat = globalQueue->receive(recvBuff, prio, Os::Queue::QUEUE_BLOCKING);
EXPECT_EQ(stat, Os::Queue::QUEUE_OK);
}
void alarm_receive_nonblock(int sig)
{
MyTestSerializedBuffer recvBuff;
Os::Queue::QueueStatus stat;
I32 prio;
stat = globalQueue->receive(recvBuff, prio, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat, Os::Queue::QUEUE_OK);
}
void alarm_error(int sig)
{
// A failure here means that something blocked that was
// not supposed to block!
EXPECT_TRUE(0);
}
// This test verifies queue behavior for active components
// ie. non-blocking send on queue full, blocking receive on queue empty
void qtest_nonblock_send() {
printf("-----------------------------\n");
printf("-- nonblocking send test ----\n");
printf("-----------------------------\n");
Os::Queue* testQueue = createTestQueue("TestQ",SER_BUFFER_SIZE,QUEUE_SIZE);
Os::Queue::QueueStatus stat;
MyTestSerializedBuffer sendBuff = getSendBuffer(0);
// TEST 1
printf("Testing non-blocking send on queue full...\n");
// Register an alarm handler to wake us up in case we block:
globalQueue = testQueue;
signal(SIGALRM, alarm_error);
alarm(2);
fillQueue(testQueue);
// Make sure we get a queue full response:
stat = testQueue->send(sendBuff, 0, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat, Os::Queue::QUEUE_FULL);
// Reset the alarm:
alarm(0);
drainQueue(testQueue);
globalQueue = nullptr;
printf("Passed.\n");
delete testQueue;
printf("Test complete.\n");
printf("-----------------------------\n");
printf("-----------------------------\n");
}
void qtest_block_send() {
printf("-----------------------------\n");
printf("---- blocking send test -----\n");
printf("-----------------------------\n");
Os::Queue* testQueue = createTestQueue("TestQ",SER_BUFFER_SIZE,QUEUE_SIZE);
Os::Queue::QueueStatus stat;
MyTestSerializedBuffer sendBuff = getSendBuffer(0);
// TEST 1
printf("Testing blocking send on queue full with blocking receive...\n");
// Register an alarm handler to wake us up in case we block:
globalQueue = testQueue;
signal(SIGALRM, alarm_receive_block);
alarm(2);
fillQueue(testQueue);
// Make sure we get a queue full response:
stat = testQueue->send(sendBuff, 0, Os::Queue::QUEUE_BLOCKING);
EXPECT_EQ(stat, Os::Queue::QUEUE_OK);
// Reset the alarm:
alarm(0);
drainQueue(testQueue);
globalQueue = nullptr;
printf("Passed.\n");
// TEST 2
printf("Testing blocking send on queue full nonblocking receive...\n");
// Register an alarm handler to wake us up in case we block:
globalQueue = testQueue;
signal(SIGALRM, alarm_receive_nonblock);
alarm(2);
fillQueue(testQueue);
// Make sure we get a queue full response:
stat = testQueue->send(sendBuff, 0, Os::Queue::QUEUE_BLOCKING);
EXPECT_EQ(stat, Os::Queue::QUEUE_OK);
// Reset the alarm:
alarm(0);
drainQueue(testQueue);
globalQueue = nullptr;
printf("Passed.\n");
delete testQueue;
printf("Test complete.\n");
printf("-----------------------------\n");
printf("-----------------------------\n");
}
// This test verifies queue behavior for active components
// ie. non-blocking send on queue full, blocking receive on queue empty
void qtest_block_receive() {
printf("-----------------------------\n");
printf("-- blocking receive test ----\n");
printf("-----------------------------\n");
Os::Queue* testQueue = createTestQueue("TestQ",SER_BUFFER_SIZE,QUEUE_SIZE);
Os::Queue::QueueStatus stat;
MyTestSerializedBuffer recvBuff;
MyTestSerializedBuffer sendBuff = getSendBuffer(0);
I32 prio; // not used
// TEST 1
printf("Testing successful receive after send...\n");
stat = testQueue->send(sendBuff, 0, Os::Queue::QUEUE_NONBLOCKING);
ASSERT_EQ(stat, Os::Queue::QUEUE_OK);
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_BLOCKING);
ASSERT_EQ(stat, Os::Queue::QUEUE_OK);
compareBuffers(sendBuff, recvBuff);
printf("Passed.\n");
// TEST 2
printf("Testing blocking receive on queue empty with blocking send...\n");
// Register an alarm handler to wake us after waiting on the queue:
globalQueue = testQueue;
signal(SIGALRM, alarm_send_block);
alarm(2);
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_BLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
globalQueue = nullptr;
printf("Passed.\n");
// TEST 3
printf("Testing blocking receive on queue empty with nonblocking send...\n");
// Register an alarm handler to wake us after waiting on the queue:
globalQueue = testQueue;
signal(SIGALRM, alarm_send_nonblock);
alarm(2);
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_BLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
globalQueue = nullptr;
printf("Passed.\n");
// TEST 5
printf("Test send and receive with priorities...\n");
// Send messages with mixed priorities,
// and make sure we get back the buffers in
// the correct order.
I32 sendBuffStart[6] = {11, 45, 70, 123, 200, 400};
NATIVE_INT_TYPE priorities[6] = {0, 50, 50, 99, 0, 16};
for( I32 ii = 0; ii < 6; ii++ ) {
// Generate a new send buffer for each enqueue:
MyTestSerializedBuffer sendBuff2 = getSendBuffer(sendBuffStart[ii]);
stat = testQueue->send(sendBuff2, priorities[ii], Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
}
#if PRIORITY_QUEUE
I32 expectedSendBuffStart[6] = {123, 45, 70, 400, 11, 200};
NATIVE_INT_TYPE expectedPriorities[6] = {99, 50, 50, 16, 0, 0};
#else
I32 expectedSendBuffStart[6] = {11, 45, 70, 123, 200, 400};
NATIVE_INT_TYPE expectedPriorities[6] = {0, 0, 0, 0, 0, 0};
#endif
for( I32 ii = 0; ii < 6; ii++ ) {
// Generate a new send buffer for each enqueue:
MyTestSerializedBuffer expectedSendBuff2 = getSendBuffer(expectedSendBuffStart[ii]);
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_BLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
EXPECT_EQ(prio,expectedPriorities[ii]);
EXPECT_TRUE(memcmp(recvBuff.getBuffAddr(), expectedSendBuff2.getBuffAddr(), recvBuff.getBuffLength()) == 0);
}
printf("Passed.\n");
delete testQueue;
printf("Test complete.\n");
printf("-----------------------------\n");
printf("-----------------------------\n");
}
// This test verifies queue behavior for queued components
// ie. non-blocking send on queue full, non-blocking receive on queue empty
void qtest_nonblock_receive() {
printf("-----------------------------\n");
printf("- nonblocking receive test --\n");
printf("-----------------------------\n");
Os::Queue* testQueue = createTestQueue("TestQ", SER_BUFFER_SIZE, QUEUE_SIZE);
Os::Queue::QueueStatus stat;
MyTestSerializedBuffer recvBuff;
MyTestSerializedBuffer sendBuff = getSendBuffer(0);
I32 prio; // not used
// TEST 1
printf("Testing successful receive after send...\n");
stat = testQueue->send(sendBuff, 0, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
compareBuffers(sendBuff, recvBuff);
printf("Passed.\n");
// TEST 2
printf("Testing non-blocking receive on queue empty...\n");
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_NO_MORE_MSGS);
printf("Passed.\n");
// TEST 3
printf("Test send and receive with priorities...\n");
// Send messages with mixed priorities,
// and make sure we get back the buffers in
// the correct order.
I32 sendBuffStart[6] = {11, 45, 70, 123, 200, 400};
NATIVE_INT_TYPE priorities[6] = {0, 50, 50, 99, 0, 16};
for( I32 ii = 0; ii < 6; ii++ ) {
// Generate a new send buffer for each enqueue:
MyTestSerializedBuffer sendBuff2 = getSendBuffer(sendBuffStart[ii]);
stat = testQueue->send(sendBuff2, priorities[ii], Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
}
#if PRIORITY_QUEUE
I32 expectedSendBuffStart[6] = {123, 45, 70, 400, 11, 200};
NATIVE_INT_TYPE expectedPriorities[6] = {99, 50, 50, 16, 0, 0};
#else
I32 expectedSendBuffStart[6] = {11, 45, 70, 123, 200, 400};
NATIVE_INT_TYPE expectedPriorities[6] = {0, 0, 0, 0, 0, 0};
#endif
for( I32 ii = 0; ii < 6; ii++ ) {
// Generate a new send buffer for each enqueue:
MyTestSerializedBuffer expectedSendBuff2 = getSendBuffer(expectedSendBuffStart[ii]);
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
EXPECT_EQ(prio,expectedPriorities[ii]);
EXPECT_TRUE(memcmp(recvBuff.getBuffAddr(), expectedSendBuff2.getBuffAddr(), recvBuff.getBuffLength()) == 0);
}
printf("Passed.\n");
delete testQueue;
printf("Test complete.\n");
printf("-----------------------------\n");
printf("-----------------------------\n");
}
// This test shows the performance of the queue:
void qtest_performance() {
printf("-----------------------------\n");
printf("---- performance test -------\n");
printf("-----------------------------\n");
Os::Queue* testQueue = createTestQueue("TestQ", SER_BUFFER_SIZE, 10);
Os::Queue::QueueStatus stat;
MyTestSerializedBuffer recvBuff;
MyTestSerializedBuffer sendBuff = getSendBuffer(0);
I32 prio; // not used
F64 elapsedTime;
I32 numIterations;
#if defined TGT_OS_TYPE_LINUX
timespec stime;
timespec etime;
#endif
#if defined TGT_OS_TYPE_DARWIN
timeval stime;
timeval etime;
#endif
// TEST 1
printf("Testing shallow queue...\n");
#if defined TGT_OS_TYPE_LINUX
(void)clock_gettime(CLOCK_REALTIME,&stime);
#endif
#if defined TGT_OS_TYPE_DARWIN
(void)gettimeofday(&stime,nullptr);
#endif
numIterations = 1000000;
for( NATIVE_INT_TYPE ii = 0; ii < numIterations; ii++ ) {
stat = testQueue->send(sendBuff, ii%4, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->send(sendBuff, ii%4, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->send(sendBuff, ii%4, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
}
#if defined TGT_OS_TYPE_LINUX
(void)clock_gettime(CLOCK_REALTIME,&etime);
elapsedTime = static_cast<F64>(etime.tv_sec - stime.tv_sec) + static_cast<F64>(etime.tv_nsec - stime.tv_nsec)/1000000000;
printf("Time: %0.3fs (%0.3fus per)\n", elapsedTime, 1000000*elapsedTime/static_cast<F64>(numIterations));
#endif
#if defined TGT_OS_TYPE_DARWIN
(void)gettimeofday(&etime,nullptr);
elapsedTime = static_cast<F64>(etime.tv_sec - stime.tv_sec) + static_cast<F64>(etime.tv_usec - stime.tv_usec)/1000000;
printf("Time: %0.3fs (%0.3fus per)\n", elapsedTime, 1000000*elapsedTime/static_cast<F64>(numIterations));
#endif
// TEST 2
printf("Testing deep queue...\n");
// Fill the queue up first:
U32 count = 0;
while(true) {
stat = testQueue->send(sendBuff, count%4, Os::Queue::QUEUE_NONBLOCKING);
count++;
if(stat == Os::Queue::QUEUE_FULL)
break;
}
#if defined TGT_OS_TYPE_LINUX
(void)clock_gettime(CLOCK_REALTIME,&stime);
#endif
#if defined TGT_OS_TYPE_DARWIN
(void)gettimeofday(&stime,nullptr);
#endif
numIterations = 1000000;
for( NATIVE_INT_TYPE ii = 0; ii < numIterations; ii++ ) {
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->send(sendBuff, ii%4, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->send(sendBuff, ii%4, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->send(sendBuff, ii%4, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
}
#if defined TGT_OS_TYPE_LINUX
(void)clock_gettime(CLOCK_REALTIME,&etime);
elapsedTime = static_cast<F64>(etime.tv_sec - stime.tv_sec) + static_cast<F64>(etime.tv_nsec - stime.tv_nsec)/1000000000;
printf("Time: %0.3fs (%0.3fus per)\n", elapsedTime, 1000000*elapsedTime/static_cast<F64>(numIterations));
#endif
#if defined TGT_OS_TYPE_DARWIN
(void)gettimeofday(&etime,nullptr);
elapsedTime = static_cast<F64>(etime.tv_sec - stime.tv_sec) + static_cast<F64>(etime.tv_usec - stime.tv_usec)/1000000;
printf("Time: %0.3fs (%0.3fus per)\n", elapsedTime, 1000000*elapsedTime/static_cast<F64>(numIterations));
#endif
while(true) {
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_NONBLOCKING);
if(stat == Os::Queue::QUEUE_NO_MORE_MSGS)
break;
}
delete testQueue;
printf("Test complete.\n");
printf("-----------------------------\n");
printf("-----------------------------\n");
}
#define NUM_THREADS 4
I32 numIterations = 50000;
void *run_task(void *ptr)
{
Os::Queue* testQueue = static_cast<Os::Queue*>(ptr);
Os::Queue::QueueStatus stat;
I32 prio; // not used
MyTestSerializedBuffer recvBuff;
MyTestSerializedBuffer sendBuff = getSendBuffer(0);
for( NATIVE_INT_TYPE ii = 0; ii < numIterations; ii++ ) {
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_BLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_BLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->receive(recvBuff, prio, Os::Queue::QUEUE_BLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->send(sendBuff, ii%4, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->send(sendBuff, ii%4, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
stat = testQueue->send(sendBuff, ii%4, Os::Queue::QUEUE_NONBLOCKING);
EXPECT_EQ(stat,Os::Queue::QUEUE_OK);
}
return nullptr;
}
// This test shows the concurrent performance of the queue:
void qtest_concurrent() {
printf("---------------------\n");
printf("-- concurrent test --\n");
printf("---------------------\n");
Os::Queue* testQueue = createTestQueue("TestQ", SER_BUFFER_SIZE, 10);
Os::Queue::QueueStatus stat;
MyTestSerializedBuffer recvBuff;
MyTestSerializedBuffer sendBuff = getSendBuffer(0);
F64 elapsedTime;
#if defined TGT_OS_TYPE_LINUX
timespec stime;
timespec etime;
#endif
#if defined TGT_OS_TYPE_DARWIN
timeval stime;
timeval etime;
#endif
printf("Testing deep queue...\n");
// Fill the queue up first:
U32 count = 0;
while(true) {
stat = testQueue->send(sendBuff,count%4, Os::Queue::QUEUE_NONBLOCKING);
count++;
if(stat == Os::Queue::QUEUE_FULL)
break;
}
#if defined TGT_OS_TYPE_LINUX
(void)clock_gettime(CLOCK_REALTIME,&stime);
#endif
#if defined TGT_OS_TYPE_DARWIN
(void)gettimeofday(&stime,nullptr);
#endif
#if defined TGT_OS_TYPE_LINUX || TGT_OS_TYPE_DARWIN
pthread_t thread[NUM_THREADS];
for(U32 ii = 0; ii < NUM_THREADS; ++ii) {
if(pthread_create(&thread[ii], nullptr, run_task, testQueue)) {
EXPECT_TRUE(0);
}
}
for(U32 ii = 0; ii < NUM_THREADS; ++ii) {
if(pthread_join(thread[ii], nullptr)) {
EXPECT_TRUE(0);
}
}
#endif
#if defined TGT_OS_TYPE_LINUX
(void)clock_gettime(CLOCK_REALTIME,&etime);
elapsedTime = static_cast<F64>(etime.tv_sec - stime.tv_sec) + static_cast<F64>(etime.tv_nsec - stime.tv_nsec)/1000000000;
printf("Time: %0.3fs (%0.3fus per)\n", elapsedTime, 1000000*elapsedTime/static_cast<F64>(numIterations));
#endif
#if defined TGT_OS_TYPE_DARWIN
(void)gettimeofday(&etime,nullptr);
elapsedTime = static_cast<F64>(etime.tv_sec - stime.tv_sec) + static_cast<F64>(etime.tv_usec - stime.tv_usec)/1000000;
printf("Time: %0.3fs (%0.3fus per)\n", elapsedTime, 1000000*elapsedTime/static_cast<F64>(numIterations));
#endif
delete testQueue;
printf("Test complete.\n");
printf("---------------------\n");
printf("---------------------\n");
}
| cpp |
fprime | data/projects/fprime/Os/test/ut/OsMutexBasicLockableTest.cpp | #include <gtest/gtest.h>
#include <Os/Mutex.hpp>
#include <Fw/Types/Assert.hpp>
#include <mutex>
// This is exclusively a compile-time check
void testMutexBasicLockableTest() {
Os::Mutex mux;
{
std::lock_guard<Os::Mutex> lock(mux);
}
ASSERT_TRUE(true); // if runs will pass
}
extern "C" {
void mutexBasicLockableTest();
}
void mutexBasicLockableTest() {
testMutexBasicLockableTest();
}
| cpp |
fprime | data/projects/fprime/Os/test/ut/OsValidateFileTest.cpp | #include <Os/ValidateFile.hpp>
#include "gtest/gtest.h"
#include <Os/FileSystem.hpp>
#include <Os/File.hpp>
#include <Utils/Hash/HashBuffer.hpp>
#include <Fw/Types/Assert.hpp>
#include <cstdio>
void testValidateFile(const char* fileName) {
Os::ValidateFile::Status validateStatus;
Os::FileSystem::Status fsStatus;
const char nonexistentFileName[] = "thisfiledoesnotexist";
const char hashFileName[] = "hashed.hashed";
const char hardtoaccessHashFileName[] = "thisdirdoesnotexist/hashed.hashed";
// Create a hash file:
printf("Creating hash for file %s in %s\n", fileName, hashFileName);
validateStatus = Os::ValidateFile::createValidation(fileName, hashFileName); //!< create a validation of the file 'filename' and store it in
if ( Os::ValidateFile::VALIDATION_OK != validateStatus ) {
printf("\tFailed to hash file %s into hash file %s.\n", fileName, hashFileName);
printf("\tReturn status: %d\n", validateStatus);
fflush(stdout);
EXPECT_TRUE(0);
return;
}
// Create a hash of a file that doesn't exist:
printf("Creating hash for file %s in %s\n", nonexistentFileName, hashFileName);
validateStatus = Os::ValidateFile::createValidation(nonexistentFileName, hashFileName); //!< create a validation of the file 'filename' and store it in
if ( Os::ValidateFile::FILE_DOESNT_EXIST != validateStatus ) {
printf("\tFile %s was found and hashed, but it shouldn't exist.\n", nonexistentFileName);
printf("\tReturn status: %d\n", validateStatus);
EXPECT_TRUE(0);
return;
}
// Create a hash of a file that doesn't exist:
printf("Creating hash for file %s in %s\n", fileName, hardtoaccessHashFileName);
validateStatus = Os::ValidateFile::createValidation(fileName, hardtoaccessHashFileName); //!< create a validation of the file 'filename' and store it in
if ( Os::ValidateFile::VALIDATION_FILE_DOESNT_EXIST != validateStatus ) {
printf("\tFile %s was found and hashed, but hash %s shouldn't exist.\n", fileName, hardtoaccessHashFileName);
printf("\tReturn status: %d\n", validateStatus);
EXPECT_TRUE(0);
return;
}
// Get file size:
printf("Checking file size of %s.\n", hashFileName);
FwSignedSizeType fileSize=0;
fsStatus = Os::FileSystem::getFileSize(hashFileName, fileSize);
if( Os::FileSystem::OP_OK != fsStatus ) {
printf("\tFailed to get file size of %s\n", hashFileName);
printf("\tReturn status: %d\n", fsStatus);
EXPECT_TRUE(0);
return;
}
Utils::HashBuffer buf;
EXPECT_TRUE(fileSize == buf.getBuffCapacity());
// Validate file:
printf("Validating file %s against hash file %s\n", fileName, hashFileName);
validateStatus = Os::ValidateFile::validate(fileName, hashFileName); //!< create a validation of the file 'filename' and store it in
if ( Os::ValidateFile::VALIDATION_OK != validateStatus ) {
printf("\tFailed to validate file %s against hash file %s.\n", fileName, hashFileName);
printf("\tReturn status: %d\n", validateStatus);
EXPECT_TRUE(0);
return;
}
// Validate bad file:
printf("Validating file %s against hash file %s\n", fileName, fileName);
validateStatus = Os::ValidateFile::validate(fileName, fileName); //!< create a validation of the file 'filename' and store it in
if ( Os::ValidateFile::VALIDATION_FAIL != validateStatus ) {
printf("\tSucceeded in validating file %s against hash file %s. But this should fail.\n", fileName, fileName);
printf("\tReturn status: %d\n", validateStatus);
EXPECT_TRUE(0);
return;
}
// Remove hash file:
printf("Removing hash file %s\n", hashFileName);
fsStatus = Os::FileSystem::removeFile(hashFileName);
if( Os::FileSystem::OP_OK != fsStatus ) {
printf("\tFailed to remove file (%s)\n", hashFileName);
printf("\tReturn status: %d\n", fsStatus);
EXPECT_TRUE(0);
return;
}
}
extern "C" {
void validateFileTest(const char* filename);
}
void validateFileTest(const char* filename) {
testValidateFile(filename);
}
| cpp |
fprime | data/projects/fprime/Os/test/ut/OsTaskTest.cpp | #include "gtest/gtest.h"
#include <Os/Task.hpp>
#include <cstdio>
extern "C" {
void startTestTask();
}
void someTask(void* ptr) {
bool* ran = static_cast<bool*>(ptr);
*ran = true;
}
void startTestTask() {
volatile bool taskRan = false;
Os::Task testTask;
Os::TaskString name("ATestTask");
Os::Task::TaskStatus stat = testTask.start(name,someTask,const_cast<bool*>(&taskRan));
ASSERT_EQ(stat, Os::Task::TASK_OK);
testTask.join(nullptr);
ASSERT_EQ(taskRan, true);
}
| cpp |
fprime | data/projects/fprime/Os/test/ut/file/SyntheticFileSystem.cpp | // ======================================================================
// \title Os/test/ut/file/SyntheticFileSystem.cpp
// \brief standard template library driven synthetic file system implementation
// ======================================================================
#include "Os/test/ut/file/SyntheticFileSystem.hpp"
#include "Fw/Types/Assert.hpp"
namespace Os {
namespace Test {
SyntheticFileSystem::OpenData SyntheticFileSystem::open(const CHAR* char_path, const Os::File::Mode open_mode, const File::OverwriteType overwrite) {
SyntheticFileSystem::OpenData return_value;
std::string path = char_path;
bool exists = (this->m_filesystem.count(path) > 0);
// Error case: read on file that does not exist
if ((not exists) && (Os::File::Mode::OPEN_READ == open_mode)) {
return_value.status = Os::File::Status::DOESNT_EXIST;
}
// Error case: create on existing file without overwrite
else if (exists and (not overwrite) && (open_mode == Os::File::Mode::OPEN_CREATE)) {
return_value.status = Os::File::Status::FILE_EXISTS;
}
// Case where file should be opened correctly
else {
const bool truncate = (Os::File::Mode::OPEN_CREATE == open_mode) && overwrite;
// Add new shadow file data when the file is new
if (not exists) {
this->m_filesystem[path] = std::make_shared<SyntheticFileData>();
}
return_value.file = this->m_filesystem[path];
return_value.status = Os::File::Status::OP_OK;
// Set file properties
if (truncate) {
return_value.file->m_data.clear();
}
return_value.file->m_pointer = 0;
return_value.file->m_mode = open_mode;
return_value.file->m_path = path;
// Checks on the shadow data to ensure consistency
FW_ASSERT(return_value.file->m_mode != Os::File::OPEN_NO_MODE);
FW_ASSERT(return_value.file->m_pointer == 0);
FW_ASSERT(return_value.file->m_path == path);
FW_ASSERT(not truncate || return_value.file->m_data.empty());
}
return return_value;
}
bool SyntheticFileSystem::exists(const CHAR* char_path) {
std::string path = char_path;
FW_ASSERT(this->m_filesystem.count(path) <= 1);
return this->m_filesystem.count(path) == 1;
}
void SyntheticFileSystem::remove(const CHAR* char_path) {
std::string path = char_path;
this->m_filesystem.erase(path);
}
std::unique_ptr<SyntheticFileSystem> SyntheticFile::s_file_system = std::unique_ptr<SyntheticFileSystem>(new SyntheticFileSystem());
void SyntheticFile::setFileSystem(std::unique_ptr<SyntheticFileSystem> new_file_system) {
s_file_system = std::move(new_file_system);
}
void SyntheticFile::remove(const CHAR* char_path) {
FW_ASSERT(s_file_system != nullptr);
s_file_system->remove(char_path);
}
File::Status SyntheticFile::open(const CHAR* char_path, const Os::File::Mode open_mode, const File::OverwriteType overwrite) {
SyntheticFileSystem::OpenData data = s_file_system->open(char_path, open_mode, overwrite);
if (data.status == Os::File::Status::OP_OK) {
this->m_data = data.file;
FW_ASSERT(this->m_data != nullptr);
}
return data.status;
}
void SyntheticFile::close() {
if (this->m_data != nullptr) {
this->m_data->m_mode = Os::File::Mode::OPEN_NO_MODE;
this->m_data->m_path.clear();
// Checks on the shadow data to ensure consistency
FW_ASSERT(this->m_data->m_mode == Os::File::Mode::OPEN_NO_MODE);
FW_ASSERT(this->m_data->m_path.empty());
}
}
Os::File::Status SyntheticFile::read(U8* buffer, FwSignedSizeType& size, WaitType wait) {
(void) wait;
FW_ASSERT(this->m_data != nullptr);
FW_ASSERT(buffer != nullptr);
FW_ASSERT(size >= 0);
FW_ASSERT(this->m_data->m_mode < Os::File::Mode::MAX_OPEN_MODE);
// Check that the file is open before attempting operation
if (Os::File::Mode::OPEN_NO_MODE == this->m_data->m_mode) {
size = 0;
return Os::File::Status::NOT_OPENED;
} else if (Os::File::Mode::OPEN_READ != this->m_data->m_mode) {
size = 0;
return Os::File::Status::INVALID_MODE;
}
std::vector<U8> output;
FwSignedSizeType original_pointer = this->m_data->m_pointer;
FwSignedSizeType original_size = this->m_data->m_data.size();
// Check expected read bytes
FwSignedSizeType i = 0;
for (i = 0; i < size; i++, this->m_data->m_pointer++) {
// End of file
if (this->m_data->m_pointer >= static_cast<FwSignedSizeType>(this->m_data->m_data.size())) {
break;
}
buffer[i] = this->m_data->m_data.at(this->m_data->m_pointer);
}
size = i;
// Checks on the shadow data to ensure consistency
FW_ASSERT(this->m_data->m_data.size() == static_cast<size_t>(original_size));
FW_ASSERT(this->m_data->m_pointer == ((original_pointer > original_size) ? original_pointer : FW_MIN(original_pointer + size, original_size)));
FW_ASSERT(size == ((original_pointer > original_size) ? 0 : FW_MIN(size, original_size - original_pointer)));
return Os::File::Status::OP_OK;
}
Os::File::Status SyntheticFile::write(const U8* buffer, FwSignedSizeType& size, WaitType wait) {
(void) wait;
FW_ASSERT(this->m_data != nullptr);
FW_ASSERT(buffer != nullptr);
FW_ASSERT(size >= 0);
FW_ASSERT(this->m_data->m_mode < Os::File::Mode::MAX_OPEN_MODE);
// Check that the file is open before attempting operation
if (Os::File::Mode::OPEN_NO_MODE == this->m_data->m_mode) {
size = 0;
return Os::File::Status::NOT_OPENED;
} else if (Os::File::Mode::OPEN_READ == this->m_data->m_mode) {
size = 0;
return Os::File::Status::INVALID_MODE;
}
FwSignedSizeType original_position = this->m_data->m_pointer;
FwSignedSizeType original_size = this->m_data->m_data.size();
const U8* write_data = reinterpret_cast<const U8*>(buffer);
// Appends seek to end before writing
if (Os::File::Mode::OPEN_APPEND == this->m_data->m_mode) {
this->m_data->m_pointer = this->m_data->m_data.size();
}
// First add in zeros to account for a pointer past the end of the file
const FwSignedSizeType zeros = static_cast<FwSignedSizeType>(this->m_data->m_pointer) - static_cast<FwSignedSizeType>(this->m_data->m_data.size());
for (FwSignedSizeType i = 0; i < zeros; i++) {
this->m_data->m_data.push_back(0);
}
// Interim checks to ensure zeroing performed correctly
FW_ASSERT(static_cast<size_t>(this->m_data->m_pointer) <= this->m_data->m_data.size());
FW_ASSERT(this->m_data->m_data.size() ==
static_cast<size_t>((Os::File::Mode::OPEN_APPEND == this->m_data->m_mode) ? original_size : FW_MAX(original_position, original_size)));
FwSignedSizeType pre_write_position = this->m_data->m_pointer;
FwSignedSizeType pre_write_size = this->m_data->m_data.size();
// Next write data
FwSignedSizeType i = 0;
for (i = 0; i < size; i++, this->m_data->m_pointer++) {
// Overwrite case
if (static_cast<size_t>(this->m_data->m_pointer) < this->m_data->m_data.size()) {
this->m_data->m_data.at(this->m_data->m_pointer) = write_data[i];
}
// Append case
else {
this->m_data->m_data.push_back(write_data[i]);
}
}
size = i;
// Checks on the shadow data to ensure consistency
FW_ASSERT(this->m_data->m_data.size() ==
static_cast<size_t>(FW_MAX(pre_write_position + size, pre_write_size)));
FW_ASSERT(this->m_data->m_pointer ==
((Os::File::Mode::OPEN_APPEND == this->m_data->m_mode) ? pre_write_size : pre_write_position) + size);
return Os::File::Status::OP_OK;
}
Os::File::Status SyntheticFile::seek(const FwSignedSizeType offset, const SeekType absolute) {
FW_ASSERT(this->m_data != nullptr);
Os::File::Status status = Os::File::Status::OP_OK;
// Cannot do a seek with a negative offset in absolute mode
FW_ASSERT(not absolute || offset >= 0);
FW_ASSERT(this->m_data->m_mode < Os::File::Mode::MAX_OPEN_MODE);
// Check that the file is open before attempting operation
if (Os::File::Mode::OPEN_NO_MODE == this->m_data->m_mode) {
status = Os::File::Status::NOT_OPENED;
} else {
FwSignedSizeType new_offset = (absolute) ? offset : (offset + this->m_data->m_pointer);
if (new_offset > 0) {
this->m_data->m_pointer = new_offset;
} else {
status = Os::File::Status::INVALID_ARGUMENT;
}
}
return status;
}
Os::File::Status SyntheticFile::preallocate(const FwSignedSizeType offset, const FwSignedSizeType length) {
FW_ASSERT(this->m_data != nullptr);
Os::File::Status status = Os::File::Status::OP_OK;
FW_ASSERT(offset >= 0);
FW_ASSERT(length >= 0);
FW_ASSERT(this->m_data->m_mode < Os::File::Mode::MAX_OPEN_MODE);
// Check that the file is open before attempting operation
if (Os::File::Mode::OPEN_NO_MODE == this->m_data->m_mode) {
status = Os::File::Status::NOT_OPENED;
} else if (Os::File::Mode::OPEN_READ == this->m_data->m_mode) {
status = Os::File::Status::INVALID_MODE;
} else {
const FwSignedSizeType original_size = this->m_data->m_data.size();
const FwSignedSizeType new_length = offset + length;
// Loop from existing size to new size adding zeros
for (FwSignedSizeType i = static_cast<FwSignedSizeType>(this->m_data->m_data.size()); i < new_length; i++) {
this->m_data->m_data.push_back(0);
}
FW_ASSERT(this->m_data->m_data.size() == static_cast<size_t>(FW_MAX(offset + length, original_size)));
}
return status;
}
Os::File::Status SyntheticFile::flush() {
FW_ASSERT(this->m_data != nullptr);
Os::File::Status status = Os::File::Status::OP_OK;
FW_ASSERT(this->m_data->m_mode < Os::File::Mode::MAX_OPEN_MODE);
// Check that the file is open before attempting operation
if (Os::File::Mode::OPEN_NO_MODE == this->m_data->m_mode) {
status = Os::File::Status::NOT_OPENED;
} else if (Os::File::Mode::OPEN_READ == this->m_data->m_mode) {
status = Os::File::Status::INVALID_MODE;
}
return status;
}
Os::File::Status SyntheticFile::position(FwSignedSizeType &position) {
position = this->m_data->m_pointer;
return Os::File::OP_OK;
}
Os::File::Status SyntheticFile::size(FwSignedSizeType &size) {
size = static_cast<FwSignedSizeType>(this->m_data->m_data.size());
return Os::File::OP_OK;
}
FileHandle* SyntheticFile::getHandle() {
return this->m_data.get();
}
bool SyntheticFile::exists(const CHAR* path) {
return s_file_system->exists(path);
}
} // namespace Test
} // namespace Os
| cpp |
fprime | data/projects/fprime/Os/test/ut/file/CommonTests.cpp | // ======================================================================
// \title Os/test/ut/file/CommonFileTests.cpp
// \brief common test implementations
// ======================================================================
#include "Os/test/ut/file/CommonTests.hpp"
#include <gtest/gtest.h>
#include "Os/File.hpp"
static const U32 RANDOM_BOUND = 1000;
Os::Test::File::Tester::Tester() {
// Wipe out the file system with a fresh copy
SyntheticFile::setFileSystem(std::unique_ptr<SyntheticFileSystem>(new SyntheticFileSystem()));
}
Functionality::Functionality() : tester(Os::Test::File::get_tester_implementation()) {}
void Functionality::SetUp() {
Os::Test::File::setUp(false);
}
void Functionality::TearDown() {
Os::Test::File::tearDown();
}
void FunctionalIO::SetUp() {
// Check that the tester supports functional tests
if (this->tester->functional()) {
this->Functionality::SetUp();
} else {
GTEST_SKIP() << "Tester does not support functional i/o testing";
}
}
// Ensure that open mode changes work reliably
TEST_F(Functionality, OpenWithCreation) {
Os::Test::File::Tester::OpenFileCreate rule(false);
rule.apply(*tester);
}
// Ensure that close mode changes work reliably
TEST_F(Functionality, Close) {
Os::Test::File::Tester::OpenFileCreate create_rule(false);
Os::Test::File::Tester::CloseFile close_rule;
create_rule.apply(*tester);
close_rule.apply(*tester);
}
// Ensure that the assignment operator works correctly
TEST_F(Functionality, AssignmentOperator) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::CopyAssignment copy_rule;
Os::Test::File::Tester::CloseFile close_rule;
open_rule.apply(*tester);
copy_rule.apply(*tester);
close_rule.apply(*tester);
}
// Ensure the copy constructor works correctly
TEST_F(Functionality, CopyConstructor) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::CopyConstruction copy_rule;
Os::Test::File::Tester::CloseFile close_rule;
open_rule.apply(*tester);
copy_rule.apply(*tester);
close_rule.apply(*tester);
}
// Ensure that open on existence works
TEST_F(FunctionalIO, OpenWithCreationExists) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::CloseFile close_rule;
open_rule.apply(*tester);
close_rule.apply(*tester);
open_rule.apply(*tester);
}
// Ensure that open on existence with overwrite works
TEST_F(Functionality, OpenWithCreationOverwrite) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::OpenFileCreateOverwrite open_overwrite(false);
Os::Test::File::Tester::CloseFile close_rule;
open_rule.apply(*tester);
close_rule.apply(*tester);
open_overwrite.apply(*tester);
}
// Ensure that open mode changes work reliably
TEST_F(Functionality, OpenInvalidModes) {
Os::Test::File::Tester::OpenFileCreate original_open(false);
Os::Test::File::Tester::OpenInvalidModes invalid_open;
original_open.apply(*tester);
invalid_open.apply(*tester);
}
// Ensure that Os::File properly refuses preallocate calls when not open
TEST_F(Functionality, PreallocateWithoutOpen) {
Os::Test::File::Tester::PreallocateWithoutOpen rule;
rule.apply(*tester);
}
// Ensure that Os::File properly refuses seek calls when not open
TEST_F(Functionality, SeekWithoutOpen) {
Os::Test::File::Tester::SeekWithoutOpen rule;
rule.apply(*tester);
}
// Ensure that Os::File properly refuses seek calls when not open
TEST_F(FunctionalIO, SeekInvalidSize) {
Os::Test::File::Tester::OpenFileCreate original_open(false);
Os::Test::File::Tester::SeekInvalidSize rule;
original_open.apply(*tester);
rule.apply(*tester);
}
// Ensure that Os::File properly refuses flush calls when not open and when reading
TEST_F(Functionality, FlushInvalidModes) {
Os::Test::File::Tester::FlushInvalidModes flush_rule;
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::CloseFile close_rule;
Os::Test::File::Tester::OpenForRead open_read;
// Test flush in closed state
flush_rule.apply(*tester);
// Used to create the test file an open in read-mode correctly
open_rule.apply(*tester);
close_rule.apply(*tester);
tester->assert_file_closed();
open_read.apply(*tester);
tester->assert_file_opened(tester->m_current_path);
// Check that a read-mode file cannot flush
flush_rule.apply(*tester);
}
// Ensure that Os::File properly refuses read calls when not open and when reading
TEST_F(Functionality, ReadInvalidModes) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::CloseFile close_rule;
Os::Test::File::Tester::OpenForWrite open_write;
Os::Test::File::Tester::ReadInvalidModes read_rule;
// Test read in closed state
read_rule.apply(*tester);
tester->assert_file_closed();
// Used to create the test file and ensure reads cannot happen in read-mode
open_rule.apply(*tester);
read_rule.apply(*tester);
close_rule.apply(*tester);
tester->assert_file_closed();
// Used to open (now existent) file in write-mode
open_write.apply(*tester);
tester->assert_file_opened(tester->m_current_path);
// Check that a read won't work on write-mode data
read_rule.apply(*tester);
}
// Ensure that Os::File properly refuses write calls when not open and when reading
TEST_F(Functionality, WriteInvalidModes) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::CloseFile close_rule;
Os::Test::File::Tester::OpenForRead open_read;
Os::Test::File::Tester::WriteInvalidModes write_rule;
// Test write in closed state
write_rule.apply(*tester);
tester->assert_file_closed();
// Used to create the test file in read-mode correctly
open_rule.apply(*tester);
close_rule.apply(*tester);
tester->assert_file_closed();
open_read.apply(*tester);
tester->assert_file_opened(tester->m_current_path);
// Check that a write won't work on write-mode data
write_rule.apply(*tester);
}
// Ensure a write followed by a read produces valid data
TEST_F(FunctionalIO, WriteReadBack) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::Write write_rule;
Os::Test::File::Tester::CloseFile close_rule;
Os::Test::File::Tester::OpenForRead open_read;
Os::Test::File::Tester::Read read_rule;
open_rule.apply(*tester);
write_rule.apply(*tester);
close_rule.apply(*tester);
open_read.apply(*tester);
read_rule.apply(*tester);
}
// Ensure a write followed by a read produces valid data
TEST_F(FunctionalIO, WriteReadSeek) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::Write write_rule;
Os::Test::File::Tester::CloseFile close_rule;
Os::Test::File::Tester::OpenForRead open_read;
Os::Test::File::Tester::Read read_rule;
Os::Test::File::Tester::Seek seek_rule;
open_rule.apply(*tester);
write_rule.apply(*tester);
close_rule.apply(*tester);
open_read.apply(*tester);
read_rule.apply(*tester);
seek_rule.apply(*tester);
}
// Ensure a write followed by a full crc produces valid results
TEST_F(FunctionalIO, WriteFullCrc) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::Write write_rule;
Os::Test::File::Tester::CloseFile close_rule;
Os::Test::File::Tester::OpenForRead open_read;
Os::Test::File::Tester::FullCrc crc_rule;
open_rule.apply(*tester);
write_rule.apply(*tester);
close_rule.apply(*tester);
open_read.apply(*tester);
crc_rule.apply(*tester);
}
// Ensure a write followed by a partial crc produces valid results
TEST_F(FunctionalIO, WritePartialCrc) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::Write write_rule;
Os::Test::File::Tester::CloseFile close_rule;
Os::Test::File::Tester::OpenForRead open_read;
Os::Test::File::Tester::IncrementalCrc crc_rule;
Os::Test::File::Tester::FinalizeCrc finalize_rule;
open_rule.apply(*tester);
write_rule.apply(*tester);
close_rule.apply(*tester);
open_read.apply(*tester);
crc_rule.apply(*tester);
finalize_rule.apply(*tester);
}
// Ensure a preallocate produces valid sizes
TEST_F(FunctionalIO, Flush) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::Write write_rule;
Os::Test::File::Tester::Flush flush_rule;
open_rule.apply(*tester);
write_rule.apply(*tester);
flush_rule.apply(*tester);
}
// Ensure a preallocate produces valid sizes
TEST_F(FunctionalIO, Preallocate) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::Preallocate preallocate_rule;
open_rule.apply(*tester);
preallocate_rule.apply(*tester);
}
// Randomized testing on the interfaces
TEST_F(Functionality, RandomizedInterfaceTesting) {
// Enumerate all rules and construct an instance of each
Os::Test::File::Tester::OpenFileCreate open_file_create_rule(true);
Os::Test::File::Tester::OpenFileCreateOverwrite open_file_create_overwrite_rule(true);
Os::Test::File::Tester::OpenForWrite open_for_write_rule(true);
Os::Test::File::Tester::CloseFile close_file_rule;
Os::Test::File::Tester::CopyConstruction copy_construction;
Os::Test::File::Tester::CopyAssignment copy_assignment;
Os::Test::File::Tester::OpenInvalidModes open_invalid_modes_rule;
Os::Test::File::Tester::PreallocateWithoutOpen preallocate_without_open_rule;
Os::Test::File::Tester::SeekWithoutOpen seek_without_open_rule;
Os::Test::File::Tester::FlushInvalidModes flush_invalid_modes_rule;
Os::Test::File::Tester::ReadInvalidModes read_invalid_modes_rule;
Os::Test::File::Tester::WriteInvalidModes write_invalid_modes_rule;
Os::Test::File::Tester::OpenIllegalPath open_illegal_path;
Os::Test::File::Tester::OpenIllegalMode open_illegal_mode;
Os::Test::File::Tester::PreallocateIllegalOffset preallocate_illegal_offset;
Os::Test::File::Tester::PreallocateIllegalLength preallocate_illegal_length;
Os::Test::File::Tester::SeekIllegal seek_illegal;
Os::Test::File::Tester::ReadIllegalBuffer read_illegal_buffer;
Os::Test::File::Tester::ReadIllegalSize read_illegal_size;
Os::Test::File::Tester::WriteIllegalBuffer write_illegal_buffer;
Os::Test::File::Tester::WriteIllegalSize write_illegal_size;
Os::Test::File::Tester::IncrementalCrcInvalidModes incremental_invalid_mode_rule;
Os::Test::File::Tester::FullCrcInvalidModes full_invalid_mode_rule;
// Place these rules into a list of rules
STest::Rule<Os::Test::File::Tester>* rules[] = {
&open_file_create_rule,
&open_file_create_overwrite_rule,
&open_for_write_rule,
&close_file_rule,
©_assignment,
©_construction,
&open_invalid_modes_rule,
&preallocate_without_open_rule,
&seek_without_open_rule,
&flush_invalid_modes_rule,
&read_invalid_modes_rule,
&write_invalid_modes_rule,
&open_illegal_path,
&open_illegal_mode,
&preallocate_illegal_offset,
&preallocate_illegal_length,
&seek_illegal,
&read_illegal_buffer,
&read_illegal_size,
&write_illegal_buffer,
&write_illegal_size,
&incremental_invalid_mode_rule,
&full_invalid_mode_rule
};
// Take the rules and place them into a random scenario
STest::RandomScenario<Os::Test::File::Tester> random(
"Random Rules",
rules,
FW_NUM_ARRAY_ELEMENTS(rules)
);
// Create a bounded scenario wrapping the random scenario
STest::BoundedScenario<Os::Test::File::Tester> bounded(
"Bounded Random Rules Scenario",
random,
RANDOM_BOUND/10
);
// Run!
const U32 numSteps = bounded.run(*tester);
printf("Ran %u steps.\n", numSteps);
}
// Ensure a write followed by a read produces valid data
TEST_F(FunctionalIO, RandomizedTesting) {
// Enumerate all rules and construct an instance of each
Os::Test::File::Tester::OpenFileCreate open_file_create_rule(true);
Os::Test::File::Tester::OpenFileCreateOverwrite open_file_create_overwrite_rule(true);
Os::Test::File::Tester::OpenForWrite open_for_write_rule(true);
Os::Test::File::Tester::OpenForRead open_for_read_rule(true);
Os::Test::File::Tester::CloseFile close_file_rule;
Os::Test::File::Tester::Read read_rule;
Os::Test::File::Tester::Write write_rule;
Os::Test::File::Tester::Seek seek_rule;
Os::Test::File::Tester::Preallocate preallocate_rule;
Os::Test::File::Tester::Flush flush_rule;
Os::Test::File::Tester::CopyConstruction copy_construction;
Os::Test::File::Tester::CopyAssignment copy_assignment;
Os::Test::File::Tester::IncrementalCrc incremental_crc_rule;
Os::Test::File::Tester::FinalizeCrc finalize_crc_rule;
Os::Test::File::Tester::FullCrc full_crc_rule;
Os::Test::File::Tester::OpenInvalidModes open_invalid_modes_rule;
Os::Test::File::Tester::PreallocateWithoutOpen preallocate_without_open_rule;
Os::Test::File::Tester::SeekWithoutOpen seek_without_open_rule;
Os::Test::File::Tester::SeekInvalidSize seek_invalid_size;
Os::Test::File::Tester::FlushInvalidModes flush_invalid_modes_rule;
Os::Test::File::Tester::ReadInvalidModes read_invalid_modes_rule;
Os::Test::File::Tester::WriteInvalidModes write_invalid_modes_rule;
Os::Test::File::Tester::IncrementalCrcInvalidModes incremental_invalid_mode_rule;
Os::Test::File::Tester::FullCrcInvalidModes full_invalid_mode_rule;
// Place these rules into a list of rules
STest::Rule<Os::Test::File::Tester>* rules[] = {
&open_file_create_rule,
&open_file_create_overwrite_rule,
&open_for_write_rule,
&open_for_read_rule,
&close_file_rule,
©_assignment,
©_construction,
&read_rule,
&write_rule,
&seek_rule,
&preallocate_rule,
&flush_rule,
&incremental_crc_rule,
&finalize_crc_rule,
&full_crc_rule,
&open_invalid_modes_rule,
&preallocate_without_open_rule,
&seek_without_open_rule,
&seek_invalid_size,
&flush_invalid_modes_rule,
&read_invalid_modes_rule,
&write_invalid_modes_rule,
&incremental_invalid_mode_rule,
&full_invalid_mode_rule
};
// Take the rules and place them into a random scenario
STest::RandomScenario<Os::Test::File::Tester> random(
"Random Rules",
rules,
FW_NUM_ARRAY_ELEMENTS(rules)
);
// Create a bounded scenario wrapping the random scenario
STest::BoundedScenario<Os::Test::File::Tester> bounded(
"Bounded Random Rules Scenario",
random,
RANDOM_BOUND
);
// Run!
const U32 numSteps = bounded.run(*tester);
printf("Ran %u steps.\n", numSteps);
}
// Ensure that Os::File properly refuses fullCrc when not in write mode
TEST_F(Functionality, FullCrcInvalidMode) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::FullCrcInvalidModes rule;
open_rule.apply(*tester);
rule.apply(*tester);
}
// Ensure that Os::File properly refuses incrementalCrc when not in write mode
TEST_F(Functionality, IncrementalCrcInvalidMode) {
Os::Test::File::Tester::OpenFileCreate open_rule(false);
Os::Test::File::Tester::IncrementalCrcInvalidModes rule;
open_rule.apply(*tester);
rule.apply(*tester);
}
// Ensure open prevents nullptr as path
TEST_F(InvalidArguments, OpenBadPath) {
Os::Test::File::Tester::OpenIllegalPath rule;
rule.apply(*tester);
}
// Ensure open prevents bad modes
TEST_F(InvalidArguments, OpenBadMode) {
Os::Test::File::Tester::OpenIllegalMode rule;
rule.apply(*tester);
}
// Ensure preallocate prevents bad offset
TEST_F(InvalidArguments, PreallocateBadOffset) {
Os::Test::File::Tester::PreallocateIllegalOffset rule;
rule.apply(*tester);
}
// Ensure preallocate prevents bad length
TEST_F(InvalidArguments, PreallocateBadLength) {
Os::Test::File::Tester::PreallocateIllegalLength rule;
rule.apply(*tester);
}
// Ensure preallocate prevents bad length
TEST_F(InvalidArguments, SeekAbsoluteWithNegativeLength) {
Os::Test::File::Tester::SeekIllegal rule;
rule.apply(*tester);
}
// Ensure read prevents bad buffer pointers
TEST_F(InvalidArguments, ReadInvalidBuffer) {
Os::Test::File::Tester::ReadIllegalBuffer rule;
rule.apply(*tester);
}
// Ensure read prevents bad sizes
TEST_F(InvalidArguments, ReadInvalidSize) {
Os::Test::File::Tester::ReadIllegalSize rule;
rule.apply(*tester);
}
// Ensure write prevents bad buffer pointers
TEST_F(InvalidArguments, WriteInvalidBuffer) {
Os::Test::File::Tester::WriteIllegalBuffer rule;
rule.apply(*tester);
}
// Ensure write prevents bad sizes
TEST_F(InvalidArguments, WriteInvalidSize) {
Os::Test::File::Tester::WriteIllegalSize rule;
rule.apply(*tester);
}
| cpp |
fprime | data/projects/fprime/Os/test/ut/file/CommonTests.hpp | // ======================================================================
// \title Os/test/ut/file/CommonFileTests.hpp
// \brief definitions used in common file testing
// ======================================================================
#include <Os/File.hpp>
#include <Os/test/ut/file/RulesHeaders.hpp>
#ifndef OS_TEST_UT_COMMON_FILE_TESTS_HPP
#define OS_TEST_UT_COMMON_FILE_TESTS_HPP
namespace Os {
namespace Test {
namespace File {
//! Set up function as defined by the unit test implementor
void setUp(bool requires_io //!< Does this test require functional io devices
);
//! Tear down function as defined by the unit test implementor
void tearDown();
} // namespace File
} // namespace Test
} // namespace Os
// Basic file tests
class Functionality : public ::testing::Test {
public:
//! Constructor
Functionality();
//! Setup function delegating to UT setUp function
void SetUp() override;
//! Setup function delegating to UT tearDown function
void TearDown() override;
//! Tester/state implementation
std::unique_ptr<Os::Test::File::Tester> tester;
};
//! Interface testing
class Interface : public Functionality {};
//! Category of tests to check for invalid argument assertions
class InvalidArguments : public Functionality {};
//! Category of tests dependent on functional io
class FunctionalIO : public Functionality {
//! Specialized setup method used to pass requirement for functional i/o
void SetUp() override;
};
#endif // OS_TEST_UT_COMMON_FILE_TESTS_HPP
| hpp |
fprime | data/projects/fprime/Os/test/ut/file/FileRules.cpp | // ======================================================================
// \title Os/test/ut/file/MyRules.cpp
// \brief rule implementations for common testing
// ======================================================================
#include "RulesHeaders.hpp"
#include "STest/Pick/Pick.hpp"
extern "C" {
#include <Utils/Hash/libcrc/lib_crc.h> // borrow CRC
}
// For testing, limit files to 32K
const FwSignedSizeType FILE_DATA_MAXIMUM = 32 * 1024;
Os::File::Status Os::Test::File::Tester::shadow_open(const std::string &path, Os::File::Mode open_mode, bool overwrite) {
Os::File::Status status = this->m_shadow.open(path.c_str(), open_mode, overwrite ? Os::File::OverwriteType::OVERWRITE : Os::File::OverwriteType::NO_OVERWRITE);
if (Os::File::Status::OP_OK == status) {
this->m_current_path = path;
this->m_mode = open_mode;
this->m_independent_crc = Os::File::INITIAL_CRC;
} else {
this->m_current_path.clear();
this->m_mode = Os::File::Mode::OPEN_NO_MODE;
}
return status;
}
void Os::Test::File::Tester::shadow_close() {
this->m_shadow.close();
this->m_current_path.clear();
this->m_mode = Os::File::Mode::OPEN_NO_MODE;
// Checks on the shadow data to ensure consistency
ASSERT_TRUE(this->m_current_path.empty());
}
std::vector<U8> Os::Test::File::Tester::shadow_read(FwSignedSizeType size) {
std::vector<U8> output;
output.resize(size);
Os::File::Status status = m_shadow.read(output.data(), size, Os::File::WaitType::WAIT);
output.resize(size);
EXPECT_EQ(status, Os::File::Status::OP_OK);
return output;
}
void Os::Test::File::Tester::shadow_write(const std::vector<U8>& write_data) {
FwSignedSizeType size = static_cast<FwSignedSizeType>(write_data.size());
FwSignedSizeType original_size = size;
Os::File::Status status = Os::File::OP_OK;
if (write_data.data() != nullptr) {
status = m_shadow.write(write_data.data(), size, Os::File::WaitType::WAIT);
}
ASSERT_EQ(status, Os::File::Status::OP_OK);
ASSERT_EQ(size, original_size);
}
void Os::Test::File::Tester::shadow_seek(const FwSignedSizeType offset, const bool absolute) {
Os::File::Status status = m_shadow.seek(offset, absolute ?Os::File::SeekType::ABSOLUTE : Os::File::SeekType::RELATIVE);
ASSERT_EQ(status, Os::File::Status::OP_OK);
}
void Os::Test::File::Tester::shadow_preallocate(const FwSignedSizeType offset, const FwSignedSizeType length) {
Os::File::Status status = m_shadow.preallocate(offset, length);
ASSERT_EQ(status, Os::File::Status::OP_OK);
}
void Os::Test::File::Tester::shadow_flush() {
Os::File::Status status = m_shadow.flush();
ASSERT_EQ(status, Os::File::Status::OP_OK);
}
void Os::Test::File::Tester::shadow_crc(U32& crc) {
crc = this->m_independent_crc;
SyntheticFileData& data = *reinterpret_cast<SyntheticFileData*>(this->m_shadow.getHandle());
// Calculate CRC on full file starting at m_pointer
for (FwSizeType i = data.m_pointer; i < data.m_data.size(); i++, this->m_shadow.seek(1, Os::File::SeekType::RELATIVE)) {
crc = update_crc_32(crc, static_cast<char>(data.m_data.at(i)));
}
// Update tracking variables
this->m_independent_crc = Os::File::INITIAL_CRC;
}
void Os::Test::File::Tester::shadow_partial_crc(FwSignedSizeType& size) {
SyntheticFileData data = *reinterpret_cast<SyntheticFileData*>(this->m_shadow.getHandle());
// Calculate CRC on full file starting at m_pointer
const FwSizeType bound = FW_MIN(static_cast<FwSizeType>(data.m_pointer) + size, data.m_data.size());
size = FW_MAX(0, static_cast<FwSignedSizeType>(bound - data.m_pointer));
for (FwSizeType i = data.m_pointer; i < bound; i++) {
this->m_independent_crc = update_crc_32(this->m_independent_crc, static_cast<char>(data.m_data.at(i)));
this->m_shadow.seek(1, Os::File::SeekType::RELATIVE);
}
}
void Os::Test::File::Tester::shadow_finalize(U32& crc) {
crc = this->m_independent_crc;
this->m_independent_crc = Os::File::INITIAL_CRC;
}
Os::Test::File::Tester::FileState Os::Test::File::Tester::current_file_state() {
Os::Test::File::Tester::FileState state;
// Invariant: mode must not be closed, or path must be nullptr
EXPECT_TRUE((Os::File::Mode::OPEN_NO_MODE != this->m_file.m_mode) || (nullptr == this->m_file.m_path));
// Read state when file is open
if (Os::File::Mode::OPEN_NO_MODE != this->m_file.m_mode) {
EXPECT_EQ(this->m_file.position(state.position), Os::File::Status::OP_OK);
EXPECT_EQ(this->m_file.size(state.size), Os::File::Status::OP_OK);
// Extra check to ensure size does not alter pointer
FwSignedSizeType new_position = -1;
EXPECT_EQ(this->m_file.position(new_position), Os::File::Status::OP_OK);
EXPECT_EQ(new_position, state.position);
}
return state;
}
void Os::Test::File::Tester::assert_valid_mode_status(Os::File::Status &status) const {
if (Os::File::Mode::OPEN_NO_MODE == this->m_mode) {
ASSERT_EQ(status, Os::File::Status::NOT_OPENED);
} else {
ASSERT_EQ(status, Os::File::Status::INVALID_MODE);
}
}
void Os::Test::File::Tester::assert_file_consistent() {
// Ensure file mode
ASSERT_EQ(this->m_mode, this->m_file.m_mode);
if (this->m_file.m_path == nullptr) {
ASSERT_EQ(this->m_current_path, std::string(""));
} else {
// Ensure the state path matches the file path
std::string path = std::string(this->m_file.m_path);
ASSERT_EQ(path, this->m_current_path);
// Check real file properties when able to do so
if (this->functional()) {
// File exists, check all properties
if (SyntheticFile::exists(this->m_current_path.c_str())) {
// Ensure the file pointer is consistent
FwSignedSizeType current_position = 0;
FwSignedSizeType shadow_position = 0;
ASSERT_EQ(this->m_file.position(current_position), Os::File::Status::OP_OK);
ASSERT_EQ(this->m_shadow.position(shadow_position), Os::File::Status::OP_OK);
ASSERT_EQ(current_position, shadow_position);
// Ensure the file size is consistent
FwSignedSizeType current_size = 0;
FwSignedSizeType shadow_size = 0;
ASSERT_EQ(this->m_file.size(current_size), Os::File::Status::OP_OK);
ASSERT_EQ(this->m_shadow.size(shadow_size), Os::File::Status::OP_OK);
ASSERT_EQ(current_size, shadow_size);
}
// Does not exist
else {
ASSERT_FALSE(this->exists(this->m_current_path));
}
}
}
}
void Os::Test::File::Tester::assert_file_opened(const std::string &path, Os::File::Mode newly_opened_mode, bool overwrite) {
// Assert the that the file is opened in some mode
ASSERT_NE(this->m_file.m_mode, Os::File::Mode::OPEN_NO_MODE);
ASSERT_TRUE(this->m_file.isOpen()) << "`isOpen()` failed to indicate file is open";
ASSERT_EQ(this->m_file.m_mode, this->m_mode);
// When the open mode has been specified assert that is in an exact state
if (not path.empty() && Os::File::Mode::OPEN_NO_MODE != newly_opened_mode) {
// Assert file pointer always at beginning when functional
if (functional() ) {
FwSignedSizeType file_position = -1;
ASSERT_EQ(this->m_file.position(file_position), Os::File::Status::OP_OK);
ASSERT_EQ(file_position, 0);
}
ASSERT_EQ(std::string(this->m_file.m_path), path);
ASSERT_EQ(this->m_file.m_mode, newly_opened_mode) << "File is in unexpected mode";
// Check truncations
const bool truncate = (Os::File::Mode::OPEN_CREATE == newly_opened_mode) && overwrite;
if (truncate) {
if (this->functional()) {
FwSignedSizeType file_size = -1;
ASSERT_EQ(this->m_file.size(file_size), Os::File::Status::OP_OK);
ASSERT_EQ(file_size, 0);
}
}
}
}
void Os::Test::File::Tester::assert_file_closed() {
ASSERT_EQ(this->m_file.m_mode, Os::File::Mode::OPEN_NO_MODE) << "File is in unexpected mode";
ASSERT_FALSE(this->m_file.isOpen()) << "`isOpen()` failed to indicate file is open";
}
void Os::Test::File::Tester::assert_file_read(const std::vector<U8>& state_data, const unsigned char *read_data, FwSignedSizeType size_read) {
// Functional tests
if (functional()) {
ASSERT_EQ(size_read, state_data.size());
ASSERT_EQ(std::vector<U8>(read_data, read_data + size_read), state_data);
FwSignedSizeType position = -1;
FwSignedSizeType shadow_position = -1;
ASSERT_EQ(this->m_file.position(position), Os::File::Status::OP_OK);
ASSERT_EQ(this->m_shadow.position(shadow_position), Os::File::Status::OP_OK);
ASSERT_EQ(position, shadow_position);
}
}
void Os::Test::File::Tester::assert_file_write(const std::vector<U8>& write_data, FwSignedSizeType size_written) {
ASSERT_EQ(size_written, write_data.size());
FwSignedSizeType file_size = 0;
FwSignedSizeType shadow_size = 0;
ASSERT_EQ(this->m_file.size(file_size), Os::File::Status::OP_OK);
ASSERT_EQ(this->m_shadow.size(shadow_size), Os::File::Status::OP_OK);
ASSERT_EQ(file_size, shadow_size);
FwSignedSizeType file_position = -1;
FwSignedSizeType shadow_position = -1;
ASSERT_EQ(this->m_file.position(file_position), Os::File::Status::OP_OK);
ASSERT_EQ(this->m_shadow.position(shadow_position), Os::File::Status::OP_OK);
ASSERT_EQ(file_position, shadow_position);
}
void Os::Test::File::Tester::assert_file_seek(const FwSignedSizeType original_position, const FwSignedSizeType seek_desired, const bool absolute) {
FwSignedSizeType new_position = 0;
FwSignedSizeType shadow_position = 0;
ASSERT_EQ(this->m_file.position(new_position), Os::File::Status::OP_OK);
ASSERT_EQ(this->m_shadow.position(shadow_position), Os::File::Status::OP_OK);
const FwSignedSizeType expected_offset = (absolute) ? seek_desired : (original_position + seek_desired);
if (expected_offset > 0) {
ASSERT_EQ(new_position, expected_offset);
} else {
ASSERT_EQ(new_position, original_position);
}
ASSERT_EQ(new_position, shadow_position);
}
// ------------------------------------------------------------------------------------------------------
// OpenFile: base rule for all open rules
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::OpenBaseRule::OpenBaseRule(const char *rule_name,
Os::File::Mode mode,
const bool overwrite,
const bool randomize_filename)
: STest::Rule<Os::Test::File::Tester>(rule_name), m_mode(mode),
m_overwrite(overwrite ? Os::File::OverwriteType::OVERWRITE : Os::File::OverwriteType::NO_OVERWRITE),
m_random(randomize_filename) {}
bool Os::Test::File::Tester::OpenBaseRule::precondition(const Os::Test::File::Tester &state //!< The test state
) {
return state.m_mode == Os::File::Mode::OPEN_NO_MODE;
}
void Os::Test::File::Tester::OpenBaseRule::action(Os::Test::File::Tester &state //!< The test state
) {
// Initial variables used for this test
std::shared_ptr<const std::string> filename = state.get_filename(this->m_random);
// Ensure initial and shadow states synchronized
state.assert_file_consistent();
state.assert_file_closed();
// Perform action and shadow action asserting the results are the same
Os::File::Status status = state.m_file.open(filename->c_str(), m_mode, this->m_overwrite);
ASSERT_EQ(status, state.shadow_open(*filename, m_mode, this->m_overwrite));
// Extra check to ensure file is consistently open
if (Os::File::Status::OP_OK == status) {
state.assert_file_opened(*filename, m_mode);
FileState file_state = state.current_file_state();
ASSERT_EQ(file_state.position, 0); // Open always zeros the position
}
// Assert the file state remains consistent.
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: OpenFileCreate
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::OpenFileCreate::OpenFileCreate(const bool randomize_filename)
: Os::Test::File::Tester::OpenBaseRule("OpenFileCreate", Os::File::Mode::OPEN_CREATE, false,
randomize_filename) {}
// ------------------------------------------------------------------------------------------------------
// Rule: OpenFileCreateOverwrite
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::OpenFileCreateOverwrite::OpenFileCreateOverwrite(const bool randomize_filename)
: Os::Test::File::Tester::OpenBaseRule("OpenFileCreate", Os::File::Mode::OPEN_CREATE, true,
randomize_filename) {}
// ------------------------------------------------------------------------------------------------------
// Rule: OpenForWrite
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::OpenForWrite::OpenForWrite(const bool randomize_filename)
: Os::Test::File::Tester::OpenBaseRule("OpenForWrite",
// Randomized write mode
static_cast<Os::File::Mode>(STest::Pick::lowerUpper(
Os::File::Mode::OPEN_WRITE,
Os::File::Mode::OPEN_APPEND)),
// Randomized overwrite
static_cast<bool>(STest::Pick::lowerUpper(0, 1)),
randomize_filename) {
// Ensures that a random write mode will work correctly
static_assert((Os::File::Mode::OPEN_SYNC_WRITE - 1) == Os::File::Mode::OPEN_WRITE, "Write modes not contiguous");
static_assert((Os::File::Mode::OPEN_APPEND - 1) == Os::File::Mode::OPEN_SYNC_WRITE,
"Write modes not contiguous");
}
// ------------------------------------------------------------------------------------------------------
// Rule: OpenForRead
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::OpenForRead::OpenForRead(const bool randomize_filename)
: Os::Test::File::Tester::OpenBaseRule("OpenForRead", Os::File::Mode::OPEN_READ,
// Randomized overwrite
static_cast<bool>(STest::Pick::lowerUpper(0, 1)),
randomize_filename) {}
// ------------------------------------------------------------------------------------------------------
// Rule: CloseFile
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::CloseFile::CloseFile() : STest::Rule<Os::Test::File::Tester>("CloseFile") {}
bool Os::Test::File::Tester::CloseFile::precondition(const Os::Test::File::Tester &state //!< The test state
) {
return Os::File::Mode::OPEN_NO_MODE != state.m_mode;
}
void Os::Test::File::Tester::CloseFile::action(Os::Test::File::Tester &state //!< The test state
) {
// Make sure test state and file state synchronized
state.assert_file_consistent();
state.assert_file_opened(state.m_current_path);
// Close file and shadow state
state.m_file.close();
state.shadow_close();
// Assert test state and file state synchronized
state.assert_file_closed();
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: Read
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::Read::Read() :
STest::Rule<Os::Test::File::Tester>("Read") {
}
bool Os::Test::File::Tester::Read::precondition(
const Os::Test::File::Tester &state //!< The test state
) {
return Os::File::Mode::OPEN_READ == state.m_mode;
}
void Os::Test::File::Tester::Read::action(
Os::Test::File::Tester &state //!< The test state
) {
U8 buffer[FILE_DATA_MAXIMUM];
state.assert_file_consistent();
FileState original_file_state = state.current_file_state();
FwSignedSizeType size_desired = static_cast<FwSignedSizeType>(STest::Pick::lowerUpper(0, FILE_DATA_MAXIMUM));
FwSignedSizeType size_read = size_desired;
bool wait = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
Os::File::Status status = state.m_file.read(buffer, size_read, wait ? Os::File::WaitType::WAIT : Os::File::WaitType::NO_WAIT);
ASSERT_EQ(Os::File::Status::OP_OK, status);
std::vector<U8> read_data = state.shadow_read(size_desired);
state.assert_file_read(read_data, buffer, size_read);
FileState final_file_state = state.current_file_state();
// File size should not change during read
ASSERT_EQ(final_file_state.size, original_file_state.size);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: Write
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::Write::Write() :
STest::Rule<Os::Test::File::Tester>("Write") {
}
bool Os::Test::File::Tester::Write::precondition(
const Os::Test::File::Tester &state //!< The test state
) {
return Os::File::Mode::OPEN_CREATE <= state.m_mode;
}
void Os::Test::File::Tester::Write::action(
Os::Test::File::Tester &state //!< The test state
) {
U8 buffer[FILE_DATA_MAXIMUM];
state.assert_file_consistent();
FwSignedSizeType size_desired = static_cast<FwSignedSizeType>(STest::Pick::lowerUpper(0, FILE_DATA_MAXIMUM));
FwSignedSizeType size_written = size_desired;
bool wait = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
for (FwSignedSizeType i = 0; i < size_desired; i++) {
buffer[i] = static_cast<U8>(STest::Pick::lowerUpper(0, std::numeric_limits<U8>::max()));
}
std::vector<U8> write_data(buffer, buffer + size_desired);
Os::File::Status status = state.m_file.write(buffer, size_written, wait ? Os::File::WaitType::WAIT : Os::File::WaitType::NO_WAIT);
ASSERT_EQ(Os::File::Status::OP_OK, status);
ASSERT_EQ(size_written, size_desired);
state.shadow_write(write_data);
state.assert_file_write(write_data, size_written);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: Read
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::Seek::Seek() :
STest::Rule<Os::Test::File::Tester>("Seek") {
}
bool Os::Test::File::Tester::Seek::precondition(
const Os::Test::File::Tester &state //!< The test state
) {
return Os::File::Mode::OPEN_NO_MODE < state.m_mode;
}
void Os::Test::File::Tester::Seek::action(
Os::Test::File::Tester &state //!< The test state
) {
FwSignedSizeType seek_offset = 0;
state.assert_file_consistent();
FileState original_file_state = state.current_file_state();
// Choose some random values
bool absolute = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
if (absolute) {
seek_offset = STest::Pick::lowerUpper(0, FILE_DATA_MAXIMUM);
} else {
seek_offset = STest::Pick::lowerUpper(0, original_file_state.position + FILE_DATA_MAXIMUM) - original_file_state.position;
}
Os::File::Status status = state.m_file.seek(seek_offset, absolute ? Os::File::SeekType::ABSOLUTE : Os::File::SeekType::RELATIVE);
ASSERT_EQ(status, Os::File::Status::OP_OK);
state.shadow_seek(seek_offset, absolute);
state.assert_file_seek(original_file_state.position, seek_offset, absolute);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: Preallocate
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::Preallocate::Preallocate() :
STest::Rule<Os::Test::File::Tester>("Preallocate") {
}
bool Os::Test::File::Tester::Preallocate::precondition(
const Os::Test::File::Tester &state //!< The test state
) {
return Os::File::Mode::OPEN_CREATE <= state.m_mode;
}
void Os::Test::File::Tester::Preallocate::action(
Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
FileState original_file_state = state.current_file_state();
FwSignedSizeType offset = static_cast<FwSignedSizeType>(STest::Pick::lowerUpper(0, FILE_DATA_MAXIMUM));
FwSignedSizeType length = static_cast<FwSignedSizeType>(STest::Pick::lowerUpper(0, FILE_DATA_MAXIMUM));
Os::File::Status status = state.m_file.preallocate(offset, length);
ASSERT_EQ(Os::File::Status::OP_OK, status);
state.shadow_preallocate(offset, length);
FileState final_file_state = state.current_file_state();
ASSERT_EQ(final_file_state.size, FW_MAX(original_file_state.size, offset + length));
ASSERT_EQ(final_file_state.position, original_file_state.position);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: Flush
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::Flush::Flush() :
STest::Rule<Os::Test::File::Tester>("Flush") {
}
bool Os::Test::File::Tester::Flush::precondition(
const Os::Test::File::Tester &state //!< The test state
) {
return Os::File::Mode::OPEN_CREATE <= state.m_mode;
}
void Os::Test::File::Tester::Flush::action(
Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
FileState original_file_state = state.current_file_state();
Os::File::Status status = state.m_file.flush();
ASSERT_EQ(status, Os::File::Status::OP_OK);
state.shadow_flush();
// Ensure no change in size or pointer
FileState final_file_state = state.current_file_state();
ASSERT_EQ(final_file_state.size, original_file_state.size);
ASSERT_EQ(final_file_state.position, original_file_state.position);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: OpenInvalidModes
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::OpenInvalidModes::OpenInvalidModes()
: STest::Rule<Os::Test::File::Tester>("OpenInvalidModes") {}
bool Os::Test::File::Tester::OpenInvalidModes::precondition(const Os::Test::File::Tester &state //!< The test state
) {
return Os::File::Mode::OPEN_NO_MODE != state.m_mode;
}
void Os::Test::File::Tester::OpenInvalidModes::action(Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
FileState original_file_state = state.current_file_state();
// Check initial file state
state.assert_file_opened(state.m_current_path);
std::shared_ptr<const std::string> filename = state.get_filename(true);
Os::File::Status status = state.m_file.open(filename->c_str(), Os::File::Mode::OPEN_CREATE);
state.assert_valid_mode_status(status);
state.assert_file_opened(state.m_current_path); // Original file remains open
// Ensure no change in size or pointer of original file
FileState final_file_state = state.current_file_state();
ASSERT_EQ(final_file_state.size, original_file_state.size);
ASSERT_EQ(final_file_state.position, original_file_state.position);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: PreallocateWithoutOpen
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::PreallocateWithoutOpen::PreallocateWithoutOpen()
: STest::Rule<Os::Test::File::Tester>("PreallocateWithoutOpen") {}
bool Os::Test::File::Tester::PreallocateWithoutOpen::precondition(
const Os::Test::File::Tester &state //!< The test state
) {
return Os::File::Mode::OPEN_NO_MODE == state.m_mode;
}
void Os::Test::File::Tester::PreallocateWithoutOpen::action(Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
// Check initial file state
state.assert_file_closed();
// Open file of given filename
FwSignedSizeType random_offset = STest::Pick::lowerUpper(0, std::numeric_limits<U32>::max());
FwSignedSizeType random_size = STest::Pick::lowerUpper(0, std::numeric_limits<U32>::max());
Os::File::Status status = state.m_file.preallocate(random_offset, random_size);
state.assert_valid_mode_status(status);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: SeekWithoutOpen
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::SeekWithoutOpen::SeekWithoutOpen() : STest::Rule<Os::Test::File::Tester>("SeekWithoutOpen") {}
bool Os::Test::File::Tester::SeekWithoutOpen::precondition(const Os::Test::File::Tester &state //!< The test state
) {
return Os::File::Mode::OPEN_NO_MODE == state.m_mode;
}
void Os::Test::File::Tester::SeekWithoutOpen::action(Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
// Check initial file state
state.assert_file_closed();
// Open file of given filename
FwSignedSizeType random_offset = STest::Pick::lowerUpper(0, std::numeric_limits<U32>::max());
bool random_absolute = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
Os::File::Status status = state.m_file.seek(random_offset, random_absolute ? Os::File::SeekType::ABSOLUTE : Os::File::SeekType::RELATIVE);
state.assert_valid_mode_status(status);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: SeekInvalidSize
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::SeekInvalidSize::SeekInvalidSize() : STest::Rule<Os::Test::File::Tester>("SeekInvalidSize") {}
bool Os::Test::File::Tester::SeekInvalidSize::precondition(const Os::Test::File::Tester &state //!< The test state
) {
return Os::File::Mode::OPEN_NO_MODE < state.m_mode;;
}
void Os::Test::File::Tester::SeekInvalidSize::action(Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
FileState original_file_state = state.current_file_state();
// Open file of given filename
FwSignedSizeType random_offset = STest::Pick::lowerUpper(original_file_state.position + 1, std::numeric_limits<U32>::max());
ASSERT_GT(random_offset, original_file_state.position);
Os::File::Status status = state.m_file.seek(-1 * random_offset, Os::File::SeekType::RELATIVE);
ASSERT_EQ(Os::File::Status::INVALID_ARGUMENT, status);
// Ensure no change in size or pointer
FileState final_file_state = state.current_file_state();
ASSERT_EQ(final_file_state.size, original_file_state.size);
ASSERT_EQ(final_file_state.position, original_file_state.position);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: FlushInvalidModes
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::FlushInvalidModes::FlushInvalidModes()
: STest::Rule<Os::Test::File::Tester>("FlushInvalidModes") {}
bool Os::Test::File::Tester::FlushInvalidModes::precondition(const Os::Test::File::Tester &state //!< The test state
) {
return Os::File::Mode::OPEN_NO_MODE == state.m_mode || Os::File::Mode::OPEN_READ == state.m_mode;
}
void Os::Test::File::Tester::FlushInvalidModes::action(Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
FileState original_file_state = state.current_file_state();
ASSERT_TRUE(Os::File::Mode::OPEN_NO_MODE == state.m_file.m_mode || Os::File::Mode::OPEN_READ == state.m_file.m_mode);
Os::File::Status status = state.m_file.flush();
state.assert_valid_mode_status(status);
// Ensure no change in size or pointer
FileState final_file_state = state.current_file_state();
ASSERT_EQ(final_file_state.size, original_file_state.size);
ASSERT_EQ(final_file_state.position, original_file_state.position);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: ReadInvalidModes
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::ReadInvalidModes::ReadInvalidModes()
: STest::Rule<Os::Test::File::Tester>("ReadInvalidModes") {}
bool Os::Test::File::Tester::ReadInvalidModes::precondition(const Os::Test::File::Tester &state //!< The test state
) {
return Os::File::Mode::OPEN_READ != state.m_mode;
}
void Os::Test::File::Tester::ReadInvalidModes::action(Os::Test::File::Tester &state //!< The test state
) {
U8 buffer[10];
FwSignedSizeType size = sizeof buffer;
state.assert_file_consistent();
FileState original_file_state = state.current_file_state();
ASSERT_NE(Os::File::Mode::OPEN_READ, state.m_file.m_mode);
bool wait = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
Os::File::Status status = state.m_file.read(buffer, size, wait ? Os::File::WaitType::WAIT : Os::File::WaitType::NO_WAIT);
state.assert_valid_mode_status(status);
// Ensure no change in size or pointer
FileState final_file_state = state.current_file_state();
ASSERT_EQ(final_file_state.size, original_file_state.size);
ASSERT_EQ(final_file_state.position, original_file_state.position);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: WriteInvalidModes
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::WriteInvalidModes::WriteInvalidModes()
: STest::Rule<Os::Test::File::Tester>("WriteInvalidModes") {}
bool Os::Test::File::Tester::WriteInvalidModes::precondition(const Os::Test::File::Tester &state //!< The test state
) {
return Os::File::Mode::OPEN_NO_MODE == state.m_mode || Os::File::Mode::OPEN_READ == state.m_mode;
}
void Os::Test::File::Tester::WriteInvalidModes::action(Os::Test::File::Tester &state //!< The test state
) {
U8 buffer[10];
FwSignedSizeType size = sizeof buffer;
state.assert_file_consistent();
FileState original_file_state = state.current_file_state();
ASSERT_TRUE(Os::File::Mode::OPEN_NO_MODE == state.m_file.m_mode || Os::File::Mode::OPEN_READ == state.m_file.m_mode);
bool wait = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
Os::File::Status status = state.m_file.write(buffer, size, wait ? Os::File::WaitType::WAIT : Os::File::WaitType::NO_WAIT);
state.assert_valid_mode_status(status);
// Ensure no change in size or pointer
FileState final_file_state = state.current_file_state();
ASSERT_EQ(final_file_state.size, original_file_state.size);
ASSERT_EQ(final_file_state.position, original_file_state.position);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Base Rule: AssertRule
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::AssertRule::AssertRule(const char *name) : STest::Rule<Os::Test::File::Tester>(name) {}
bool Os::Test::File::Tester::AssertRule::precondition(const Os::Test::File::Tester &state //!< The test state
) {
return true;
}
// ------------------------------------------------------------------------------------------------------
// Rule: OpenIllegalPath
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::OpenIllegalPath::OpenIllegalPath() : Os::Test::File::Tester::AssertRule("OpenIllegalPath") {}
void Os::Test::File::Tester::OpenIllegalPath::action(Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
Os::File::Mode random_mode =
static_cast<Os::File::Mode>(STest::Pick::lowerUpper(Os::File::Mode::OPEN_READ,
Os::File::Mode::OPEN_APPEND));
bool overwrite = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
ASSERT_DEATH_IF_SUPPORTED(
state.m_file.open(nullptr, random_mode,
overwrite ? Os::File::OverwriteType::OVERWRITE : Os::File::OverwriteType::NO_OVERWRITE),
ASSERT_IN_FILE_CPP);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: OpenIllegalMode
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::OpenIllegalMode::OpenIllegalMode() : Os::Test::File::Tester::AssertRule("OpenIllegalMode") {}
void Os::Test::File::Tester::OpenIllegalMode::action(Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
std::shared_ptr<const std::string> random_filename = state.get_filename(true);
U32 mode = STest::Pick::lowerUpper(0, 1);
bool overwrite = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
ASSERT_DEATH_IF_SUPPORTED(
state.m_file.open(random_filename->c_str(),
(mode == 0) ? Os::File::Mode::MAX_OPEN_MODE : Os::File::Mode::OPEN_NO_MODE,
overwrite ? Os::File::OverwriteType::OVERWRITE : Os::File::OverwriteType::NO_OVERWRITE),
Os::Test::File::Tester::ASSERT_IN_FILE_CPP);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: PreallocateIllegalOffset
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::PreallocateIllegalOffset::PreallocateIllegalOffset()
: Os::Test::File::Tester::AssertRule("PreallocateIllegalOffset") {}
void Os::Test::File::Tester::PreallocateIllegalOffset::action(Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
FwSignedSizeType length = static_cast<FwSignedSizeType>(STest::Pick::any());
FwSignedSizeType invalid_offset =
-1 * static_cast<FwSignedSizeType>(STest::Pick::lowerUpper(0, std::numeric_limits<U32>::max()));
ASSERT_DEATH_IF_SUPPORTED(state.m_file.preallocate(invalid_offset, length),
Os::Test::File::Tester::ASSERT_IN_FILE_CPP) << "With offset: " << invalid_offset;
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: PreallocateIllegalLength
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::PreallocateIllegalLength::PreallocateIllegalLength()
: Os::Test::File::Tester::AssertRule("PreallocateIllegalLength") {}
void Os::Test::File::Tester::PreallocateIllegalLength::action(Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
FwSignedSizeType offset = static_cast<FwSignedSizeType>(STest::Pick::any());
FwSignedSizeType invalid_length =
-1 * static_cast<FwSignedSizeType>(STest::Pick::lowerUpper(0, std::numeric_limits<U32>::max()));
ASSERT_DEATH_IF_SUPPORTED(state.m_file.preallocate(offset, invalid_length),
Os::Test::File::Tester::ASSERT_IN_FILE_CPP);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: SeekIllegal
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::SeekIllegal::SeekIllegal() : Os::Test::File::Tester::AssertRule("SeekIllegal") {}
void Os::Test::File::Tester::SeekIllegal::action(Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
ASSERT_DEATH_IF_SUPPORTED(state.m_file.seek(-1, Os::File::SeekType::ABSOLUTE), Os::Test::File::Tester::ASSERT_IN_FILE_CPP);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: ReadIllegalBuffer
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::ReadIllegalBuffer::ReadIllegalBuffer()
: Os::Test::File::Tester::AssertRule("ReadIllegalBuffer") {}
void Os::Test::File::Tester::ReadIllegalBuffer::action(Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
FwSignedSizeType size = static_cast<FwSignedSizeType>(STest::Pick::any());
bool random_wait = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
ASSERT_DEATH_IF_SUPPORTED(
state.m_file.read(nullptr, size, random_wait ? Os::File::WaitType::WAIT : Os::File::WaitType::NO_WAIT),
Os::Test::File::Tester::ASSERT_IN_FILE_CPP);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: ReadIllegalSize
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::ReadIllegalSize::ReadIllegalSize() : Os::Test::File::Tester::AssertRule("ReadIllegalSize") {}
void Os::Test::File::Tester::ReadIllegalSize::action(Os::Test::File::Tester &state //!< The test state
) {
U8 buffer[10] = {};
state.assert_file_consistent();
FwSignedSizeType invalid_size = -1 * static_cast<FwSignedSizeType>(STest::Pick::lowerUpper(0, std::numeric_limits<U32>::max()));
bool random_wait = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
ASSERT_DEATH_IF_SUPPORTED(
state.m_file.read(buffer, invalid_size,
random_wait ? Os::File::WaitType::WAIT : Os::File::WaitType::NO_WAIT),
Os::Test::File::Tester::ASSERT_IN_FILE_CPP);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: WriteIllegalBuffer
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::WriteIllegalBuffer::WriteIllegalBuffer()
: Os::Test::File::Tester::AssertRule("WriteIllegalBuffer") {}
void Os::Test::File::Tester::WriteIllegalBuffer::action(Os::Test::File::Tester &state //!< The test state
) {
state.assert_file_consistent();
FwSignedSizeType size = static_cast<FwSignedSizeType>(STest::Pick::any());
bool random_wait = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
ASSERT_DEATH_IF_SUPPORTED(
state.m_file.write(nullptr, size, random_wait ? Os::File::WaitType::WAIT : Os::File::WaitType::NO_WAIT),
Os::Test::File::Tester::ASSERT_IN_FILE_CPP);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: WriteIllegalSize
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::WriteIllegalSize::WriteIllegalSize() : Os::Test::File::Tester::AssertRule("WriteIllegalSize") {}
void Os::Test::File::Tester::WriteIllegalSize::action(Os::Test::File::Tester &state //!< The test state
) {
U8 buffer[10] = {};
state.assert_file_consistent();
FwSignedSizeType invalid_size = -1 * static_cast<FwSignedSizeType>(STest::Pick::lowerUpper(0, std::numeric_limits<U32>::max()));
bool random_wait = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
ASSERT_DEATH_IF_SUPPORTED(
state.m_file.read(buffer, invalid_size, random_wait ? Os::File::WaitType::WAIT : Os::File::WaitType::NO_WAIT),
Os::Test::File::Tester::ASSERT_IN_FILE_CPP);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: CopyAssignment
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::CopyAssignment::CopyAssignment() :
STest::Rule<Os::Test::File::Tester>("CopyAssignment") {}
bool Os::Test::File::Tester::CopyAssignment::precondition(const Os::Test::File::Tester& state //!< The test state
) {
return true;
}
void Os::Test::File::Tester::CopyAssignment::action(Os::Test::File::Tester& state //!< The test state
) {
state.assert_file_consistent();
Os::File temp = state.m_file;
state.assert_file_consistent(); // Prevents optimization
state.m_file = temp;
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: CopyConstruction
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::CopyConstruction::CopyConstruction() :
STest::Rule<Os::Test::File::Tester>("CopyConstruction") {}
bool Os::Test::File::Tester::CopyConstruction::precondition(const Os::Test::File::Tester& state //!< The test state
) {
return true;
}
void Os::Test::File::Tester::CopyConstruction::action(Os::Test::File::Tester& state //!< The test state
) {
state.assert_file_consistent();
Os::File temp(state.m_file);
state.assert_file_consistent(); // Interim check to ensure original file did not change
(void) new(&state.m_file)Os::File(temp); // Copy-construct overtop of the original file
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: FullCrc
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::FullCrc::FullCrc() :
STest::Rule<Os::Test::File::Tester>("FullCrc") {}
bool Os::Test::File::Tester::FullCrc::precondition(
const Os::Test::File::Tester& state //!< The test state
) {
return state.m_mode == Os::File::Mode::OPEN_READ;
}
void Os::Test::File::Tester::FullCrc::action(
Os::Test::File::Tester& state //!< The test state
) {
U32 crc = 1;
U32 shadow_crc = 2;
state.assert_file_consistent();
Os::File::Status status = state.m_file.calculateCrc(crc);
state.shadow_crc(shadow_crc);
ASSERT_EQ(status, Os::File::Status::OP_OK);
ASSERT_EQ(crc, shadow_crc);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: IncrementalCrc
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::IncrementalCrc::IncrementalCrc() :
STest::Rule<Os::Test::File::Tester>("IncrementalCrc") {}
bool Os::Test::File::Tester::IncrementalCrc::precondition(
const Os::Test::File::Tester& state //!< The test state
) {
return state.m_mode == Os::File::Mode::OPEN_READ;
}
void Os::Test::File::Tester::IncrementalCrc::action(
Os::Test::File::Tester& state //!< The test state
){
state.assert_file_consistent();
FwSignedSizeType size_desired = static_cast<FwSignedSizeType>(STest::Pick::lowerUpper(0, FW_FILE_CHUNK_SIZE));
FwSignedSizeType shadow_size = size_desired;
Os::File::Status status = state.m_file.incrementalCrc(size_desired);
state.shadow_partial_crc(shadow_size);
ASSERT_EQ(status, Os::File::Status::OP_OK);
ASSERT_EQ(size_desired, shadow_size);
ASSERT_EQ(state.m_file.m_crc, state.m_independent_crc);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: FinalizeCrc
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::FinalizeCrc::FinalizeCrc() :
STest::Rule<Os::Test::File::Tester>("FinalizeCrc") {}
bool Os::Test::File::Tester::FinalizeCrc::precondition(
const Os::Test::File::Tester& state //!< The test state
) {
return true;
}
void Os::Test::File::Tester::FinalizeCrc::action(
Os::Test::File::Tester& state //!< The test state
) {
U32 crc = 1;
U32 shadow_crc = 2;
state.assert_file_consistent();
Os::File::Status status = state.m_file.finalizeCrc(crc);
state.shadow_finalize(shadow_crc);
ASSERT_EQ(status, Os::File::Status::OP_OK);
ASSERT_EQ(crc, shadow_crc);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: FullCrcInvalidModes
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::FullCrcInvalidModes::FullCrcInvalidModes() :
STest::Rule<Os::Test::File::Tester>("FullCrcInvalidModes") {}
bool Os::Test::File::Tester::FullCrcInvalidModes::precondition(
const Os::Test::File::Tester& state //!< The test state
) {
return Os::File::Mode::OPEN_READ != state.m_mode;
}
void Os::Test::File::Tester::FullCrcInvalidModes::action(
Os::Test::File::Tester& state //!< The test state
) {
state.assert_file_consistent();
FileState original_file_state = state.current_file_state();
ASSERT_TRUE(Os::File::Mode::OPEN_READ != state.m_file.m_mode);
U32 crc = 1;
Os::File::Status status = state.m_file.calculateCrc(crc);
ASSERT_EQ(crc, 0);
state.assert_valid_mode_status(status);
// Ensure no change in size or pointer
FileState final_file_state = state.current_file_state();
ASSERT_EQ(final_file_state.size, original_file_state.size);
ASSERT_EQ(final_file_state.position, original_file_state.position);
state.assert_file_consistent();
}
// ------------------------------------------------------------------------------------------------------
// Rule: IncrementalCrcInvalidModes
//
// ------------------------------------------------------------------------------------------------------
Os::Test::File::Tester::IncrementalCrcInvalidModes::IncrementalCrcInvalidModes() :
STest::Rule<Os::Test::File::Tester>("IncrementalCrcInvalidModes") {}
bool Os::Test::File::Tester::IncrementalCrcInvalidModes::precondition(
const Os::Test::File::Tester& state //!< The test state
) {
return Os::File::Mode::OPEN_READ != state.m_mode;;
}
void Os::Test::File::Tester::IncrementalCrcInvalidModes::action(
Os::Test::File::Tester& state //!< The test state
) {
state.assert_file_consistent();
FileState original_file_state = state.current_file_state();
ASSERT_TRUE(Os::File::Mode::OPEN_READ != state.m_file.m_mode);
FwSignedSizeType size = static_cast<FwSignedSizeType>(STest::Pick::lowerUpper(0, 1));
Os::File::Status status = state.m_file.incrementalCrc(size);
state.assert_valid_mode_status(status);
// Ensure no change in size or pointer
FileState final_file_state = state.current_file_state();
ASSERT_EQ(final_file_state.size, original_file_state.size);
ASSERT_EQ(final_file_state.position, original_file_state.position);
state.assert_file_consistent();
}
| cpp |
fprime | data/projects/fprime/Os/test/ut/file/FileRules.hpp | // ======================================================================
// \title Os/test/ut/file/MyRules.hpp
// \brief rule definitions for common testing
// ======================================================================
// Stripped when compiled, here for IDEs
#include "RulesHeaders.hpp"
// ------------------------------------------------------------------------------------------------------
// OpenFile: base rule for all open rules
//
// ------------------------------------------------------------------------------------------------------
struct OpenBaseRule : public STest::Rule<Os::Test::File::Tester> {
//! Constructor
OpenBaseRule(const char *rule_name, Os::File::Mode mode = Os::File::Mode::OPEN_CREATE, const bool overwrite = false,
const bool randomize_filename = false);
Os::File::Mode m_mode;
Os::File::OverwriteType m_overwrite;
bool m_random;
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: OpenFileCreate
//
// ------------------------------------------------------------------------------------------------------
struct OpenFileCreate : public OpenBaseRule {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
explicit OpenFileCreate(const bool randomize_filename = false);
};
// ------------------------------------------------------------------------------------------------------
// Rule: OpenFileCreateOverwrite
//
// ------------------------------------------------------------------------------------------------------
struct OpenFileCreateOverwrite : public OpenBaseRule {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
explicit OpenFileCreateOverwrite(const bool randomize_filename = false);
};
// ------------------------------------------------------------------------------------------------------
// Rule: OpenForWrite
//
// ------------------------------------------------------------------------------------------------------
struct OpenForWrite : public OpenBaseRule {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
explicit OpenForWrite(const bool randomize_filename = false);
};
// ------------------------------------------------------------------------------------------------------
// Rule: OpenForRead
//
// ------------------------------------------------------------------------------------------------------
struct OpenForRead : public OpenBaseRule {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
explicit OpenForRead(const bool randomize_filename = false);
};
// ------------------------------------------------------------------------------------------------------
// Rule: CloseFile
//
// ------------------------------------------------------------------------------------------------------
struct CloseFile : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
CloseFile();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: Read
//
// ------------------------------------------------------------------------------------------------------
struct Read : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
Read();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(
const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(
Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: Write
//
// ------------------------------------------------------------------------------------------------------
struct Write : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
Write();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(
const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(
Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: Seek
//
// ------------------------------------------------------------------------------------------------------
struct Seek : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
Seek();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(
const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(
Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: Preallocate
//
// ------------------------------------------------------------------------------------------------------
struct Preallocate : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
Preallocate();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(
const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(
Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: Flush
//
// ------------------------------------------------------------------------------------------------------
struct Flush : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
Flush();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(
const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(
Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: OpenInvalidModes
//
// ------------------------------------------------------------------------------------------------------
struct OpenInvalidModes : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
OpenInvalidModes();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: PreallocateWithoutOpen
//
// ------------------------------------------------------------------------------------------------------
struct PreallocateWithoutOpen : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
PreallocateWithoutOpen();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: SeekWithoutOpen
//
// ------------------------------------------------------------------------------------------------------
struct SeekWithoutOpen : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
SeekWithoutOpen();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: SeekInvalidSize
//
// ------------------------------------------------------------------------------------------------------
struct SeekInvalidSize : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
SeekInvalidSize();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: FlushInvalidModes
//
// ------------------------------------------------------------------------------------------------------
struct FlushInvalidModes : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
FlushInvalidModes();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: ReadInvalidModes
//
// ------------------------------------------------------------------------------------------------------
struct ReadInvalidModes : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
ReadInvalidModes();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: WriteInvalidModes
//
// ------------------------------------------------------------------------------------------------------
struct WriteInvalidModes : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
WriteInvalidModes();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(const Os::Test::File::Tester &state //!< The test state
);
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Base Rule: AssertRule
//
// ------------------------------------------------------------------------------------------------------
struct AssertRule : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
explicit AssertRule(const char *name);
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(const Os::Test::File::Tester &state //!< The test state
);
//! Action
virtual void action(Os::Test::File::Tester &state //!< The test state
) = 0;
};
// ------------------------------------------------------------------------------------------------------
// Rule: OpenIllegalPath
//
// ------------------------------------------------------------------------------------------------------
struct OpenIllegalPath : public AssertRule {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
OpenIllegalPath();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Action
void action(Os::Test::File::Tester &state //!< The test state
) override;
};
// ------------------------------------------------------------------------------------------------------
// Rule: OpenIllegalMode
//
// ------------------------------------------------------------------------------------------------------
struct OpenIllegalMode : public AssertRule {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
OpenIllegalMode();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: PreallocateIllegalOffset
//
// ------------------------------------------------------------------------------------------------------
struct PreallocateIllegalOffset : public AssertRule {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
PreallocateIllegalOffset();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: PreallocateIllegalLength
//
// ------------------------------------------------------------------------------------------------------
struct PreallocateIllegalLength : public AssertRule {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
PreallocateIllegalLength();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: SeekIllegal
//
// ------------------------------------------------------------------------------------------------------
struct SeekIllegal : public AssertRule {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
SeekIllegal();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: ReadIllegalBuffer
//
// ------------------------------------------------------------------------------------------------------
struct ReadIllegalBuffer : public AssertRule {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
ReadIllegalBuffer();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: ReadIllegalSize
//
// ------------------------------------------------------------------------------------------------------
struct ReadIllegalSize : public AssertRule {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
ReadIllegalSize();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: WriteIllegalBuffer
//
// ------------------------------------------------------------------------------------------------------
struct WriteIllegalBuffer : public AssertRule {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
WriteIllegalBuffer();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: WriteIllegalSize
//
// ------------------------------------------------------------------------------------------------------
struct WriteIllegalSize : public AssertRule {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
WriteIllegalSize();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Action
void action(Os::Test::File::Tester &state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: CopyAssignment
//
// ------------------------------------------------------------------------------------------------------
struct CopyAssignment : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
CopyAssignment();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(
const Os::Test::File::Tester& state //!< The test state
);
//! Action
void action(
Os::Test::File::Tester& state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: CopyConstruction
//
// ------------------------------------------------------------------------------------------------------
struct CopyConstruction : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
CopyConstruction();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(
const Os::Test::File::Tester& state //!< The test state
);
//! Action
void action(
Os::Test::File::Tester& state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: FullCrc
//
// ------------------------------------------------------------------------------------------------------
struct FullCrc : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
FullCrc();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(
const Os::Test::File::Tester& state //!< The test state
);
//! Action
void action(
Os::Test::File::Tester& state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: IncrementalCrc
//
// ------------------------------------------------------------------------------------------------------
struct IncrementalCrc : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
IncrementalCrc();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(
const Os::Test::File::Tester& state //!< The test state
);
//! Action
void action(
Os::Test::File::Tester& state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: FinalizeCrc
//
// ------------------------------------------------------------------------------------------------------
struct FinalizeCrc : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
FinalizeCrc();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(
const Os::Test::File::Tester& state //!< The test state
);
//! Action
void action(
Os::Test::File::Tester& state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: FullCrcInvalidModes
//
// ------------------------------------------------------------------------------------------------------
struct FullCrcInvalidModes : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
FullCrcInvalidModes();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(
const Os::Test::File::Tester& state //!< The test state
);
//! Action
void action(
Os::Test::File::Tester& state //!< The test state
);
};
// ------------------------------------------------------------------------------------------------------
// Rule: IncrementalCrcInvalidModes
//
// ------------------------------------------------------------------------------------------------------
struct IncrementalCrcInvalidModes : public STest::Rule<Os::Test::File::Tester> {
// ----------------------------------------------------------------------
// Construction
// ----------------------------------------------------------------------
//! Constructor
IncrementalCrcInvalidModes();
// ----------------------------------------------------------------------
// Public member functions
// ----------------------------------------------------------------------
//! Precondition
bool precondition(
const Os::Test::File::Tester& state //!< The test state
);
//! Action
void action(
Os::Test::File::Tester& state //!< The test state
);
};
| hpp |
fprime | data/projects/fprime/Os/test/ut/file/RulesHeaders.hpp | // ======================================================================
// \title Os/test/ut/file/RulesHeaders.hpp
// \brief rule definitions for common testing
// ======================================================================
#ifndef __RULES_HEADERS__
#define __RULES_HEADERS__
#include <gtest/gtest.h>
#include <cstdio>
#include <map>
#include "Os/File.hpp"
#include "STest/Rule/Rule.hpp"
#include "STest/Scenario/BoundedScenario.hpp"
#include "STest/Scenario/RandomScenario.hpp"
#include "STest/Scenario/Scenario.hpp"
#include "Os/test/ut/file/SyntheticFileSystem.hpp"
namespace Os {
namespace Test {
namespace File {
struct Tester {
//! State data for an open OS file.
//!
struct FileState {
FwSignedSizeType size = -1;
FwSignedSizeType position = -1;
};
//! Assert in File.cpp for searching death text
static constexpr const char* ASSERT_IN_FILE_CPP = "Assert: \".*/Os/File\\.cpp:[0-9]+\"";
// Constructors that ensures the file is always valid
Tester();
// Destructor must be virtual
virtual ~Tester() = default;
//! Check if the test file exists.
//! \return true if it exists, false otherwise.
//!
virtual bool exists(const std::string& filename) const = 0;
//! Check if the back-end tester is fully functional
//! \return true if functional, false otherwise
//!
virtual bool functional() const = 0;
//! Get a filename, randomly if random is true, otherwise use a basic filename.
//! \param random: true if filename should be random, false if predictable
//! \return: filename to use for testing as a shared pointer
//!
virtual std::shared_ptr<const std::string> get_filename(bool random) const = 0;
//! Performs the "open" action on the shadow state.
//!
Os::File::Status shadow_open(const std::string &path, Os::File::Mode newly_opened_mode = Os::File::Mode::OPEN_NO_MODE,
bool overwrite = false);
//! Perform the "close" action on the shadow state.
//!
void shadow_close();
//! Perform the "read" action on the shadow state returning the read data.
//! \return data read
//!
std::vector<U8> shadow_read(FwSignedSizeType size);
//! Perform the "write" action on the shadow state given the data.
//!
void shadow_write(const std::vector<U8>& data);
//! Perform the "seek" action on the shadow state given.
//!
void shadow_seek(const FwSignedSizeType offset, const bool absolute);
//! Perform the "preallocate" action on the shadow state.
//!
void shadow_preallocate(const FwSignedSizeType offset, const FwSignedSizeType length);
//! Perform the "flush" action on the shadow state.
//!
void shadow_flush();
//! Perform the "full crc" action on the shadow state.
//! \param crc: output for CRC value
//!
void shadow_crc(U32& crc);
//! Perform the "incremental crc" action on the shadow state.
//! \param crc: output for CRC value
//!
void shadow_partial_crc(FwSignedSizeType& size);
//! Perform the "crc finalize" action on the shadow state.
//! \param crc: output for CRC value
//!
void shadow_finalize(U32& crc);
//! Detect current state of the file. Note: for files that are known, but unopened this will open the file as read
//! detect the state, and then close it again.
//! \return file state for the test
//!
FileState current_file_state();
//! Assert file and shadow state are in-sync
//!
void assert_file_consistent();
//! Assert that the supplied status is appropriate for the current mode.
//! \param status: status to check
//!
void assert_valid_mode_status(Os::File::Status& status) const;
//! Assert that the file is opened
//!
void assert_file_opened(const std::string& path="", Os::File::Mode newly_opened_mode = Os::File::Mode::OPEN_NO_MODE, bool overwrite = false);
//! Assert that the file is closed
//!
void assert_file_closed();
//! Assert a file read
//!
void assert_file_read(const std::vector<U8>& state_data, const unsigned char* read_data, FwSignedSizeType size_read);
//! Assert a file write
//!
void assert_file_write(const std::vector<U8>& write_data, FwSignedSizeType size_written);
//! Assert a file seek
//!
void assert_file_seek(const FwSignedSizeType original_position, const FwSignedSizeType seek_desired, const bool absolute);
//! File under test
Os::File m_file;
//! Shadow file state: file system
Os::Test::SyntheticFile m_shadow;
//! Currently opened path
std::string m_current_path;
//! Independent tracking of mode
Os::File::Mode m_mode = Os::File::Mode::OPEN_NO_MODE;
U32 m_independent_crc = Os::File::INITIAL_CRC;
// Do NOT alter, adds rules to Tester as inner classes
#include "FileRules.hpp"
};
//! Get the tester implementation for the given backend.
//! \return pointer to tester subclass implementation
//!
std::unique_ptr<Os::Test::File::Tester> get_tester_implementation();
} // namespace File
} // namespace Test
} // namespace Os
#endif // __RULES_HEADERS__
| hpp |
fprime | data/projects/fprime/Os/test/ut/file/SyntheticFileSystem.hpp | // ======================================================================
// \title Os/test/ut/file/SyntheticFileSystem.hpp
// \brief standard template library driven synthetic file system definitions
// ======================================================================
#include "config/FpConfig.h"
#include "Os/File.hpp"
#include <map>
#include <memory>
#include <vector>
#include <string>
#ifndef OS_TEST_UT_FILE_SYNTHETIC_FILE_SYSTEM
#define OS_TEST_UT_FILE_SYNTHETIC_FILE_SYSTEM
namespace Os {
namespace Test {
// Forward declaration
class SyntheticFileSystem;
struct SyntheticFileData : public FileHandle {
//! Path of this file
std::string m_path;
//! Data stored in the file
std::vector<U8> m_data;
//! Pointer of the file
FwSignedSizeType m_pointer = -1;
//! Separate mode tracking
File::Mode m_mode = File::OPEN_NO_MODE;
};
//! \brief Synthetic file data implementation
//!
//! File implementation for a synthetic standard template library based file.
//!
class SyntheticFile : public FileInterface {
public:
friend class SyntheticFileSystem;
//! \brief check if file exists
static bool exists(const CHAR* path);
//! \brief set the file system
static void setFileSystem(std::unique_ptr<SyntheticFileSystem> new_file_system);
//! \brief remove a file by path
static void remove(const CHAR* path);
//! \brief open a given path with mode and overwrite
//!
//! This opens a file at the given path. Mode drives the mode of the file and overwrite will overwrite files if it
//! exists and was created. Returns a pair of status and synthetic file data.
//!
//! \param path: path to open
//! \param mode: mode to open with
//! \param overwrite: overwrite if exists
//! \return (status, synthetic file object)
//!
Status open(const CHAR *path, const Os::File::Mode mode, const OverwriteType overwrite) override;
//! \brief close the file
//!
void close() override;
//! \brief read data from the file
//!
//! Read from the synthetic file and fill the buffer up-to size. Fill size with the data that was read.
//!
//! \param buffer: buffer to fill
//! \param size: size of data to read
//! \param wait: wait, unused
//! \return status of the read
//!
Os::File::Status read(U8 *buffer, FwSignedSizeType &size, File::WaitType wait) override;
//! \brief write data to the file
//!
//! Write to the synthetic file from the buffer of given size. Fill size with the data that was written.
//!
//! \param buffer: buffer to fill
//! \param size: size of data to read
//! \param bool: wait, unused
//! \return status of the write
//!
Os::File::Status write(const U8 *buffer, FwSignedSizeType &size, File::WaitType wait) override;
//! \brief seek pointer within file
//!
//! Seek the pointer within the file.
//!
//! \param offset: offset to seek to
//! \param bool: absolute
//! \return status of the seek
//!
Os::File::Status seek(const FwSignedSizeType offset, const File::SeekType absolute) override;
//! \brief preallocate data within file
//!
//! Preallocate data within the file.
//!
//! \param offset: offset to start pre-allocation
//! \param length: length of the pre-allocation
//! \return status of the preallocate
//!
Os::File::Status preallocate(const FwSignedSizeType offset, const FwSignedSizeType length) override;
//! \brief flush is no-op
//!
Os::File::Status flush() override;
//! \brief pointer getter
Os::File::Status position(FwSignedSizeType& position) override;
//! \brief size getter
Os::File::Status size(FwSignedSizeType& size) override;
//! \brief silt data handle
FileHandle* getHandle() override;
std::shared_ptr<SyntheticFileData> m_data;
static std::unique_ptr<SyntheticFileSystem> s_file_system;
};
//! \brief Synthetic file system implementation
//!
//! A synthetic standard template library based in-memory file system for use with testing. It is composed of a map of string paths to a
//! synthetic file data packet that tracks data and file pointer
//!
class SyntheticFileSystem {
public:
friend class SyntheticFile;
//! \brief data returned by the open call
//!
struct OpenData {
std::shared_ptr<SyntheticFileData> file;
Os::File::Status status = Os::File::Status::OTHER_ERROR;
};
//! Constructor
SyntheticFileSystem() = default;
//! Destructor
virtual ~SyntheticFileSystem() = default;
//! \brief check a file exists
//!
//! Check if a file exists.
//!
//! \return: true if exists, false otherwise
//!
bool exists(const CHAR *path);
//! \brief remove file
void remove(const CHAR* path);
private:
//! \brief open a given path with mode and overwrite
//!
//! This opens a file at the given path. Mode drives the mode of the file and overwrite will overwrite files if it
//! exists and was created. Returns a pair of status and synthetic file data.
//!
//! \param path: path to open
//! \param mode: mode to open with
//! \param overwrite: overwrite if exists
//! \return (status, synthetic file object)
//!
OpenData open(const CHAR *path, const Os::File::Mode mode, const File::OverwriteType overwrite);
//! Shadow file state: file system
std::map<std::string, std::shared_ptr<SyntheticFileData>> m_filesystem;
};
} // namespace Test
} // namespace Os
#endif // OS_TEST_UT_FILE_SYNTHETIC_FILE_SYSTEM
| hpp |
fprime | data/projects/fprime/Os/Posix/File.cpp | // ======================================================================
// \title Os/Posix/File.cpp
// \brief posix implementation for Os::File
// ======================================================================
#include <cerrno>
#include <fcntl.h>
#include <unistd.h>
#include <limits>
#include <Os/File.hpp>
#include <Os/Posix/File.hpp>
#include <Fw/Types/Assert.hpp>
#include <Os/Posix/errno.hpp>
namespace Os {
namespace Posix {
namespace File {
// Sets up the default file permission as user read + user write
// Some posix systems (e.g. Darwin) use the older S_IREAD and S_IWRITE flags while other systems (e.g. Linux) use the
// newer S_IRUSR and S_IWUSR flags, and some don't support these flags at all. Hence, we look if flags are defined then
// set USER_FLAGS to be the set of flags supported or 0 in the case neither is defined.
#if defined(S_IREAD) && defined(S_IWRITE)
#define USER_FLAGS (S_IREAD | S_IWRITE)
#elif defined(S_IRUSR) && defined(S_IWUSR)
#define USER_FLAGS (S_IRUSR | S_IWUSR)
#else
#define USER_FLAGS (0)
#endif
// Ensure size of FwSizeType is large enough to fit eh necessary range
static_assert(sizeof(FwSignedSizeType) >= sizeof(off_t), "FwSizeType is not large enough to store values of type off_t");
static_assert(sizeof(FwSignedSizeType) >= sizeof(ssize_t), "FwSizeType is not large enough to store values of type ssize_t");
// Now check ranges of FwSizeType
static_assert(std::numeric_limits<FwSignedSizeType>::max() >= std::numeric_limits<off_t>::max(),
"Maximum value of FwSizeType less than the maximum value of off_t. Configure a larger type.");
static_assert(std::numeric_limits<FwSignedSizeType>::max() >= std::numeric_limits<ssize_t>::max(),
"Maximum value of FwSizeType less than the maximum value of ssize_t. Configure a larger type.");
static_assert(std::numeric_limits<FwSignedSizeType>::min() <= std::numeric_limits<off_t>::min(),
"Minimum value of FwSizeType larger than the minimum value of off_t. Configure a larger type.");
static_assert(std::numeric_limits<FwSignedSizeType>::min() <= std::numeric_limits<ssize_t>::min(),
"Minimum value of FwSizeType larger than the minimum value of ssize_t. Configure a larger type.");
//!\brief default copy constructor
PosixFile::PosixFile(const PosixFile& other) {
// Must properly duplicate the file handle
this->m_handle.m_file_descriptor = ::dup(other.m_handle.m_file_descriptor);
}
PosixFile& PosixFile::operator=(const PosixFile& other) {
if (this != &other) {
this->m_handle.m_file_descriptor = ::dup(other.m_handle.m_file_descriptor);
}
return *this;
}
PosixFile::Status PosixFile::open(const char* filepath, PosixFile::Mode requested_mode, PosixFile::OverwriteType overwrite) {
PlatformIntType mode_flags = 0;
Status status = OP_OK;
switch (requested_mode) {
case OPEN_READ:
mode_flags = O_RDONLY;
break;
case OPEN_WRITE:
mode_flags = O_WRONLY | O_CREAT;
break;
case OPEN_SYNC_WRITE:
mode_flags = O_WRONLY | O_CREAT | O_SYNC;
break;
case OPEN_CREATE:
mode_flags = O_WRONLY | O_CREAT | O_TRUNC | ((overwrite == PosixFile::OverwriteType::OVERWRITE) ? 0 : O_EXCL);
break;
case OPEN_APPEND:
mode_flags = O_WRONLY | O_CREAT | O_APPEND;
break;
default:
FW_ASSERT(0, requested_mode);
break;
}
PlatformIntType descriptor = ::open(filepath, mode_flags, USER_FLAGS);
if (PosixFileHandle::INVALID_FILE_DESCRIPTOR == descriptor) {
PlatformIntType errno_store = errno;
status = Os::Posix::errno_to_file_status(errno_store);
}
this->m_handle.m_file_descriptor = descriptor;
return status;
}
void PosixFile::close() {
// Only close file handles that are not open
if (PosixFileHandle::INVALID_FILE_DESCRIPTOR != this->m_handle.m_file_descriptor) {
(void)::close(this->m_handle.m_file_descriptor);
this->m_handle.m_file_descriptor = PosixFileHandle::INVALID_FILE_DESCRIPTOR;
}
}
PosixFile::Status PosixFile::size(FwSignedSizeType& size_result) {
FwSignedSizeType current_position = 0;
Status status = this->position(current_position);
size_result = 0;
if (Os::File::Status::OP_OK == status) {
// Seek to the end of the file to determine size
off_t end_of_file = ::lseek(this->m_handle.m_file_descriptor, 0, SEEK_END);
if (PosixFileHandle::ERROR_RETURN_VALUE == end_of_file) {
PlatformIntType errno_store = errno;
status = Os::Posix::errno_to_file_status(errno_store);
} else {
// Return the file pointer back to the original position
off_t original = ::lseek(this->m_handle.m_file_descriptor, current_position, SEEK_SET);
if ((PosixFileHandle::ERROR_RETURN_VALUE == original) || (current_position != original)) {
PlatformIntType errno_store = errno;
status = Os::Posix::errno_to_file_status(errno_store);
}
}
size_result = end_of_file;
}
return status;
}
PosixFile::Status PosixFile::position(FwSignedSizeType &position_result) {
Status status = OP_OK;
position_result = 0;
off_t actual = ::lseek(this->m_handle.m_file_descriptor, 0, SEEK_CUR);
if (PosixFileHandle::ERROR_RETURN_VALUE == actual) {
PlatformIntType errno_store = errno;
status = Os::Posix::errno_to_file_status(errno_store);
}
position_result = static_cast<FwSignedSizeType>(actual);
return status;
}
PosixFile::Status PosixFile::preallocate(FwSignedSizeType offset, FwSignedSizeType length) {
PosixFile::Status status = Os::File::Status::NOT_SUPPORTED;
// posix_fallocate is only available with the posix C-API post version 200112L, however; it is not guaranteed that
// this call is properly implemented. This code starts with a status of "NOT_SUPPORTED". When the standard is met
// an attempt will be made to called posix_fallocate, and should that still return NOT_SUPPORTED then fallback
// code is engaged to synthesize this behavior.
#if _POSIX_C_SOURCE >= 200112L
PlatformIntType errno_status = ::posix_fallocate(this->m_handle.m_file_descriptor, offset, length);
status = Os::Posix::errno_to_file_status(errno_status);
#endif
// When the operation is not supported or posix-API is not sufficient, fallback to a slower algorithm
if (Os::File::Status::NOT_SUPPORTED == status) {
// Calculate size
FwSignedSizeType file_size = 0;
status = this->size(file_size);
if (Os::File::Status::OP_OK == status) {
// Calculate current position
FwSignedSizeType file_position = 0;
status = this->position(file_position);
if (Os::File::Status::OP_OK == status) {
// Check for integer overflow
if ((std::numeric_limits<FwSignedSizeType>::max() - offset - length) < 0) {
status = PosixFile::NO_SPACE;
} else if (file_size < (offset + length)) {
const FwSignedSizeType write_length = (offset + length) - file_size;
status = this->seek(file_size, PosixFile::SeekType::ABSOLUTE);
if (Os::File::Status::OP_OK == status) {
// Fill in zeros past size of file to ensure compatibility with fallocate
for (FwSignedSizeType i = 0; i < write_length; i++) {
FwSignedSizeType write_size = 1;
status = this->write(reinterpret_cast<const U8*>("\0"), write_size, PosixFile::WaitType::NO_WAIT);
if (Status::OP_OK != status || write_size != 1) {
break;
}
}
// Return to original position
if (Os::File::Status::OP_OK == status) {
status = this->seek(file_position, PosixFile::SeekType::ABSOLUTE);
}
}
}
}
}
}
return status;
}
PosixFile::Status PosixFile::seek(FwSignedSizeType offset, PosixFile::SeekType seekType) {
Status status = OP_OK;
off_t actual = ::lseek(this->m_handle.m_file_descriptor, offset, (seekType == SeekType::ABSOLUTE) ? SEEK_SET : SEEK_CUR);
PlatformIntType errno_store = errno;
if (actual == PosixFileHandle::ERROR_RETURN_VALUE) {
status = Os::Posix::errno_to_file_status(errno_store);
} else if ((seekType == SeekType::ABSOLUTE) && (actual != offset)) {
status = Os::File::Status::OTHER_ERROR;
}
return status;
}
PosixFile::Status PosixFile::flush() {
PosixFile::Status status = OP_OK;
if (PosixFileHandle::ERROR_RETURN_VALUE == ::fsync(this->m_handle.m_file_descriptor)) {
PlatformIntType errno_store = errno;
status = Os::Posix::errno_to_file_status(errno_store);
}
return status;
}
PosixFile::Status PosixFile::read(U8* buffer, FwSignedSizeType &size, PosixFile::WaitType wait) {
Status status = OP_OK;
FwSignedSizeType accumulated = 0;
// Loop up to 2 times for each by, bounded to prevent overflow
const FwSignedSizeType maximum = (size > (std::numeric_limits<FwSignedSizeType>::max()/2)) ? std::numeric_limits<FwSignedSizeType>::max() : size * 2;
for (FwSignedSizeType i = 0; i < maximum && accumulated < size; i++) {
// char* for some posix implementations
ssize_t read_size = ::read(this->m_handle.m_file_descriptor, reinterpret_cast<CHAR*>(&buffer[accumulated]), size - accumulated);
// Non-interrupt error
if (PosixFileHandle::ERROR_RETURN_VALUE == read_size) {
PlatformIntType errno_store = errno;
// Interrupted w/o read, try again
if (EINTR != errno_store) {
continue;
}
status = Os::Posix::errno_to_file_status(errno_store);
break;
}
// End-of-file
else if (read_size == 0) {
break;
}
accumulated += read_size;
// Stop looping when we had a good read and are not waiting
if (not wait) {
break;
}
}
size = accumulated;
return status;
}
PosixFile::Status PosixFile::write(const U8* buffer, FwSignedSizeType &size, PosixFile::WaitType wait) {
Status status = OP_OK;
FwSignedSizeType accumulated = 0;
// Loop up to 2 times for each by, bounded to prevent overflow
const FwSignedSizeType maximum = (size > (std::numeric_limits<FwSignedSizeType>::max()/2)) ? std::numeric_limits<FwSignedSizeType>::max() : size * 2;
for (FwSignedSizeType i = 0; i < maximum && accumulated < size; i++) {
// char* for some posix implementations
ssize_t write_size = ::write(this->m_handle.m_file_descriptor, reinterpret_cast<const CHAR*>(&buffer[accumulated]), size - accumulated);
// Non-interrupt error
if (PosixFileHandle::ERROR_RETURN_VALUE == write_size) {
PlatformIntType errno_store = errno;
// Interrupted w/o read, try again
if (EINTR != errno_store) {
continue;
}
status = Os::Posix::errno_to_file_status(errno_store);
break;
}
accumulated += write_size;
}
size = accumulated;
// When waiting, sync to disk
if (wait) {
PlatformIntType fsync_return = ::fsync(this->m_handle.m_file_descriptor);
if (PosixFileHandle::ERROR_RETURN_VALUE == fsync_return) {
PlatformIntType errno_store = errno;
status = Os::Posix::errno_to_file_status(errno_store);
}
}
return status;
}
FileHandle* PosixFile::getHandle() {
return &this->m_handle;
}
} // namespace File
} // namespace Posix
} // namespace Os
| cpp |
fprime | data/projects/fprime/Os/Posix/LocklessQueue.cpp | #include <Os/LocklessQueue.hpp>
#include <Fw/Types/Assert.hpp>
#include <fcntl.h>
#include <cstring>
#include <new>
#define CAS(a_ptr, a_oldVal, a_newVal) __sync_bool_compare_and_swap(a_ptr, a_oldVal, a_newVal)
namespace Os {
LocklessQueue::LocklessQueue(const NATIVE_INT_TYPE maxmsg,
const NATIVE_INT_TYPE msgsize) {
#ifndef BUILD_DARWIN
m_attr.mq_flags = O_NONBLOCK;
m_attr.mq_maxmsg = maxmsg;
m_attr.mq_msgsize = msgsize;
m_attr.mq_curmsgs = 0;
#endif
// Must have at least 2 messages in the queue
FW_ASSERT(maxmsg >= 2, maxmsg);
m_index = new(std::nothrow) QueueNode[maxmsg]; // Allocate an index entry for each msg
m_data = new(std::nothrow) U8[maxmsg * msgsize]; // Allocate data for each msg
FW_ASSERT(m_index != nullptr);
FW_ASSERT(m_data != nullptr);
for (int i = 0, j = 1; i < maxmsg; i++, j++) {
m_index[i].data = &m_data[i * msgsize]; // Assign the data pointer of index to top that msg's buffer
if (j < maxmsg) { // If we aren't processing the last item
m_index[i].next = &m_index[j]; // Chain this item to the next one
} else {
m_index[i].next = nullptr; // Initialize to NULL otherwise
}
}
// Assign each of the pointers to the first index element
// This one is held in a "dummy" position for now
// It will be cleaned up by the producer
m_first = &m_index[0];
m_last = &m_index[0];
m_last->next = nullptr;
// Assign the head of the free list to the second element
m_free_head = &m_index[1];
}
LocklessQueue::~LocklessQueue() {
delete[] m_index;
delete[] m_data;
}
#ifndef BUILD_DARWIN
void LocklessQueue::GetAttr(mq_attr & attr) {
memcpy(&attr, &m_attr, sizeof(mq_attr));
}
#endif
void LocklessQueue::PushFree(QueueNode * my_node) {
QueueNode * old_free_head;
FW_ASSERT(my_node != nullptr);
// CAS the node into the free list
do {
old_free_head = m_free_head;
my_node->next = old_free_head;
} while (!CAS(&m_free_head, old_free_head, my_node));
}
bool LocklessQueue::PopFree(QueueNode ** free_node) {
QueueNode * my_node;
// CAS a buffer from the free list
do {
my_node = m_free_head;
if (nullptr == my_node) {
return false;
}
} while (!CAS(&m_free_head, my_node, my_node->next));
(*free_node) = my_node;
return true;
}
Queue::QueueStatus LocklessQueue::Send(const U8 * buffer,
NATIVE_INT_TYPE size) {
QueueNode * my_node;
QueueNode * old_last;
#ifndef BUILD_DARWIN
// Check that the new message will fit in our buffers
if (size > m_attr.mq_msgsize) {
return Queue::QUEUE_SIZE_MISMATCH;
}
#endif
if (!PopFree(&my_node)) {
return Queue::QUEUE_FULL;
}
// Copy the data into the buffer
memcpy(my_node->data, buffer, size);
my_node->size = size;
my_node->next = nullptr;
// Publish the node
// The m_last pointer is moved before the item is published
// All concurrent writers will argue over their order using CAS
do {
old_last = m_last;
} while (!CAS(&m_last, old_last, my_node));
old_last->next = my_node;
return Queue::QUEUE_OK;
}
// ONLY ONE RECEIVER AT A TIME!!!!
Queue::QueueStatus LocklessQueue::Receive(U8 * buffer,
NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE & size) {
QueueNode * my_node;
QueueNode * old_node;
#ifndef BUILD_DARWIN
if (capacity < m_attr.mq_msgsize) {
return Queue::QUEUE_SIZE_MISMATCH;
}
#endif
if (m_first == m_last) {
return Queue::QUEUE_NO_MORE_MSGS;
}
old_node = m_first;
my_node = m_first->next;
if (my_node == nullptr) {
// We may not be fully linked yet, even though "last" has moved
return Queue::QUEUE_NO_MORE_MSGS;
}
m_first = m_first->next;
PushFree(old_node);
// Copy the data from the buffer
memcpy(buffer, my_node->data, my_node->size);
size = my_node->size;
return Queue::QUEUE_OK;
}
}
| cpp |
fprime | data/projects/fprime/Os/Posix/TaskId.cpp | // File: TaskId.cpp
// Author: Ben Soudry (benjamin.s.soudry@jpl.nasa.gov)
// Nathan Serafin (nathan.serafin@jpl.nasa.gov)
// Date: 29 June, 2018
//
// POSIX implementation of TaskId type.
extern "C" {
#include <pthread.h>
}
#include <Os/TaskId.hpp>
namespace Os
{
TaskId::TaskId() : id(pthread_self())
{
}
TaskId::~TaskId()
{
}
bool TaskId::operator==(const TaskId& T) const
{
return pthread_equal(id, T.id);
}
bool TaskId::operator!=(const TaskId& T) const
{
return !pthread_equal(id, T.id);
}
TaskIdRepr TaskId::getRepr() const
{
return this->id;
}
}
| cpp |
fprime | data/projects/fprime/Os/Posix/IntervalTimer.cpp | /**
* Posix/IntervalTimer.cpp:
*
* The Posix implementation of the interval timer shares the same raw setup as other X86
* implementations. That is: the lower U32 of the RawTime is nano-seconds, and the upper U32 of
* RawTime object is seconds. Thus only the "getRawTime" function differs from the base X86
* version of this file.
*/
#include <Os/IntervalTimer.hpp>
#include <Fw/Types/Assert.hpp>
#include <ctime>
#include <cerrno>
namespace Os {
void IntervalTimer::getRawTime(RawTime& time) {
timespec t;
PlatformIntType status = clock_gettime(CLOCK_REALTIME,&t);
FW_ASSERT(status == 0,errno);
time.upper = t.tv_sec;
time.lower = t.tv_nsec;
}
// Adapted from: http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html
// should be t1In - t2In
U32 IntervalTimer::getDiffUsec(const RawTime& t1In, const RawTime& t2In) {
RawTime result = {t1In.upper - t2In.upper, 0};
if (t1In.lower < t2In.lower) {
result.upper -= 1; // subtract nsec carry to seconds
result.lower = t1In.lower + (1000000000 - t2In.lower);
} else {
result.lower = t1In.lower - t2In.lower;
}
return (result.upper * 1000000) + (result.lower / 1000);
}
}
| cpp |
fprime | data/projects/fprime/Os/Posix/Queue.cpp | #include <Fw/Types/Assert.hpp>
#include <Os/Queue.hpp>
#ifdef TGT_OS_TYPE_VXWORKS
#include <vxWorks.h>
#endif
#ifdef TGT_OS_TYPE_LINUX
#include <sys/types.h>
#include <unistd.h>
#endif
#include <mqueue.h>
#include <fcntl.h>
#include <cerrno>
#include <cstring>
#include <cstdio>
#include <ctime>
#include <pthread.h>
#include <new>
namespace Os {
class QueueHandle {
public:
QueueHandle(mqd_t m_handle) {
// Initialize the handle:
int ret;
ret = pthread_cond_init(&this->queueNotEmpty, nullptr);
FW_ASSERT(ret == 0, ret); // If this fails, something horrible happened.
ret = pthread_cond_init(&this->queueNotFull, nullptr);
FW_ASSERT(ret == 0, ret); // If this fails, something horrible happened.
ret = pthread_mutex_init(&this->mp, nullptr);
FW_ASSERT(ret == 0, ret); // If this fails, something horrible happened.
this->handle = m_handle;
}
~QueueHandle() {
// Destroy the handle:
if (-1 != this->handle) {
(void) mq_close(this->handle);
}
(void) pthread_cond_destroy(&this->queueNotEmpty);
(void) pthread_mutex_destroy(&this->mp);
}
mqd_t handle;
pthread_cond_t queueNotEmpty;
pthread_cond_t queueNotFull;
pthread_mutex_t mp;
};
Queue::Queue() :
m_handle(-1) {
}
Queue::QueueStatus Queue::createInternal(const Fw::StringBase &name, NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize) {
this->m_name = "/QP_";
this->m_name += name;
#ifndef TGT_OS_TYPE_VXWORKS
char pid[40];
(void)snprintf(pid,sizeof(pid),".%d",getpid());
pid[sizeof(pid)-1] = 0;
this->m_name += pid;
#endif
mq_attr att;
mqd_t handle;
memset(&att,0,sizeof(att));
att.mq_maxmsg = depth;
att.mq_msgsize = msgSize;
att.mq_flags = 0;
att.mq_curmsgs = 0;
handle = mq_open(this->m_name.toChar(), O_RDWR | O_CREAT | O_EXCL | O_NONBLOCK, 0666, &att);
// If queue already exists, then unlink it and try again.
if (-1 == handle) {
switch (errno) {
case EEXIST:
(void)mq_unlink(this->m_name.toChar());
break;
default:
return QUEUE_UNINITIALIZED;
}
handle = mq_open(this->m_name.toChar(), O_RDWR | O_CREAT | O_EXCL, 0666, &att);
if (-1 == handle) {
return QUEUE_UNINITIALIZED;
}
}
// Set up queue handle:
QueueHandle* queueHandle = new(std::nothrow) QueueHandle(handle);
if (nullptr == queueHandle) {
return QUEUE_UNINITIALIZED;
}
this->m_handle = reinterpret_cast<POINTER_CAST>(queueHandle);
Queue::s_numQueues++;
return QUEUE_OK;
}
Queue::~Queue() {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
delete queueHandle;
(void) mq_unlink(this->m_name.toChar());
}
Queue::QueueStatus Queue::send(const U8* buffer, NATIVE_INT_TYPE size, NATIVE_INT_TYPE priority, QueueBlocking block) {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
mqd_t handle = queueHandle->handle;
pthread_cond_t* queueNotEmpty = &queueHandle->queueNotEmpty;
pthread_cond_t* queueNotFull = &queueHandle->queueNotFull;
pthread_mutex_t* mp = &queueHandle->mp;
if (-1 == handle) {
return QUEUE_UNINITIALIZED;
}
if (nullptr == buffer) {
return QUEUE_EMPTY_BUFFER;
}
bool keepTrying = true;
int ret;
while (keepTrying) {
NATIVE_INT_TYPE stat = mq_send(handle, reinterpret_cast<const char*>(buffer), size, priority);
if (-1 == stat) {
switch (errno) {
case EINTR:
continue;
case EMSGSIZE:
return QUEUE_SIZE_MISMATCH;
case EINVAL:
return QUEUE_INVALID_PRIORITY;
case EAGAIN:
if (block == QUEUE_NONBLOCKING) {
// no more messages. If we are
// non-blocking, return
return QUEUE_FULL;
} else {
// Go to sleep until we receive a signal that something was taken off the queue:
// Note: pthread_cont_wait must be called "with mutex locked by the calling
// thread or undefined behavior results." - from the docs
ret = pthread_mutex_lock(mp);
FW_ASSERT(ret == 0, errno);
ret = pthread_cond_wait(queueNotFull, mp);
FW_ASSERT(ret == 0, ret); // If this fails, something horrible happened.
ret = pthread_mutex_unlock(mp);
FW_ASSERT(ret == 0, errno);
continue;
}
default:
return QUEUE_UNKNOWN_ERROR;
}
} else {
keepTrying=false;
// Wake up a thread that might be waiting on the other end of the queue:
ret = pthread_cond_signal(queueNotEmpty);
FW_ASSERT(ret == 0, ret); // If this fails, something horrible happened.
}
}
return QUEUE_OK;
}
Queue::QueueStatus Queue::receive(U8* buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE &actualSize, NATIVE_INT_TYPE &priority, QueueBlocking block) {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
mqd_t handle = queueHandle->handle;
pthread_cond_t* queueNotEmpty = &queueHandle->queueNotEmpty;
pthread_cond_t* queueNotFull = &queueHandle->queueNotFull;
pthread_mutex_t* mp = &queueHandle->mp;
if (-1 == handle) {
return QUEUE_UNINITIALIZED;
}
ssize_t size;
int ret;
bool notFinished = true;
while (notFinished) {
size = mq_receive(handle, static_cast<char*>(buffer), static_cast<size_t>(capacity),
#ifdef TGT_OS_TYPE_VXWORKS
reinterpret_cast<int*>(&priority));
#else
reinterpret_cast<unsigned int*>(&priority));
#endif
if (-1 == size) { // error
switch (errno) {
case EINTR:
continue;
case EMSGSIZE:
return QUEUE_SIZE_MISMATCH;
case EAGAIN:
if (block == QUEUE_NONBLOCKING) {
// no more messages. If we are
// non-blocking, return
return QUEUE_NO_MORE_MSGS;
} else {
// Go to sleep until we receive a signal that something was put on the queue:
// Note: pthread_cont_wait must be called "with mutex locked by the calling
// thread or undefined behavior results." - from the docs
ret = pthread_mutex_lock(mp);
FW_ASSERT(ret == 0, errno);
ret = pthread_cond_wait(queueNotEmpty, mp);
FW_ASSERT(ret == 0, ret); // If this fails, something horrible happened.
ret = pthread_mutex_unlock(mp);
FW_ASSERT(ret == 0, errno);
continue;
}
break;
default:
return QUEUE_UNKNOWN_ERROR;
}
}
else {
notFinished = false;
// Wake up a thread that might be waiting on the other end of the queue:
ret = pthread_cond_signal(queueNotFull);
FW_ASSERT(ret == 0, ret); // If this fails, something horrible happened.
}
}
actualSize = static_cast<NATIVE_INT_TYPE>(size);
return QUEUE_OK;
}
NATIVE_INT_TYPE Queue::getNumMsgs() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
mqd_t handle = queueHandle->handle;
struct mq_attr attr;
int status = mq_getattr(handle, &attr);
FW_ASSERT(status == 0);
return static_cast<U32>(attr.mq_curmsgs);
}
NATIVE_INT_TYPE Queue::getMaxMsgs() const {
//FW_ASSERT(0);
return 0;
}
NATIVE_INT_TYPE Queue::getQueueSize() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
mqd_t handle = queueHandle->handle;
struct mq_attr attr;
int status = mq_getattr(handle, &attr);
FW_ASSERT(status == 0);
return static_cast<U32>(attr.mq_maxmsg);
}
NATIVE_INT_TYPE Queue::getMsgSize() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
mqd_t handle = queueHandle->handle;
struct mq_attr attr;
int status = mq_getattr(handle, &attr);
FW_ASSERT(status == 0);
return static_cast<U32>(attr.mq_msgsize);
}
}
| cpp |
fprime | data/projects/fprime/Os/Posix/errno.cpp | // ======================================================================
// \title Os/Posix/errno.cpp
// \brief implementation for posix errno conversion
// ======================================================================
#include <cerrno>
#include "Os/Posix/errno.hpp"
namespace Os {
namespace Posix {
File::Status errno_to_file_status(PlatformIntType errno_input) {
File::Status status = File::Status::OP_OK;
switch (errno_input) {
case 0:
status = File::Status::OP_OK;
break;
// Fallthrough intended
case ENOSPC:
case EFBIG:
status = File::Status::NO_SPACE;
break;
case ENOENT:
status = File::Status::DOESNT_EXIST;
break;
// Fallthrough intended
case EPERM:
case EACCES:
status = File::Status::NO_PERMISSION;
break;
case EEXIST:
status = File::Status::FILE_EXISTS;
break;
case EBADF:
status = File::Status::NOT_OPENED;
break;
// Fallthrough intended
case ENOSYS:
case EOPNOTSUPP:
status = File::Status::NOT_SUPPORTED;
break;
case EINVAL:
status = File::Status::INVALID_ARGUMENT;
break;
default:
status = File::Status::OTHER_ERROR;
break;
}
return status;
}
}
}
| cpp |
fprime | data/projects/fprime/Os/Posix/File.hpp | // ======================================================================
// \title Os/Posix/File.hpp
// \brief posix implementation for Os::File, header and test definitions
// ======================================================================
#include <Os/File.hpp>
#ifndef OS_POSIX_FILE_HPP
#define OS_POSIX_FILE_HPP
namespace Os {
namespace Posix {
namespace File {
//! FileHandle class definition for posix implementations.
//!
struct PosixFileHandle : public FileHandle {
static constexpr PlatformIntType INVALID_FILE_DESCRIPTOR = -1;
static constexpr PlatformIntType ERROR_RETURN_VALUE = -1;
//! Posix file descriptor
PlatformIntType m_file_descriptor = INVALID_FILE_DESCRIPTOR;
};
//! \brief posix implementation of Os::File
//!
//! Posix implementation of `FileInterface` for use as a delegate class handling posix file operations. Posix files use
//! standard `open`, `read`, and `write` posix calls. The handle is represented as a `PosixFileHandle` which wraps a
//! single `int` type file descriptor used in those API calls.
//!
class PosixFile : public FileInterface {
public:
//! \brief constructor
//!
PosixFile() = default;
//! \brief copy constructor
PosixFile(const PosixFile& other);
//! \brief assignment operator that copies the internal representation
PosixFile& operator=(const PosixFile& other);
//! \brief destructor
//!
~PosixFile() override = default;
// ------------------------------------
// Functions overrides
// ------------------------------------
//! \brief open file with supplied path and mode
//!
//! Open the file passed in with the given mode. If overwrite is set to OVERWRITE, then opening files in
//! OPEN_CREATE mode will clobber existing files. Set overwrite to NO_OVERWRITE to preserve existing files.
//! The status of the open request is returned from the function call. Delegates to the chosen
//! implementation's `open` function.
//!
//! It is invalid to send `nullptr` as the path.
//! It is invalid to supply `mode` as a non-enumerated value.
//! It is invalid to supply `overwrite` as a non-enumerated value.
//!
//! \param path: c-string of path to open
//! \param mode: file operation mode
//! \param overwrite: overwrite existing file on create
//! \return: status of the open
//!
Os::FileInterface::Status open(const char *path, Mode mode, OverwriteType overwrite) override;
//! \brief close the file, if not opened then do nothing
//!
//! Closes the file, if open. Otherwise this function does nothing. Delegates to the chosen implementation's
//! `closeInternal` function. `mode` is set to `OPEN_NO_MODE`.
//!
void close() override;
//! \brief get size of currently open file
//!
//! Get the size of the currently open file and fill the size parameter. Return status of the operation.
//! \param size: output parameter for size.
//! \return OP_OK on success otherwise error status
//!
Status size(FwSignedSizeType &size_result) override;
//! \brief get file pointer position of the currently open file
//!
//! Get the current position of the read/write pointer of the open file.
//! \param position: output parameter for size.
//! \return OP_OK on success otherwise error status
//!
Status position(FwSignedSizeType &position_result) override;
//! \brief pre-allocate file storage
//!
//! Pre-allocates file storage with at least `length` storage starting at `offset`. No-op on implementations
//! that cannot pre-allocate.
//!
//! It is invalid to pass a negative `offset`.
//! It is invalid to pass a negative `length`.
//!
//! \param offset: offset into file
//! \param length: length after offset to preallocate
//! \return OP_OK on success otherwise error status
//!
Status preallocate(FwSignedSizeType offset, FwSignedSizeType length) override;
//! \brief seek the file pointer to the given offset
//!
//! Seek the file pointer to the given `offset`. If `seekType` is set to `ABSOLUTE` then the offset is calculated
//! from the start of the file, and if it is set to `CURRENT` it is calculated from the current position.
//!
//! \param offset: offset to seek to
//! \param seekType: `ABSOLUTE` for seeking from beginning of file, `CURRENT` to use current position.
//! \return OP_OK on success otherwise error status
//!
Status seek(FwSignedSizeType offset, SeekType seekType) override;
//! \brief flush file contents to storage
//!
//! Flushes the file contents to storage (i.e. out of the OS cache to disk). Does nothing in implementations
//! that do not support flushing.
//!
//! \return OP_OK on success otherwise error status
//!
Status flush() override;
//! \brief read data from this file into supplied buffer bounded by size
//!
//! Read data from this file up to the `size` and store it in `buffer`. When `wait` is set to `WAIT`, this
//! will block until the requested size has been read successfully read or the end of the file has been
//! reached. When `wait` is set to `NO_WAIT` it will return whatever data is currently available.
//!
//! `size` will be updated to the count of bytes actually read. Status will reflect the success/failure of
//! the read operation.
//!
//! It is invalid to pass `nullptr` to this function call.
//! It is invalid to pass a negative `size`.
//! It is invalid to supply wait as a non-enumerated value.
//!
//! \param buffer: memory location to store data read from file
//! \param size: size of data to read
//! \param wait: `WAIT` to wait for data, `NO_WAIT` to return what is currently available
//! \return OP_OK on success otherwise error status
//!
Status read(U8 *buffer, FwSignedSizeType &size, WaitType wait) override;
//! \brief read data from this file into supplied buffer bounded by size
//!
//! Write data to this file up to the `size` from the `buffer`. When `wait` is set to `WAIT`, this
//! will block until the requested size has been written successfully to disk. When `wait` is set to
//! `NO_WAIT` it will return once the data is sent to the OS.
//!
//! `size` will be updated to the count of bytes actually written. Status will reflect the success/failure of
//! the read operation.
//!
//! It is invalid to pass `nullptr` to this function call.
//! It is invalid to pass a negative `size`.
//! It is invalid to supply wait as a non-enumerated value.
//!
//! \param buffer: memory location to store data read from file
//! \param size: size of data to read
//! \param wait: `WAIT` to wait for data to write to disk, `NO_WAIT` to return what is currently available
//! \return OP_OK on success otherwise error status
//!
Status write(const U8 *buffer, FwSignedSizeType &size, WaitType wait) override;
//! \brief returns the raw file handle
//!
//! Gets the raw file handle from the implementation. Note: users must include the implementation specific
//! header to make any real use of this handle. Otherwise it//!must* be passed as an opaque type.
//!
//! \return raw file handle
//!
FileHandle *getHandle() override;
private:
//! File handle for PosixFile
PosixFileHandle m_handle;
};
} // namespace File
} // namespace Posix
} // namespace Os
#endif // OS_POSIX_FILE_HPP
| hpp |
fprime | data/projects/fprime/Os/Posix/IPCQueue.cpp | #include <Fw/Types/Assert.hpp>
#include <Os/Queue.hpp>
#include <Os/IPCQueue.hpp>
#ifdef TGT_OS_TYPE_VXWORKS
#include <vxWorks.h>
#endif
#ifdef TGT_OS_TYPE_LINUX
#include <sys/types.h>
#include <unistd.h>
#endif
#include <mqueue.h>
#include <fcntl.h>
#include <cerrno>
#include <cstring>
#include <cstdio>
#include <ctime>
#include <sys/time.h>
#include <pthread.h>
#include <new>
#define IPC_QUEUE_TIMEOUT_SEC (1)
namespace Os {
class QueueHandle {
public:
QueueHandle(mqd_t m_handle) {
this->handle = m_handle;
}
~QueueHandle() {
// Destroy the handle:
if (-1 != this->handle) {
(void) mq_close(this->handle);
}
}
mqd_t handle;
};
IPCQueue::IPCQueue() : Queue() {
}
Queue::QueueStatus IPCQueue::create(const Fw::StringBase &name, NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize) {
this->m_name = "/QP_";
this->m_name += name;
#ifndef TGT_OS_TYPE_VXWORKS
char pid[40];
(void)snprintf(pid,sizeof(pid),".%d",getpid());
pid[sizeof(pid)-1] = 0;
this->m_name += pid;
#endif
mq_attr att;
mqd_t handle;
memset(&att,0,sizeof(att));
att.mq_maxmsg = depth;
att.mq_msgsize = msgSize;
att.mq_flags = 0;
att.mq_curmsgs = 0;
/* NOTE(mereweth) - O_BLOCK is the default; we use timedsend and
* timedreceive below if QUEUE_NONBLOCKING is specified
*
*/
handle = mq_open(this->m_name.toChar(), O_RDWR | O_CREAT | O_EXCL, 0666, &att);
// If queue already exists, then unlink it and try again.
if (-1 == handle) {
switch (errno) {
case EEXIST:
(void)mq_unlink(this->m_name.toChar());
break;
default:
return QUEUE_UNINITIALIZED;
}
handle = mq_open(this->m_name.toChar(), O_RDWR | O_CREAT | O_EXCL, 0666, &att);
if (-1 == handle) {
return QUEUE_UNINITIALIZED;
}
}
// Set up queue handle:
QueueHandle* queueHandle = new(std::nothrow) QueueHandle(handle);
if (nullptr == queueHandle) {
return QUEUE_UNINITIALIZED;
}
this->m_handle = reinterpret_cast<POINTER_CAST>(queueHandle);
Queue::s_numQueues++;
return QUEUE_OK;
}
IPCQueue::~IPCQueue() {
// Clean up the queue handle:
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
if (nullptr != queueHandle) {
delete queueHandle;
}
this->m_handle = reinterpret_cast<POINTER_CAST>(nullptr); // important so base Queue class doesn't free it
(void) mq_unlink(this->m_name.toChar());
}
Queue::QueueStatus IPCQueue::send(const U8* buffer, NATIVE_INT_TYPE size, NATIVE_INT_TYPE priority, QueueBlocking block) {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
mqd_t handle = queueHandle->handle;
if (-1 == handle) {
return QUEUE_UNINITIALIZED;
}
if (nullptr == buffer) {
return QUEUE_EMPTY_BUFFER;
}
bool keepTrying = true;
while (keepTrying) {
struct timeval now;
gettimeofday(&now,nullptr);
struct timespec wait;
wait.tv_sec = now.tv_sec;
wait.tv_nsec = now.tv_usec * 1000;
if (block == QUEUE_BLOCKING) {
wait.tv_sec += IPC_QUEUE_TIMEOUT_SEC;
}
NATIVE_INT_TYPE stat = mq_timedsend(handle, reinterpret_cast<const char*>(buffer), size, priority, &wait);
if (-1 == stat) {
switch (errno) {
case EINTR:
continue;
case EMSGSIZE:
return QUEUE_SIZE_MISMATCH;
case EINVAL:
return QUEUE_INVALID_PRIORITY;
case ETIMEDOUT:
if (block == QUEUE_NONBLOCKING) {
// no more messages. If we are
// non-blocking, return
return QUEUE_FULL;
} else {
// TODO(mereweth) - multiprocess signalling necessary?
// Go to sleep until we receive a signal that something was taken off the queue
continue;
}
default:
return QUEUE_UNKNOWN_ERROR;
}
} else {
keepTrying=false;
// TODO(mereweth) - multiprocess signalling necessary?
// Wake up a thread that might be waiting on the other end of the queue:
}
}
return QUEUE_OK;
}
Queue::QueueStatus IPCQueue::receive(U8* buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE &actualSize, NATIVE_INT_TYPE &priority, QueueBlocking block) {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
mqd_t handle = queueHandle->handle;
if (-1 == handle) {
return QUEUE_UNINITIALIZED;
}
ssize_t size;
bool notFinished = true;
while (notFinished) {
struct timeval now;
gettimeofday(&now,nullptr);
struct timespec wait;
wait.tv_sec = now.tv_sec;
wait.tv_nsec = now.tv_usec * 1000;
if (block == QUEUE_BLOCKING) {
wait.tv_sec += IPC_QUEUE_TIMEOUT_SEC;
}
size = mq_timedreceive(handle, reinterpret_cast<char*>(buffer), static_cast<size_t>(capacity),
#ifdef TGT_OS_TYPE_VXWORKS
reinterpret_cast<int*>(&priority), &wait);
#else
reinterpret_cast<unsigned int*>(&priority), &wait);
#endif
if (-1 == size) { // error
switch (errno) {
case EINTR:
continue;
case EMSGSIZE:
return QUEUE_SIZE_MISMATCH;
case ETIMEDOUT:
if (block == QUEUE_NONBLOCKING) {
// no more messages. If we are
// non-blocking, return
return QUEUE_NO_MORE_MSGS;
} else {
// TODO(mereweth) - multiprocess signalling necessary?
// Go to sleep until we receive a signal that something was put on the queue:
continue;
}
break;
default:
return QUEUE_UNKNOWN_ERROR;
}
}
else {
notFinished = false;
// TODO(mereweth) - multiprocess signalling necessary?
// Wake up a thread that might be waiting on the other end of the queue
}
}
actualSize = static_cast<NATIVE_INT_TYPE>(size);
return QUEUE_OK;
}
NATIVE_INT_TYPE IPCQueue::getNumMsgs() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
mqd_t handle = queueHandle->handle;
struct mq_attr attr;
int status = mq_getattr(handle, &attr);
FW_ASSERT(status == 0);
return static_cast<U32>(attr.mq_curmsgs);
}
NATIVE_INT_TYPE IPCQueue::getMaxMsgs() const {
//FW_ASSERT(0);
return 0;
}
NATIVE_INT_TYPE IPCQueue::getQueueSize() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
mqd_t handle = queueHandle->handle;
struct mq_attr attr;
int status = mq_getattr(handle, &attr);
FW_ASSERT(status == 0);
return static_cast<U32>(attr.mq_maxmsg);
}
NATIVE_INT_TYPE IPCQueue::getMsgSize() const {
QueueHandle* queueHandle = reinterpret_cast<QueueHandle*>(this->m_handle);
mqd_t handle = queueHandle->handle;
struct mq_attr attr;
int status = mq_getattr(handle, &attr);
FW_ASSERT(status == 0);
return static_cast<U32>(attr.mq_msgsize);
}
}
| cpp |
fprime | data/projects/fprime/Os/Posix/errno.hpp | // ======================================================================
// \title Os/Posix/errno.hpp
// \brief header for posix errno conversion
// ======================================================================
#include "Os/File.hpp"
#ifndef OS_POSIX_ERRNO_HPP
#define OS_POSIX_ERRNO_HPP
namespace Os {
namespace Posix {
//! Convert an errno representation of an error to the Os::File::Status representation.
//! \param errno: errno representation of the error
//! \return: Os::File::Status representation of the error
//!
Os::File::Status errno_to_file_status(PlatformIntType errno_input);
}
}
#endif
| hpp |
fprime | data/projects/fprime/Os/Posix/DefaultFile.cpp | // ======================================================================
// \title Os/Posix/DefaultFile.cpp
// \brief sets default Os::File to posix implementation via linker
// ======================================================================
#include "Os/File.hpp"
#include "Os/Posix/File.hpp"
#include "Fw/Types/Assert.hpp"
#include <new>
namespace Os {
//! \brief get implementation file interface for use as delegate
//!
//! Added via linker to ensure that the posix implementation of Os::File is the default.
//!
//! \param aligned_placement_new_memory: memory to placement-new into
//! \return FileInterface pointer result of placement new
//!
FileInterface* FileInterface::getDelegate(U8* aligned_placement_new_memory, const FileInterface* to_copy) {
FW_ASSERT(aligned_placement_new_memory != nullptr);
const Os::Posix::File::PosixFile* copy_me = reinterpret_cast<const Os::Posix::File::PosixFile*>(to_copy);
// Placement-new the file handle into the opaque file-handle storage
static_assert(sizeof(Os::Posix::File::PosixFile) <= sizeof Os::File::m_handle_storage,
"Handle size not large enough");
static_assert((FW_HANDLE_ALIGNMENT % alignof(Os::Posix::File::PosixFile)) == 0, "Handle alignment invalid");
Os::Posix::File::PosixFile *interface = nullptr;
if (to_copy == nullptr) {
interface = new(aligned_placement_new_memory) Os::Posix::File::PosixFile;
} else {
interface = new(aligned_placement_new_memory) Os::Posix::File::PosixFile(*copy_me);
}
FW_ASSERT(interface != nullptr);
return interface;
}
}
| cpp |
fprime | data/projects/fprime/Os/Posix/Task.cpp | #include <Os/Task.hpp>
#include <Fw/Types/Assert.hpp>
#include <pthread.h>
#include <cerrno>
#include <cstring>
#include <ctime>
#include <cstdio>
#include <new>
#include <sched.h>
#include <climits>
#include <Fw/Logger/Logger.hpp>
#ifdef TGT_OS_TYPE_LINUX
#include <features.h>
#endif
static const NATIVE_INT_TYPE SCHED_POLICY = SCHED_RR;
typedef void* (*pthread_func_ptr)(void*);
void* pthread_entry_wrapper(void* arg) {
FW_ASSERT(arg);
Os::Task::TaskRoutineWrapper *task = reinterpret_cast<Os::Task::TaskRoutineWrapper*>(arg);
FW_ASSERT(task->routine);
task->routine(task->arg);
return nullptr;
}
namespace Os {
void validate_arguments(NATIVE_UINT_TYPE& priority, NATIVE_UINT_TYPE& stack, NATIVE_UINT_TYPE& affinity, bool expect_perm) {
const NATIVE_INT_TYPE min_priority = sched_get_priority_min(SCHED_POLICY);
const NATIVE_INT_TYPE max_priority = sched_get_priority_max(SCHED_POLICY);
// Check to ensure that these calls worked. -1 is an error
if (min_priority < 0 or max_priority < 0) {
Fw::Logger::logMsg("[WARNING] Unable to determine min/max priority with error %s. Discarding priority.\n", reinterpret_cast<POINTER_CAST>(strerror(errno)));
priority = Os::Task::TASK_DEFAULT;
}
// Check priority attributes
if (!expect_perm and priority != Task::TASK_DEFAULT) {
Fw::Logger::logMsg("[WARNING] Task priority set and permissions unavailable. Discarding priority.\n");
priority = Task::TASK_DEFAULT; //Action: use constant
}
if (priority != Task::TASK_DEFAULT and priority < static_cast<Task::ParamType>(min_priority)) {
Fw::Logger::logMsg("[WARNING] Low task priority of %d being clamped to %d\n", priority, min_priority);
priority = min_priority;
}
if (priority != Task::TASK_DEFAULT and priority > static_cast<Task::ParamType>(max_priority)) {
Fw::Logger::logMsg("[WARNING] High task priority of %d being clamped to %d\n", priority, max_priority);
priority = max_priority;
}
// Check the stack
if (stack != Task::TASK_DEFAULT and stack < PTHREAD_STACK_MIN) {
Fw::Logger::logMsg("[WARNING] Stack size %d too small, setting to minimum of %d\n", stack, PTHREAD_STACK_MIN);
stack = PTHREAD_STACK_MIN;
}
// Check CPU affinity
if (!expect_perm and affinity != Task::TASK_DEFAULT) {
Fw::Logger::logMsg("[WARNING] Cpu affinity set and permissions unavailable. Discarding affinity.\n");
affinity = Task::TASK_DEFAULT;
}
}
Task::TaskStatus set_stack_size(pthread_attr_t& att, NATIVE_UINT_TYPE stack) {
// Set the stack size, if it has been supplied
if (stack != Task::TASK_DEFAULT) {
I32 stat = pthread_attr_setstacksize(&att, stack);
if (stat != 0) {
Fw::Logger::logMsg("pthread_attr_setstacksize: %s\n", reinterpret_cast<POINTER_CAST>(strerror(stat)));
return Task::TASK_INVALID_STACK;
}
}
return Task::TASK_OK;
}
Task::TaskStatus set_priority_params(pthread_attr_t& att, NATIVE_UINT_TYPE priority) {
if (priority != Task::TASK_DEFAULT) {
I32 stat = pthread_attr_setschedpolicy(&att, SCHED_POLICY);
if (stat != 0) {
Fw::Logger::logMsg("pthread_attr_setschedpolicy: %s\n", reinterpret_cast<POINTER_CAST>(strerror(stat)));
return Task::TASK_INVALID_PARAMS;
}
stat = pthread_attr_setinheritsched(&att, PTHREAD_EXPLICIT_SCHED);
if (stat != 0) {
Fw::Logger::logMsg("pthread_attr_setinheritsched: %s\n",
reinterpret_cast<POINTER_CAST>(strerror(stat)));
return Task::TASK_INVALID_PARAMS;
}
sched_param schedParam;
memset(&schedParam, 0, sizeof(sched_param));
schedParam.sched_priority = priority;
stat = pthread_attr_setschedparam(&att, &schedParam);
if (stat != 0) {
Fw::Logger::logMsg("pthread_attr_setschedparam: %s\n", reinterpret_cast<POINTER_CAST>(strerror(stat)));
return Task::TASK_INVALID_PARAMS;
}
}
return Task::TASK_OK;
}
Task::TaskStatus set_cpu_affinity(pthread_attr_t& att, NATIVE_UINT_TYPE cpuAffinity) {
if (cpuAffinity != Task::TASK_DEFAULT) {
#if TGT_OS_TYPE_LINUX && __GLIBC__
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(cpuAffinity, &cpuset);
I32 stat = pthread_attr_setaffinity_np(&att, sizeof(cpu_set_t), &cpuset);
if (stat != 0) {
Fw::Logger::logMsg("pthread_setaffinity_np: %i %s\n", cpuAffinity,
reinterpret_cast<POINTER_CAST>(strerror(stat)));
return Task::TASK_INVALID_PARAMS;
}
#elif TGT_OS_TYPE_LINUX
Fw::Logger::logMsg("[WARNING] Setting CPU affinity is only available on Linux with glibc\n");
#else
Fw::Logger::logMsg("[WARNING] Setting CPU affinity is only available on Linux\n");
#endif
}
return Task::TASK_OK;
}
Task::TaskStatus create_pthread(NATIVE_UINT_TYPE priority, NATIVE_UINT_TYPE stackSize, NATIVE_UINT_TYPE cpuAffinity, pthread_t*& tid, void* arg, bool expect_perm) {
Task::TaskStatus tStat = Task::TASK_OK;
validate_arguments(priority, stackSize, cpuAffinity, expect_perm);
pthread_attr_t att;
memset(&att,0, sizeof(att));
I32 stat = pthread_attr_init(&att);
if (stat != 0) {
Fw::Logger::logMsg("pthread_attr_init: (%d): %s\n", stat, reinterpret_cast<POINTER_CAST>(strerror(stat)));
return Task::TASK_INVALID_PARAMS;
}
// Handle setting stack size
tStat = set_stack_size(att, stackSize);
if (tStat != Task::TASK_OK) {
return tStat;
}
// Handle non-zero priorities
tStat = set_priority_params(att, priority);
if (tStat != Task::TASK_OK) {
return tStat;
}
// Set affinity before creating thread:
tStat = set_cpu_affinity(att, cpuAffinity);
if (tStat != Task::TASK_OK) {
return tStat;
}
tid = new pthread_t;
const char* message = nullptr;
stat = pthread_create(tid, &att, pthread_entry_wrapper, arg);
switch (stat) {
// Success, do nothing
case 0:
break;
case EINVAL:
message = "Invalid thread attributes specified";
tStat = Task::TASK_INVALID_PARAMS;
break;
case EPERM:
message = "Insufficient permissions to create thread. May not set thread priority without permission";
tStat = Task::TASK_ERROR_PERMISSION;
break;
case EAGAIN:
message = "Unable to allocate thread. Increase thread ulimit.";
tStat = Task::TASK_ERROR_RESOURCES;
break;
default:
message = "Unknown error";
tStat = Task::TASK_UNKNOWN_ERROR;
break;
}
(void)pthread_attr_destroy(&att);
if (stat != 0) {
delete tid;
tid = nullptr;
Fw::Logger::logMsg("pthread_create: %s. %s\n", reinterpret_cast<POINTER_CAST>(message), reinterpret_cast<POINTER_CAST>(strerror(stat)));
return tStat;
}
return Task::TASK_OK;
}
Task::Task() : m_handle(reinterpret_cast<POINTER_CAST>(nullptr)), m_identifier(0), m_affinity(-1), m_started(false), m_suspendedOnPurpose(false), m_routineWrapper() {
}
Task::TaskStatus Task::start(const Fw::StringBase &name, taskRoutine routine, void* arg, ParamType priority, ParamType stackSize, ParamType cpuAffinity, ParamType identifier) {
FW_ASSERT(routine);
this->m_name = "TP_";
this->m_name += name;
this->m_identifier = identifier;
// Setup functor wrapper parameters
this->m_routineWrapper.routine = routine;
this->m_routineWrapper.arg = arg;
pthread_t* tid;
// Try to create thread with assuming permissions
TaskStatus status = create_pthread(priority, stackSize, cpuAffinity, tid, &this->m_routineWrapper, true);
// Failure due to permission automatically retried
if (status == TASK_ERROR_PERMISSION) {
Fw::Logger::logMsg("[WARNING] Insufficient Permissions:\n");
Fw::Logger::logMsg("[WARNING] Insufficient permissions to set task priority or set task CPU affinity on task %s. Creating task without priority nor affinity.\n", reinterpret_cast<POINTER_CAST>(m_name.toChar()));
Fw::Logger::logMsg("[WARNING] Please use no-argument <component>.start() calls, set priority/affinity to TASK_DEFAULT or ensure user has correct permissions for operating system.\n");
Fw::Logger::logMsg("[WARNING] Note: future releases of fprime will fail when setting priority/affinity without sufficient permissions \n");
Fw::Logger::logMsg("\n");
status = create_pthread(priority, stackSize, cpuAffinity, tid, &this->m_routineWrapper, false); // Fallback with no permission
}
// Check for non-zero error code
if (status != TASK_OK) {
return status;
}
FW_ASSERT(tid != nullptr);
// Handle a successfully created task
this->m_handle = reinterpret_cast<POINTER_CAST>(tid);
Task::s_numTasks++;
// If a registry has been registered, register task
if (Task::s_taskRegistry) {
Task::s_taskRegistry->addTask(this);
}
return status;
}
Task::TaskStatus Task::delay(NATIVE_UINT_TYPE milliseconds)
{
timespec time1;
time1.tv_sec = milliseconds/1000;
time1.tv_nsec = (milliseconds%1000)*1000000;
timespec time2;
time2.tv_sec = 0;
time2.tv_nsec = 0;
timespec* sleepTimePtr = &time1;
timespec* remTimePtr = &time2;
while (true) {
int stat = nanosleep(sleepTimePtr,remTimePtr);
if (0 == stat) {
return TASK_OK;
} else { // check errno
if (EINTR == errno) { // swap pointers
timespec* temp = remTimePtr;
remTimePtr = sleepTimePtr;
sleepTimePtr = temp;
continue; // if interrupted, just continue
} else {
return TASK_DELAY_ERROR;
}
}
}
return TASK_OK; // for coverage analysis
}
Task::~Task() {
if (this->m_handle) {
delete reinterpret_cast<pthread_t*>(this->m_handle);
}
// If a registry has been registered, remove task
if (Task::s_taskRegistry) {
Task::s_taskRegistry->removeTask(this);
}
}
// Note: not implemented for Posix threads. Must be manually done using a mutex or other blocking construct as there
// is not top-level pthreads support for suspend and resume.
void Task::suspend(bool onPurpose) {
FW_ASSERT(0);
}
void Task::resume() {
FW_ASSERT(0);
}
bool Task::isSuspended() {
FW_ASSERT(0);
return false;
}
TaskId Task::getOsIdentifier() {
TaskId T;
return T;
}
Task::TaskStatus Task::join(void **value_ptr) {
NATIVE_INT_TYPE stat = 0;
if (!(this->m_handle)) {
return TASK_JOIN_ERROR;
}
stat = pthread_join(*reinterpret_cast<pthread_t*>(this->m_handle), value_ptr);
if (stat != 0) {
return TASK_JOIN_ERROR;
}
else {
return TASK_OK;
}
}
}
| cpp |
fprime | data/projects/fprime/Os/Posix/Mutex.cpp | #include <Os/Mutex.hpp>
#include <pthread.h>
#include <Fw/Types/Assert.hpp>
#include <new>
namespace Os {
Mutex::Mutex() {
pthread_mutex_t* handle = new(std::nothrow) pthread_mutex_t;
FW_ASSERT(handle != nullptr);
// set attributes
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
NATIVE_INT_TYPE stat;
// set to error checking
// stat = pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_ERRORCHECK);
// FW_ASSERT(stat == 0,stat);
// set to normal mutex type
stat = pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_NORMAL);
FW_ASSERT(stat == 0,stat);
// set to check for priority inheritance
stat = pthread_mutexattr_setprotocol(&attr,PTHREAD_PRIO_INHERIT);
FW_ASSERT(stat == 0,stat);
stat = pthread_mutex_init(handle,&attr);
FW_ASSERT(stat == 0,stat);
this->m_handle = reinterpret_cast<POINTER_CAST>(handle);
}
Mutex::~Mutex() {
NATIVE_INT_TYPE stat = pthread_mutex_destroy(reinterpret_cast<pthread_mutex_t*>(this->m_handle));
FW_ASSERT(stat == 0,stat);
delete reinterpret_cast<pthread_mutex_t*>(this->m_handle);
}
void Mutex::lock() {
NATIVE_INT_TYPE stat = pthread_mutex_lock(reinterpret_cast<pthread_mutex_t*>(this->m_handle));
FW_ASSERT(stat == 0,stat);
}
void Mutex::unLock() {
NATIVE_INT_TYPE stat = pthread_mutex_unlock(reinterpret_cast<pthread_mutex_t*>(this->m_handle));
FW_ASSERT(stat == 0,stat);
}
}
| cpp |
fprime | data/projects/fprime/Os/Posix/test/ut/PosixFileTests.cpp | // ======================================================================
// \title Os/Posix/test/ut/PosixFileTests.cpp
// \brief tests for posix implementation for Os::File
// ======================================================================
#include <gtest/gtest.h>
#include <unistd.h>
#include <list>
#include "Os/File.hpp"
#include "Os/Posix/File.hpp"
#include "Os/test/ut/file/CommonTests.hpp"
#include "STest/Pick/Pick.hpp"
#include <cstdio>
#include <csignal>
namespace Os {
namespace Test {
namespace File {
std::vector<std::shared_ptr<const std::string> > FILES;
static const U32 MAX_FILES = 100;
static const char BASE_PATH[] = "/tmp/fprime";
static const char TEST_FILE[] = "fprime-os-file-test";
//! Check if we can use the file. F_OK file exists, R_OK, W_OK are read and write.
//! \return true if it exists, false otherwise.
//!
bool check_permissions(const char* path, int permission) {
return ::access(path, permission) == 0;
}
//! Get a filename, randomly if random is true, otherwise use a basic filename.
//! \param random: true if filename should be random, false if predictable
//! \return: filename to use for testing
//!
std::shared_ptr<std::string> get_test_filename(bool random) {
const char* filename = TEST_FILE;
char full_buffer[PATH_MAX];
char buffer[PATH_MAX - sizeof(BASE_PATH)];
// When random, select random characters
if (random) {
filename = buffer;
size_t i = 0;
for (i = 0; i < STest::Pick::lowerUpper(1, (sizeof buffer) - 1); i++) {
char selected_character = static_cast<char>(STest::Pick::lowerUpper(32, 126));
selected_character =
(selected_character == '/') ? static_cast<char>(selected_character + 1) : selected_character;
buffer[i] = selected_character;
}
buffer[i] = 0; // Terminate random string
}
(void) snprintf(full_buffer, PATH_MAX, "%s/%s", BASE_PATH, filename);
// Create a shared pointer wrapping our filename buffer
std::shared_ptr<std::string> pointer(new std::string(full_buffer), std::default_delete<std::string>());
return pointer;
}
//! Clean-up the files created during this test.
//!
void cleanup(int signal) {
// Ensure the test files are removed only when the test was run
for (const auto& val : FILES) {
if (check_permissions(val->c_str(), F_OK)) {
::unlink(val->c_str());
}
}
FILES.clear();
}
//! Set up for the test ensures that the test can run at all
//!
void setUp(bool requires_io) {
std::shared_ptr<std::string> non_random_filename = get_test_filename(false);
int result = mkdir(BASE_PATH, 0777);
// Check that we could make the directory for test files
if (result != 0 && errno != EEXIST) {
GTEST_SKIP() << "Cannot make directory for test files: " << strerror(errno);
}
// IO required and test file exists then skip
else if (check_permissions(non_random_filename->c_str(), F_OK)) {
GTEST_SKIP() << "Test file exists: " << non_random_filename->c_str();
}
// IO required and cannot read/write to BASE_PATH then skip
else if (requires_io && not check_permissions(BASE_PATH, R_OK & W_OK)) {
GTEST_SKIP() << "Cannot read/write in directory: " << BASE_PATH;
}
int signals[] = {SIGQUIT, SIGABRT, SIGTERM, SIGINT, SIGHUP};
for (unsigned long i = 0; i < FW_NUM_ARRAY_ELEMENTS(signals); i++) {
// Could not register signal handler
if (signal(SIGQUIT, cleanup) == SIG_ERR) {
GTEST_SKIP() << "Cannot register signal handler for cleanup";
}
}
}
//! Tear down for the tests cleans up the test file used
//!
void tearDown() {
cleanup(0);
}
class PosixTester : public Tester {
//! Check if the test file exists.
//! \return true if it exists, false otherwise.
//!
bool exists(const std::string& filename) const override {
bool exits = check_permissions(filename.c_str(), F_OK);
return exits;
}
//! Get a filename, randomly if random is true, otherwise use a basic filename.
//! \param random: true if filename should be random, false if predictable
//! \return: filename to use for testing
//!
std::shared_ptr<const std::string> get_filename(bool random) const override {
U32 pick = STest::Pick::lowerUpper(0, MAX_FILES);
if (random && pick < FILES.size()) {
return FILES[pick];
}
std::shared_ptr<const std::string> filename = get_test_filename(random);
FILES.push_back(filename);
return filename;
}
//! Posix tester is fully functional
//! \return true
//!
bool functional() const override{
return true;
}
};
std::unique_ptr<Os::Test::File::Tester> get_tester_implementation() {
return std::unique_ptr<Os::Test::File::Tester>(new Os::Test::File::PosixTester());
}
} // namespace File
} // namespace Test
} // namespace Os
int main(int argc, char** argv) {
STest::Random::seed();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/Os/Baremetal/File.cpp | #include <FpConfig.hpp>
#include <Os/File.hpp>
#include <Fw/Types/Assert.hpp>
namespace Os {
File::File() :m_fd(0),m_mode(OPEN_NO_MODE),m_lastError(0) {}
File::~File() {}
File::Status File::open(const char* fileName, File::Mode mode) {
return NOT_OPENED;
}
File::Status File::open(const char* fileName, File::Mode mode, bool include_excl) {
return NOT_OPENED;
}
bool File::isOpen() {
return false;
}
File::Status File::seek(NATIVE_INT_TYPE offset, bool absolute) {
return NOT_OPENED;
}
File::Status File::read(void * buffer, NATIVE_INT_TYPE &size, bool waitForFull) {
return NOT_OPENED;
}
File::Status File::write(const void * buffer, NATIVE_INT_TYPE &size, bool waitForDone) {
return NOT_OPENED;
}
void File::close() {}
NATIVE_INT_TYPE File::getLastError() {
return 0;
}
const char* File::getLastErrorString() {
return "FileBad";
}
}
| cpp |
fprime | data/projects/fprime/Os/Baremetal/IntervalTimer.cpp | #include <Os/IntervalTimer.hpp>
#include <Fw/Types/Assert.hpp>
namespace Os {
void IntervalTimer::getRawTime(RawTime& time) {
time.lower = 0;
time.upper = 0;
}
U32 IntervalTimer::getDiffUsec(const RawTime& t1In, const RawTime& t2In) {
return 0;
}
}
| cpp |
fprime | data/projects/fprime/Os/Baremetal/Queue.cpp | // ======================================================================
// \title Queue.cpp
// \author mstarch, borrowed from @dinkel
// \brief Queue implementation for Baremetal devices. No IPC nor thread
// safety is implemented as this intended for baremetal devices.
// Based on Os/Pthreads/Queue.cpp from @dinkel
// ======================================================================
#include <FpConfig.hpp>
#include <Os/Pthreads/BufferQueue.hpp>
#include <Fw/Types/Assert.hpp>
#include <Os/Queue.hpp>
#include <new>
#include <cstdio>
namespace Os {
/**
* Wrapper class used to convert the BufferQueue into a "handler" used by
* the Queue class.
*/
class BareQueueHandle {
public:
BareQueueHandle() : m_init(false) {}
/**
* Create a new queue for use in the system.
* WARNING: this **must** be called during initialization.
*/
bool create(NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize) {
bool ret = m_queue.create(depth, msgSize);
m_init = ret;
return ret;
}
bool m_init;
//!< Actual queue used to store
BufferQueue m_queue;
};
Queue::Queue() :
m_handle(reinterpret_cast<POINTER_CAST>(nullptr))
{ }
Queue::QueueStatus Queue::createInternal(const Fw::StringBase &name, NATIVE_INT_TYPE depth, NATIVE_INT_TYPE msgSize) {
BareQueueHandle* handle = reinterpret_cast<BareQueueHandle*>(this->m_handle);
// Queue has already been created... remove it and try again:
if (nullptr != handle) {
delete handle;
handle = nullptr;
}
//New queue handle, check for success or return error
handle = new(std::nothrow) BareQueueHandle;
if (nullptr == handle || !handle->create(depth, msgSize)) {
return QUEUE_UNINITIALIZED;
}
//Set handle member variable
this->m_handle = reinterpret_cast<POINTER_CAST>(handle);
//Register the queue
#if FW_QUEUE_REGISTRATION
if (this->s_queueRegistry) {
this->s_queueRegistry->regQueue(this);
}
#endif
return QUEUE_OK;
}
Queue::~Queue() {
// Clean up the queue handle:
BareQueueHandle* handle = reinterpret_cast<BareQueueHandle*>(this->m_handle);
if (nullptr != handle) {
delete handle;
}
this->m_handle = reinterpret_cast<POINTER_CAST>(nullptr);
}
Queue::QueueStatus bareSendNonBlock(BareQueueHandle& handle, const U8* buffer, NATIVE_INT_TYPE size, NATIVE_INT_TYPE priority) {
FW_ASSERT(handle.m_init);
BufferQueue& queue = handle.m_queue;
Queue::QueueStatus status = Queue::QUEUE_OK;
// Push item onto queue:
bool success = queue.push(buffer, size, priority);
if(!success) {
status = Queue::QUEUE_FULL;
}
return status;
}
Queue::QueueStatus bareSendBlock(BareQueueHandle& handle, const U8* buffer, NATIVE_INT_TYPE size, NATIVE_INT_TYPE priority) {
FW_ASSERT(handle.m_init);
BufferQueue& queue = handle.m_queue;
// If the queue is full, wait until a message is taken off the queue.
while(queue.isFull()) {
//Forced to assert, as blocking would destroy timely-ness
FW_ASSERT(false);
}
// Push item onto queue:
bool success = queue.push(buffer, size, priority);
// The only reason push would not succeed is if the queue
// was full. Since we waited for the queue to NOT be full
// before sending on the queue, the push must have succeeded
// unless there was a programming error or a bit flip.
FW_ASSERT(success, success);
return Queue::QUEUE_OK;
}
Queue::QueueStatus Queue::send(const U8* buffer, NATIVE_INT_TYPE size, NATIVE_INT_TYPE priority, QueueBlocking block) {
//Check if the handle is null or check the underlying queue is null
if ((nullptr == reinterpret_cast<BareQueueHandle*>(this->m_handle)) ||
(!reinterpret_cast<BareQueueHandle*>(this->m_handle)->m_init)) {
return QUEUE_UNINITIALIZED;
}
BareQueueHandle& handle = *reinterpret_cast<BareQueueHandle*>(this->m_handle);
BufferQueue& queue = handle.m_queue;
//Check that the buffer is non-null
if (nullptr == buffer) {
return QUEUE_EMPTY_BUFFER;
}
//Fail if there is a size miss-match
if (size < 0 || static_cast<NATIVE_UINT_TYPE>(size) > queue.getMsgSize()) {
return QUEUE_SIZE_MISMATCH;
}
//Send to the queue
if( QUEUE_NONBLOCKING == block ) {
return bareSendNonBlock(handle, buffer, size, priority);
}
return bareSendBlock(handle, buffer, size, priority);
}
Queue::QueueStatus bareReceiveNonBlock(BareQueueHandle& handle, U8* buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE &actualSize, NATIVE_INT_TYPE &priority) {
FW_ASSERT(handle.m_init);
BufferQueue& queue = handle.m_queue;
NATIVE_UINT_TYPE size = static_cast<NATIVE_UINT_TYPE>(capacity);
NATIVE_INT_TYPE pri = 0;
Queue::QueueStatus status = Queue::QUEUE_OK;
// Get an item off of the queue:
bool success = queue.pop(buffer, size, pri);
if(success) {
// Pop worked - set the return size and priority:
actualSize = static_cast<NATIVE_INT_TYPE>(size);
priority = pri;
}
else {
actualSize = 0;
if( size > static_cast<NATIVE_UINT_TYPE>(capacity) ) {
// The buffer capacity was too small!
status = Queue::QUEUE_SIZE_MISMATCH;
}
else if( size == 0 ) {
// The queue is empty:
status = Queue::QUEUE_NO_MORE_MSGS;
}
else {
// If this happens, a programming error or bit flip occurred:
FW_ASSERT(0);
}
}
return status;
}
Queue::QueueStatus bareReceiveBlock(BareQueueHandle& handle, U8* buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE &actualSize, NATIVE_INT_TYPE &priority) {
FW_ASSERT(handle.m_init);
BufferQueue& queue = handle.m_queue;
NATIVE_UINT_TYPE size = static_cast<NATIVE_UINT_TYPE>(capacity);
NATIVE_INT_TYPE pri = 0;
Queue::QueueStatus status = Queue::QUEUE_OK;
// If the queue is full, wait until a message is taken off the queue.
while(queue.isEmpty()) {
//Forced to assert, as blocking would destroy timely-ness
FW_ASSERT(false);
}
// Get an item off of the queue:
bool success = queue.pop(buffer, size, pri);
if(success) {
// Pop worked - set the return size and priority:
actualSize = static_cast<NATIVE_INT_TYPE>(size);
priority = pri;
}
else {
actualSize = 0;
if( size > (static_cast<NATIVE_UINT_TYPE>(capacity)) ) {
// The buffer capacity was too small!
status = Queue::QUEUE_SIZE_MISMATCH;
}
else {
// If this happens, a programming error or bit flip occurred:
// The only reason a pop should fail is if the user's buffer
// was too small.
FW_ASSERT(0);
}
}
return status;
}
Queue::QueueStatus Queue::receive(U8* buffer, NATIVE_INT_TYPE capacity, NATIVE_INT_TYPE &actualSize, NATIVE_INT_TYPE &priority, QueueBlocking block) {
//Check if the handle is null or check the underlying queue is null
if ((nullptr == reinterpret_cast<BareQueueHandle*>(this->m_handle)) ||
(!reinterpret_cast<BareQueueHandle*>(this->m_handle)->m_init)) {
return QUEUE_UNINITIALIZED;
}
BareQueueHandle& handle = *reinterpret_cast<BareQueueHandle*>(this->m_handle);
//Check the buffer can hold the out-going message
if (capacity < this->getMsgSize()) {
return QUEUE_SIZE_MISMATCH;
}
//Receive either non-blocking or blocking
if(QUEUE_NONBLOCKING == block) {
return bareReceiveNonBlock(handle, buffer, capacity, actualSize, priority);
}
return bareReceiveBlock(handle, buffer, capacity, actualSize, priority);
}
NATIVE_INT_TYPE Queue::getNumMsgs() const {
//Check if the handle is null or check the underlying queue is null
if ((nullptr == reinterpret_cast<BareQueueHandle*>(this->m_handle)) ||
(!reinterpret_cast<BareQueueHandle*>(this->m_handle)->m_init)) {
return 0;
}
BareQueueHandle& handle = *reinterpret_cast<BareQueueHandle*>(this->m_handle);
BufferQueue& queue = handle.m_queue;
return queue.getCount();
}
NATIVE_INT_TYPE Queue::getMaxMsgs() const {
//Check if the handle is null or check the underlying queue is null
if ((nullptr == reinterpret_cast<BareQueueHandle*>(this->m_handle)) ||
(!reinterpret_cast<BareQueueHandle*>(this->m_handle)->m_init)) {
return 0;
}
BareQueueHandle& handle = *reinterpret_cast<BareQueueHandle*>(this->m_handle);
BufferQueue& queue = handle.m_queue;
return queue.getMaxCount();
}
NATIVE_INT_TYPE Queue::getQueueSize() const {
//Check if the handle is null or check the underlying queue is null
if ((nullptr == reinterpret_cast<BareQueueHandle*>(this->m_handle)) ||
(!reinterpret_cast<BareQueueHandle*>(this->m_handle)->m_init)) {
return 0;
}
BareQueueHandle& handle = *reinterpret_cast<BareQueueHandle*>(this->m_handle);
BufferQueue& queue = handle.m_queue;
return queue.getDepth();
}
NATIVE_INT_TYPE Queue::getMsgSize() const {
//Check if the handle is null or check the underlying queue is null
if ((nullptr == reinterpret_cast<BareQueueHandle*>(this->m_handle)) ||
(!reinterpret_cast<BareQueueHandle*>(this->m_handle)->m_init)) {
return 0;
}
BareQueueHandle& handle = *reinterpret_cast<BareQueueHandle*>(this->m_handle);
BufferQueue& queue = handle.m_queue;
return queue.getMsgSize();
}
}//Namespace Os
| cpp |
fprime | data/projects/fprime/Os/Baremetal/SystemResources.cpp | // ======================================================================
// \title Baremetal/SystemResources.cpp
// \author mstarch
// \brief cpp file for SystemResources component implementation class
//
// \copyright
// Copyright 2021, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include <Os/SystemResources.hpp>
namespace Os {
SystemResources::SystemResourcesStatus SystemResources::getCpuCount(U32& cpuCount) {
// Assumes 1 CPU
cpuCount = 1;
return SYSTEM_RESOURCES_OK;
}
SystemResources::SystemResourcesStatus SystemResources::getCpuTicks(CpuTicks& cpu_ticks, U32 cpu_index) {
// Always 100 percent
cpu_ticks.used = 1;
cpu_ticks.total = 1;
return SYSTEM_RESOURCES_OK;
}
SystemResources::SystemResourcesStatus SystemResources::getMemUtil(MemUtil& memory_util) {
// Always 100 percent
memory_util.total = 1;
memory_util.used = 1;
return SYSTEM_RESOURCES_OK;
}
} // namespace Os
| cpp |
fprime | data/projects/fprime/Os/Baremetal/FileSystem.cpp | #include <FpConfig.hpp>
#include <Fw/Types/Assert.hpp>
#include <Os/File.hpp>
#include <Os/FileSystem.hpp>
namespace Os {
namespace FileSystem {
Status createDirectory(const char* path) {
return NO_SPACE;
} // end createDirectory
Status removeDirectory(const char* path) {
return INVALID_PATH;
} // end removeDirectory
Status readDirectory(const char* path, const U32 maxNum, Fw::String fileArray[], U32& numFiles) {
numFiles = 0;
return OTHER_ERROR;
} // end readDirectory
Status removeFile(const char* path) {
return OTHER_ERROR;
} // end removeFile
Status moveFile(const char* originPath, const char* destPath) {
return OTHER_ERROR;
} // end moveFile
Status handleFileError(File::Status fileStatus) {
return OTHER_ERROR;
} // end handleFileError
Status copyFile(const char* originPath, const char* destPath) {
return OTHER_ERROR;
} // end copyFile
Status getFileSize(const char* path, FwSizeType& size) {
return OTHER_ERROR;
} // end getFileSize
Status changeWorkingDirectory(const char* path) {
return OTHER_ERROR;
} // end changeWorkingDirectory
// Public function to get the file count for a given directory.
Status getFileCount(const char* directory, U32& fileCount) {
return OTHER_ERROR;
} // end getFileCount
Status appendFile(const char* originPath, const char* destPath, bool createMissingDest) {
return OTHER_ERROR;
}
Status getFreeSpace(const char* path, FwSizeType& totalBytes, FwSizeType& freeBytes) {
return OTHER_ERROR;
}
} // namespace FileSystem
} // namespace Os
| cpp |
fprime | data/projects/fprime/Os/Baremetal/Task.cpp | #include <Fw/Comp/ActiveComponentBase.hpp>
#include <Os/Task.hpp>
#include <Os/Baremetal/TaskRunner/BareTaskHandle.hpp>
#include <Fw/Types/Assert.hpp>
#include <cstdio>
#include <new>
namespace Os {
Task::Task() :
m_handle(0),
m_identifier(0),
m_affinity(-1),
m_started(false),
m_suspendedOnPurpose(false)
{}
Task::TaskStatus Task::start(const Fw::StringBase &name, taskRoutine routine, void* arg, ParamType priority, ParamType stackSize, ParamType cpuAffinity, ParamType identifier) {
//Get a task handle, and set it up
BareTaskHandle* handle = new(std::nothrow) BareTaskHandle();
if (handle == nullptr) {
return Task::TASK_UNKNOWN_ERROR;
}
//Set handle member variables
handle->m_enabled = true;
handle->m_priority = priority;
handle->m_routine = routine;
handle->m_argument = arg;
//Register this task using our custom task handle
m_handle = reinterpret_cast<POINTER_CAST>(handle);
this->m_name = "BR_";
this->m_name += name;
this->m_identifier = identifier;
// If a registry has been registered, register task
if (Task::s_taskRegistry) {
Task::s_taskRegistry->addTask(this);
}
//Running the task the first time allows setup activities for the task
handle->m_routine(handle->m_argument);
return Task::TASK_OK;
}
Task::TaskStatus Task::delay(NATIVE_UINT_TYPE milliseconds)
{
//Task delays are a bad idea in baremetal tasks
return Task::TASK_DELAY_ERROR;
}
Task::~Task() {
if (this->m_handle) {
delete reinterpret_cast<BareTaskHandle*>(this->m_handle);
}
// If a registry has been registered, remove task
if (Task::s_taskRegistry) {
Task::s_taskRegistry->removeTask(this);
}
}
void Task::suspend(bool onPurpose) {
FW_ASSERT(reinterpret_cast<BareTaskHandle*>(this->m_handle) != nullptr);
reinterpret_cast<BareTaskHandle*>(this->m_handle)->m_enabled = false;
}
void Task::resume() {
FW_ASSERT(reinterpret_cast<BareTaskHandle*>(this->m_handle) != nullptr);
reinterpret_cast<BareTaskHandle*>(this->m_handle)->m_enabled = true;
}
bool Task::isSuspended() {
FW_ASSERT(reinterpret_cast<BareTaskHandle*>(this->m_handle) != nullptr);
return !reinterpret_cast<BareTaskHandle*>(this->m_handle)->m_enabled;
}
Task::TaskStatus Task::join(void **value_ptr) {
return TASK_OK;
}
}
| cpp |
fprime | data/projects/fprime/Os/Baremetal/Mutex.cpp | #include <Os/Mutex.hpp>
namespace Os {
/**
* On baremetal, mutexes are not required as there is a single threaded
* engine to run on.
*/
Mutex::Mutex() {
static U32 counter = 0;
m_handle = counter++;
}
Mutex::~Mutex() {}
void Mutex::lock() {}
void Mutex::unLock() {}
}
| cpp |
fprime | data/projects/fprime/Os/Baremetal/TaskRunner/BareTaskHandle.hpp | /*
* BareTaskHandle.hpp
*
* Created on: Feb 28, 2019
* Author: lestarch
*/
#ifndef OS_BAREMETAL_TASKRUNNER_BARETASKHANDLE_HPP_
#define OS_BAREMETAL_TASKRUNNER_BARETASKHANDLE_HPP_
#include <Os/Task.hpp>
namespace Os {
/**
* Helper handle used to pretend to be a task.
*/
class BareTaskHandle {
public:
//!< Constructor sets enabled to false
BareTaskHandle() : m_enabled(false), m_priority(0), m_routine(nullptr) {}
//!< Is this task enabled or not
bool m_enabled;
//!< Save the priority
NATIVE_INT_TYPE m_priority;
//!< Function passed into the task
Task::taskRoutine m_routine;
//!< Argument input pointer
void* m_argument;
};
}
#endif /* OS_BAREMETAL_TASKRUNNER_BARETASKHANDLE_HPP_ */
| hpp |
fprime | data/projects/fprime/Os/Baremetal/TaskRunner/TaskRunner.cpp | /*
* TaskRunner.cpp
*
* Created on: Feb 28, 2019
* Author: lestarch
*/
#include <Fw/Types/Assert.hpp>
#include <FpConfig.hpp>
#include <Os/Baremetal/TaskRunner/TaskRunner.hpp>
#include <Os/Baremetal/TaskRunner/BareTaskHandle.hpp>
namespace Os {
TaskRunner::TaskRunner() :
m_index(0),
m_cont(true)
{
for (U32 i = 0; i < TASK_REGISTRY_CAP; i++) {
this->m_task_table[i] = 0;
}
Task::registerTaskRegistry(this);
}
TaskRunner::~TaskRunner() {}
void TaskRunner::addTask(Task* task) {
FW_ASSERT(m_index < TASK_REGISTRY_CAP);
this->m_task_table[m_index] = task;
m_index++;
}
void TaskRunner::removeTask(Task* task) {
bool found = false;
//Squash that existing task
for (U32 i = 0; i < TASK_REGISTRY_CAP; i++) {
found = found | (task == this->m_task_table[i]);
//If not found, keep looking
if (!found) {
continue;
}
//If we are less than the end of the array, shift variables over
else if (i < TASK_REGISTRY_CAP - 1) {
this->m_task_table[i] = this->m_task_table[i+1];
}
//If the last element, mark NULL
else {
this->m_task_table[i] = nullptr;
}
}
}
void TaskRunner::stop() {
m_cont = false;
}
void TaskRunner::run() {
U32 i = 0;
if (!m_cont) {
return;
}
//Loop through full table
for (i = 0; i < TASK_REGISTRY_CAP; i++) {
//Break at end of table
if (m_task_table[i] == nullptr) {
break;
}
//Get bare task or break
BareTaskHandle* handle = reinterpret_cast<BareTaskHandle*>(m_task_table[i]->getRawHandle());
if (handle == nullptr || handle->m_routine == nullptr || !handle->m_enabled) {
continue;
}
//Run-it!
handle->m_routine(handle->m_argument);
//Disable tasks that have "exited" or stopped
handle->m_enabled = m_task_table[i]->isStarted();
}
//Check if no tasks, and stop
if (i == 0) {
m_cont = false;
}
}
}
| cpp |
fprime | data/projects/fprime/Os/Baremetal/TaskRunner/TaskRunner.hpp | /*
* TaskRunner.hpp
*
* Created on: Feb 28, 2019
* Author: lestarch
*/
#include <Os/Task.hpp>
#ifndef OS_BAREMETAL_TASKRUNNER_TASKRUNNER_HPP_
#define OS_BAREMETAL_TASKRUNNER_TASKRUNNER_HPP_
#define TASK_REGISTRY_CAP 100
namespace Os {
/**
* Combination TaskRegistry and task runner. This does the "heavy lifting" for
* baremetal running of tasks.
*/
class TaskRunner : TaskRegistry {
public:
//!< Nothing constructor
TaskRunner();
//!< Nothing destructor
~TaskRunner();
/**
* Add a task to the registry. These tasks will be run on a bare-metal
* loop. The function used in this task may be overridden.
* \param task: task to be added
*/
void addTask(Task* task);
/**
* Remove a task to the registry. These tasks will no-longer be run.
* \param task: task to be removed
*/
void removeTask(Task* task);
/**
* Stop this task registry
*/
void stop();
/**
* Run once function call, used to run one pass over tasks
*/
void run();
private:
U32 m_index;
Task* m_task_table[TASK_REGISTRY_CAP];
bool m_cont;
};
} //End Namespace Os
#endif /* OS_BAREMETAL_TASKRUNNER_TASKRUNNER_HPP_ */
| hpp |
fprime | data/projects/fprime/FppTest/source.cpp | // Empty source file so that SOURCES for target FppTest is not empty
| cpp |
fprime | data/projects/fprime/FppTest/array/main.cpp | // ======================================================================
// \title main.cpp
// \author T. Chieu
// \brief main cpp file for FPP array tests
//
// \copyright
// Copyright (C) 2009-2022 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FppTest/array/EnumArrayAc.hpp"
#include "FppTest/array/StringArrayAc.hpp"
#include "FppTest/array/StructArrayAc.hpp"
#include "FppTest/array/Uint32ArrayArrayAc.hpp"
#include "FppTest/array/String100ArrayAc.hpp"
#include "FppTest/typed_tests/ArrayTest.hpp"
#include "FppTest/typed_tests/StringTest.hpp"
#include "FppTest/utils/Utils.hpp"
#include "STest/Random/Random.hpp"
#include "gtest/gtest.h"
// Instantiate array tests
using ArrayTestImplementations = ::testing::Types<
Enum,
String,
Struct,
Uint32Array
>;
INSTANTIATE_TYPED_TEST_SUITE_P(FppTest, ArrayTest, ArrayTestImplementations);
// Specializations for default values
template <>
void FppTest::Array::setDefaultVals<Enum>(E (&a)[Enum::SIZE]) {
a[0] = E::A;
a[1] = E::B;
a[2] = E::C;
}
// Specialization for test values
template<>
void FppTest::Array::setTestVals<Enum>(E (&a)[Enum::SIZE]) {
a[0] = static_cast<E::T>(STest::Pick::startLength(
E::B,
E::NUM_CONSTANTS - 1
));
for (U32 i = 1; i < Enum::SIZE; i++) {
a[i] = static_cast<E::T>(STest::Pick::startLength(
E::A,
E::NUM_CONSTANTS - 1
));
}
}
template<>
void FppTest::Array::setTestVals<String>
(::String::StringSize80 (&a)[::String::SIZE]) {
char buf[80];
for (U32 i = 0; i < ::String::SIZE; i++) {
FppTest::Utils::setString(buf, sizeof(buf));
a[i] = buf;
}
}
template<>
void FppTest::Array::setTestVals<Struct>(S (&a)[Struct::SIZE]) {
U32 b[3];
for (U32 i = 0; i < Struct::SIZE; i++) {
for (U32 j = 0; j < 3; j++) {
b[j] = FppTest::Utils::getNonzeroU32();
}
a[i].set(FppTest::Utils::getNonzeroU32(), b);
}
}
template<>
void FppTest::Array::setTestVals<Uint32Array>(Uint32 (&a)[Uint32Array::SIZE]) {
Uint32 b;
for (U32 i = 0; i < Uint32Array::SIZE; i++) {
for (U32 j = 0; j < Uint32::SIZE; j++) {
b[j] = FppTest::Utils::getNonzeroU32();
}
a[i] = b;
}
}
// Specializations for multi element constructor
template<>
Enum FppTest::Array::getMultiElementConstructedArray<Enum>
(E (&a)[Enum::SIZE]) {
return Enum(a[0], a[1], a[2]);
}
template<>
::String FppTest::Array::getMultiElementConstructedArray<::String>
(::String::StringSize80 (&a)[::String::SIZE]) {
return ::String(a[0], a[1], a[2]);
}
template<>
Struct FppTest::Array::getMultiElementConstructedArray<Struct>
(S (&a)[Struct::SIZE]) {
return Struct(a[0], a[1], a[2]);
}
template<>
Uint32Array FppTest::Array::getMultiElementConstructedArray<Uint32Array>
(Uint32 (&a)[Uint32Array::SIZE]) {
return Uint32Array(a[0], a[1], a[2]);
}
// Specializations for serialized size
template <>
U32 FppTest::Array::getSerializedSize<::String>
(::String::StringSize80 (&a)[::String::SIZE]) {
U32 serializedSize = 0;
for (U32 i = 0; i < ::String::SIZE; i++) {
serializedSize += a[i].length() + sizeof(FwBuffSizeType);
}
return serializedSize;
}
// Instantiate string tests for arrays
using StringTestImplementations = ::testing::Types<
String::StringSize80,
String100::StringSize100
>;
INSTANTIATE_TYPED_TEST_SUITE_P(Array, StringTest, StringTestImplementations);
template<>
U32 FppTest::String::getSize<String100::StringSize100>() {
return 100;
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
STest::Random::seed();
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/FppTest/array/ArrayToStringTest.cpp | // ======================================================================
// \title ArrayToStringTest.cpp
// \author T. Chieu
// \brief cpp file for ArrayToStringTest class
//
// \copyright
// Copyright (C) 2009-2022 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FppTest/array/EnumArrayAc.hpp"
#include "FppTest/array/StringArrayAc.hpp"
#include "FppTest/array/StructArrayAc.hpp"
#include "FppTest/array/Uint32ArrayArrayAc.hpp"
#include "FppTest/typed_tests/ArrayTest.hpp"
#include "gtest/gtest.h"
#include <sstream>
// Test array string functions
template <typename ArrayType>
class ArrayToStringTest : public ::testing::Test {
protected:
void SetUp() override {
FppTest::Array::setTestVals<ArrayType>(testVals);
}
typename ArrayType::ElementType testVals[ArrayType::SIZE];
};
using ArrayTypes = ::testing::Types<
Enum,
String,
Struct,
Uint32Array
>;
TYPED_TEST_SUITE(ArrayToStringTest, ArrayTypes);
// Test array toString() and ostream operator functions
TYPED_TEST(ArrayToStringTest, ToString) {
TypeParam a(this->testVals);
std::stringstream buf1, buf2;
buf1 << a;
buf2 << "[ ";
for (U32 i = 0; i < TypeParam::SIZE; i++) {
buf2 << this->testVals[i] << " ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
| cpp |
fprime | data/projects/fprime/FppTest/array/FormatTest.cpp | // ======================================================================
// \title FormatTest.cpp
// \author T. Chieu
// \brief cpp file for FormatTest class
//
// \copyright
// Copyright (C) 2009-2022 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FppTest/array/FormatBoolArrayAc.hpp"
#include "FppTest/array/FormatU8ArrayAc.hpp"
#include "FppTest/array/FormatU16DecArrayAc.hpp"
#include "FppTest/array/FormatU32OctArrayAc.hpp"
#include "FppTest/array/FormatU64HexArrayAc.hpp"
#include "FppTest/array/FormatI8ArrayAc.hpp"
#include "FppTest/array/FormatI16DecArrayAc.hpp"
#include "FppTest/array/FormatI32OctArrayAc.hpp"
#include "FppTest/array/FormatI64HexArrayAc.hpp"
#include "FppTest/array/FormatF32eArrayAc.hpp"
#include "FppTest/array/FormatF32fArrayAc.hpp"
#include "FppTest/array/FormatF64gArrayAc.hpp"
#include "FppTest/array/FormatStringArrayAc.hpp"
#include "FppTest/array/FormatCharArrayAc.hpp"
#include "FppTest/utils/Utils.hpp"
#include "gtest/gtest.h"
#include <sstream>
#include <limits>
// Tests FPP format strings
class FormatTest : public ::testing::Test {
protected:
void SetUp() override {
buf2 << "[ ";
}
std::stringstream buf1, buf2;
};
TEST_F(FormatTest, Bool) {
bool testVals[FormatBool::SIZE] = {true, true, false};
FormatBool a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatBool::SIZE; i++) {
buf2 << "a " << testVals[i] << " b ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
TEST_F(FormatTest, U8) {
U8 testVals[FormatU8::SIZE] = {0, 100, std::numeric_limits<U8>::max()};
FormatU8 a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatU8::SIZE; i++) {
buf2 << "a " << (U16) testVals[i] << " b ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
TEST_F(FormatTest, U16Dec) {
U16 testVals[FormatU16Dec::SIZE] = {0, 100, std::numeric_limits<U16>::max()};
FormatU16Dec a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatU16Dec::SIZE; i++) {
buf2 << "a " << std::dec << testVals[i] << " b ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
TEST_F(FormatTest, U32Oct) {
U32 testVals[FormatU32Oct::SIZE] = {0, 100, std::numeric_limits<U32>::max()};
FormatU32Oct a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatU32Oct::SIZE; i++) {
buf2 << "a " << std::oct << testVals[i] << " b ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
TEST_F(FormatTest, U64Hex) {
U64 testVals[FormatU64Hex::SIZE] =
{0, 100, std::numeric_limits<U64>::max()};
FormatU64Hex a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatU64Hex::SIZE; i++) {
buf2 << "a " << std::hex << testVals[i] << " b ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
TEST_F(FormatTest, I8) {
I8 testVals[FormatI8::SIZE] =
{std::numeric_limits<I8>::min(), 0, std::numeric_limits<I8>::max()};
FormatI8 a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatI8::SIZE; i++) {
buf2 << "a " << (I16) testVals[i] << " b ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
TEST_F(FormatTest, I16Dec) {
I16 testVals[FormatI16Dec::SIZE] =
{std::numeric_limits<I16>::min(), 0, std::numeric_limits<I16>::max()};
FormatI16Dec a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatI16Dec::SIZE; i++) {
buf2 << "a " << std::dec << testVals[i] << " b ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
TEST_F(FormatTest, I32Oct) {
I32 testVals[FormatI32Oct::SIZE] =
{std::numeric_limits<I32>::min(), 0, std::numeric_limits<I32>::max()};
FormatI32Oct a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatI32Oct::SIZE; i++) {
buf2 << "a " << std::oct << testVals[i] << " b ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
TEST_F(FormatTest, I64Hex) {
I64 testVals[FormatI64Hex::SIZE] =
{std::numeric_limits<I64>::min(), 0, std::numeric_limits<I64>::max()};
FormatI64Hex a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatI64Hex::SIZE; i++) {
buf2 << "a " << std::hex << testVals[i] << " b ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
TEST_F(FormatTest, F32E) {
F32 testVals[FormatF32e::SIZE] =
{std::numeric_limits<F32>::min(), 0.0, std::numeric_limits<F32>::max()};
FormatF32e a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatF32e::SIZE; i++) {
buf2 << "a " << std::setprecision(1) << std::scientific << testVals[i] << " b ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
TEST_F(FormatTest, F32F) {
F32 testVals[FormatF32f::SIZE] =
{std::numeric_limits<F32>::min(), 0.0, std::numeric_limits<F32>::max()};
FormatF32f a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatF32f::SIZE; i++) {
buf2 << "a " << std::setprecision(2) << std::fixed << testVals[i] << " b ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
TEST_F(FormatTest, F64G) {
F64 testVals[FormatF64g::SIZE] =
{std::numeric_limits<F64>::min(), 0.0, std::numeric_limits<F64>::max()};
FormatF64g a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatF64g::SIZE; i++) {
buf2 << "a " << std::setprecision(3) << testVals[i] << " b ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
TEST_F(FormatTest, String) {
FormatString::StringSize80 testVals[FormatString::SIZE];
char buf[80];
for (U32 i = 0; i < FormatString::SIZE; i++) {
FppTest::Utils::setString(buf, sizeof(buf));
testVals[i] = buf;
}
FormatString a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatString::SIZE; i++) {
buf2 << "% " << testVals[i].toChar() << " ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
TEST_F(FormatTest, Char) {
U8 testVals[FormatChar::SIZE] =
{FppTest::Utils::getNonzeroU8(), FppTest::Utils::getNonzeroU8(), FppTest::Utils::getNonzeroU8()};
FormatChar a(testVals);
buf1 << a;
for (U32 i = 0; i < FormatChar::SIZE; i++) {
buf2 << "a " << testVals[i] << " b ";
}
buf2 << "]";
ASSERT_STREQ(
buf1.str().c_str(),
buf2.str().c_str()
);
}
| cpp |
fprime | data/projects/fprime/FppTest/component/types/FormalParamTypes.hpp | // ======================================================================
// \title FormalParamTypes.hpp
// \author T. Chieu
// \brief hpp file for formal param types
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#ifndef FPP_TEST_FORMAL_PARAM_TYPES_HPP
#define FPP_TEST_FORMAL_PARAM_TYPES_HPP
#include "Fw/Cmd/CmdString.hpp"
#include "Fw/Log/LogString.hpp"
#include "Fw/Prm/PrmString.hpp"
#include "Fw/Tlm/TlmString.hpp"
#include "Fw/Types/InternalInterfaceString.hpp"
#include "Fw/Types/SerialBuffer.hpp"
#include "FppTest/component/active/FormalParamArrayArrayAc.hpp"
#include "FppTest/component/active/FormalParamEnumEnumAc.hpp"
#include "FppTest/component/active/FormalParamStructSerializableAc.hpp"
#include "FppTest/component/active/StringArgsPortAc.hpp"
#include "FppTest/utils/Utils.hpp"
#define SERIAL_ARGS_BUFFER_CAPACITY 256
namespace FppTest {
namespace Types {
template <typename ArgType, typename ReturnType>
struct FormalParamsWithReturn {
ArgType args;
};
// Empty type
struct Empty {};
template <typename ArgType>
using FormalParams = FormalParamsWithReturn<ArgType, Empty>;
// ----------------------------------------------------------------------
// Primitive types
// ----------------------------------------------------------------------
struct BoolType {
BoolType();
bool val;
};
struct U32Type {
U32Type();
U32 val;
};
struct F32Type {
F32Type();
F32 val;
};
struct PrimitiveTypes {
PrimitiveTypes();
U32 val1;
U32 val2;
F32 val3;
F32 val4;
bool val5;
bool val6;
};
// ----------------------------------------------------------------------
// FPP types
// ----------------------------------------------------------------------
struct EnumType {
EnumType();
FormalParamEnum val;
};
struct EnumTypes {
EnumTypes();
FormalParamEnum val1;
FormalParamEnum val2;
};
struct ArrayType {
ArrayType();
FormalParamArray val;
};
struct ArrayTypes {
ArrayTypes();
FormalParamArray val1;
FormalParamArray val2;
};
struct StructType {
StructType();
FormalParamStruct val;
};
struct StructTypes {
StructTypes();
FormalParamStruct val1;
FormalParamStruct val2;
};
// ----------------------------------------------------------------------
// String types
// ----------------------------------------------------------------------
struct PortStringType {
PortStringType();
StringArgsPortStrings::StringSize80 val;
};
struct PortStringTypes {
PortStringTypes();
StringArgsPortStrings::StringSize80 val1;
StringArgsPortStrings::StringSize80 val2;
StringArgsPortStrings::StringSize100 val3;
StringArgsPortStrings::StringSize100 val4;
};
struct InternalInterfaceStringType {
InternalInterfaceStringType();
Fw::InternalInterfaceString val;
};
struct InternalInterfaceStringTypes {
InternalInterfaceStringTypes();
Fw::InternalInterfaceString val1;
Fw::InternalInterfaceString val2;
};
struct CmdStringType {
CmdStringType();
Fw::CmdStringArg val;
};
struct CmdStringTypes {
CmdStringTypes();
Fw::CmdStringArg val1;
Fw::CmdStringArg val2;
};
struct LogStringType {
LogStringType();
Fw::LogStringArg val;
};
struct LogStringTypes {
LogStringTypes();
Fw::LogStringArg val1;
Fw::LogStringArg val2;
};
struct TlmStringType {
TlmStringType();
Fw::TlmString val;
};
struct TlmStringTypes {
TlmStringTypes();
Fw::TlmString val1;
Fw::TlmString val2;
};
struct PrmStringType {
PrmStringType();
Fw::ParamString val;
};
struct PrmStringTypes {
PrmStringTypes();
Fw::ParamString val1;
Fw::ParamString val2;
};
// ----------------------------------------------------------------------
// Serial type
// ----------------------------------------------------------------------
struct SerialType {
SerialType();
U8 data[SERIAL_ARGS_BUFFER_CAPACITY];
Fw::SerialBuffer val;
};
// ----------------------------------------------------------------------
// Helper functions
// ----------------------------------------------------------------------
void setRandomString(Fw::StringBase& str);
void setRandomString(Fw::StringBase& str, U32 size);
FormalParamEnum getRandomFormalParamEnum();
void getRandomFormalParamArray(FormalParamArray& a);
FormalParamStruct getRandomFormalParamStruct();
// ----------------------------------------------------------------------
// Typedefs
// ----------------------------------------------------------------------
typedef FormalParams<Empty> NoParams;
typedef FormalParams<BoolType> BoolParam;
typedef FormalParams<U32Type> U32Param;
typedef FormalParams<F32Type> F32Param;
typedef FormalParams<PrimitiveTypes> PrimitiveParams;
typedef FormalParams<EnumType> EnumParam;
typedef FormalParams<EnumTypes> EnumParams;
typedef FormalParams<ArrayType> ArrayParam;
typedef FormalParams<ArrayTypes> ArrayParams;
typedef FormalParams<StructType> StructParam;
typedef FormalParams<StructTypes> StructParams;
typedef FormalParams<PortStringType> PortStringParam;
typedef FormalParams<PortStringTypes> PortStringParams;
typedef FormalParams<InternalInterfaceStringType> InternalInterfaceStringParam;
typedef FormalParams<InternalInterfaceStringTypes> InternalInterfaceStringParams;
typedef FormalParams<CmdStringType> CmdStringParam;
typedef FormalParams<CmdStringTypes> CmdStringParams;
typedef FormalParams<LogStringType> LogStringParam;
typedef FormalParams<LogStringTypes> LogStringParams;
typedef FormalParams<TlmStringType> TlmStringParam;
typedef FormalParams<TlmStringTypes> TlmStringParams;
typedef FormalParams<PrmStringType> PrmStringParam;
typedef FormalParams<PrmStringTypes> PrmStringParams;
typedef FormalParams<SerialType> SerialParam;
typedef FormalParamsWithReturn<Empty, BoolType> NoParamReturn;
typedef FormalParamsWithReturn<PrimitiveTypes, U32Type> PrimitiveReturn;
typedef FormalParamsWithReturn<EnumTypes, EnumType> EnumReturn;
typedef FormalParamsWithReturn<ArrayTypes, ArrayType> ArrayReturn;
typedef FormalParamsWithReturn<StructTypes, StructType> StructReturn;
} // namespace Types
} // namespace FppTest
#endif
| hpp |
fprime | data/projects/fprime/FppTest/component/types/FormalParamTypes.cpp | // ======================================================================
// \title FormalParamTypes.cpp
// \author T. Chieu
// \brief cpp file for formal param types
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FormalParamTypes.hpp"
#include "FppTest/utils/Utils.hpp"
#include "STest/Pick/Pick.hpp"
namespace FppTest {
namespace Types {
// ----------------------------------------------------------------------
// Primitive types
// ----------------------------------------------------------------------
BoolType::BoolType() {
val = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
}
U32Type::U32Type() {
val = STest::Pick::any();
}
F32Type::F32Type() {
val = static_cast<F32>(STest::Pick::any());
}
PrimitiveTypes::PrimitiveTypes() {
val1 = STest::Pick::any();
val2 = STest::Pick::any();
val3 = static_cast<F32>(STest::Pick::any());
val4 = static_cast<F32>(STest::Pick::any());
val5 = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
val6 = static_cast<bool>(STest::Pick::lowerUpper(0, 1));
}
// ----------------------------------------------------------------------
// FPP types
// ----------------------------------------------------------------------
EnumType::EnumType() {
val = getRandomFormalParamEnum();
}
EnumTypes::EnumTypes() {
val1 = getRandomFormalParamEnum();
val2 = getRandomFormalParamEnum();
}
ArrayType::ArrayType() {
getRandomFormalParamArray(val);
}
ArrayTypes::ArrayTypes() {
getRandomFormalParamArray(val1);
getRandomFormalParamArray(val2);
}
StructType::StructType() {
val = getRandomFormalParamStruct();
}
StructTypes::StructTypes() {
val1 = getRandomFormalParamStruct();
val2 = getRandomFormalParamStruct();
}
// ----------------------------------------------------------------------
// String types
// ----------------------------------------------------------------------
PortStringType::PortStringType() {
setRandomString(val);
}
PortStringTypes::PortStringTypes() {
setRandomString(val1);
setRandomString(val2);
setRandomString(val3);
setRandomString(val4);
}
InternalInterfaceStringType::InternalInterfaceStringType() {
setRandomString(val);
}
InternalInterfaceStringTypes::InternalInterfaceStringTypes() {
setRandomString(val1);
setRandomString(val2);
}
CmdStringType::CmdStringType() {
setRandomString(val, FW_CMD_STRING_MAX_SIZE);
}
CmdStringTypes::CmdStringTypes() {
setRandomString(val1, FW_CMD_STRING_MAX_SIZE / 2);
setRandomString(val2, FW_CMD_STRING_MAX_SIZE / 2);
}
LogStringType::LogStringType() {
setRandomString(val, FW_LOG_STRING_MAX_SIZE);
}
LogStringTypes::LogStringTypes() {
setRandomString(val1, FW_LOG_STRING_MAX_SIZE / 2);
setRandomString(val2, FW_LOG_STRING_MAX_SIZE / 2);
}
TlmStringType::TlmStringType() {
setRandomString(val, FW_TLM_STRING_MAX_SIZE);
}
TlmStringTypes::TlmStringTypes() {
setRandomString(val1, FW_TLM_STRING_MAX_SIZE / 2);
setRandomString(val2, FW_TLM_STRING_MAX_SIZE / 2);
}
PrmStringType::PrmStringType() {
setRandomString(val, FW_PARAM_STRING_MAX_SIZE);
}
PrmStringTypes::PrmStringTypes() {
setRandomString(val1, FW_PARAM_STRING_MAX_SIZE / 2);
setRandomString(val2, FW_PARAM_STRING_MAX_SIZE / 2);
}
// ----------------------------------------------------------------------
// Serial type
// ----------------------------------------------------------------------
SerialType::SerialType() : val(data, sizeof(data)) {
U32 len = STest::Pick::lowerUpper(1, SERIAL_ARGS_BUFFER_CAPACITY);
for (U32 i = 0; i < len; i++) {
data[i] = Utils::getNonzeroU8();
}
}
// ----------------------------------------------------------------------
// Helper functions
// ----------------------------------------------------------------------
void setRandomString(Fw::StringBase& str) {
char buf[str.getCapacity()];
Utils::setString(buf, sizeof(buf));
str = buf;
}
void setRandomString(Fw::StringBase& str, U32 size) {
char buf[size];
Utils::setString(buf, size);
str = buf;
}
FormalParamEnum getRandomFormalParamEnum() {
FormalParamEnum e;
e = static_cast<FormalParamEnum::T>(STest::Pick::lowerUpper(0, FormalParamEnum::NUM_CONSTANTS - 1));
return e;
}
void getRandomFormalParamArray(FormalParamArray& a) {
for (U32 i = 0; i < FormalParamArray::SIZE; i++) {
a[i] = STest::Pick::any();
}
}
FormalParamStruct getRandomFormalParamStruct() {
FormalParamStruct s;
char buf[s.gety().getCapacity()];
FormalParamStruct::StringSize80 str = buf;
Utils::setString(buf, sizeof(buf));
s.set(STest::Pick::any(), str);
return s;
}
} // namespace Types
} // namespace FppTest
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/TlmTests.cpp | // ======================================================================
// \title TlmTests.cpp
// \author T. Chieu
// \brief cpp file for telemetry tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "TlmTests.hpp"
#include "Tester.hpp"
TLM_TEST_DEFS
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/AsyncCmdTests.cpp | // ======================================================================
// \title AsyncCmdTests.cpp
// \author T. Chieu
// \brief cpp file for async command tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "CmdTests.hpp"
#include "Fw/Cmd/CmdArgBuffer.hpp"
CMD_TEST_INVOKE_DEFS_ASYNC
CMD_TEST_DEFS(Async, _ASYNC)
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/InternalInterfaceTests.cpp | // ======================================================================
// \title InternalInterfaceTests.cpp
// \author T. Chieu
// \brief cpp file for internal interface tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Tester.hpp"
#include "Fw/Comp/QueuedComponentBase.hpp"
void Tester ::testInternalInterface(FppTest::Types::NoParams& data) {
Fw::QueuedComponentBase::MsgDispatchStatus status;
this->component.internalNoArgs_internalInterfaceInvoke();
status = this->doDispatch();
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK);
}
void Tester ::testInternalInterface(FppTest::Types::PrimitiveParams& data) {
Fw::QueuedComponentBase::MsgDispatchStatus status;
this->component.internalPrimitive_internalInterfaceInvoke(data.args.val1, data.args.val2, data.args.val3,
data.args.val4, data.args.val5, data.args.val6);
status = this->doDispatch();
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK);
ASSERT_EQ(this->component.primitiveInterface.args.val1, data.args.val1);
ASSERT_EQ(this->component.primitiveInterface.args.val2, data.args.val2);
ASSERT_EQ(this->component.primitiveInterface.args.val3, data.args.val3);
ASSERT_EQ(this->component.primitiveInterface.args.val4, data.args.val4);
ASSERT_EQ(this->component.primitiveInterface.args.val5, data.args.val5);
ASSERT_EQ(this->component.primitiveInterface.args.val6, data.args.val6);
}
void Tester ::testInternalInterface(FppTest::Types::InternalInterfaceStringParams& data) {
Fw::QueuedComponentBase::MsgDispatchStatus status;
this->component.internalString_internalInterfaceInvoke(data.args.val1, data.args.val2);
status = this->doDispatch();
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK);
ASSERT_EQ(this->component.stringInterface.args.val1, data.args.val1);
ASSERT_EQ(this->component.stringInterface.args.val2, data.args.val2);
}
void Tester ::testInternalInterface(FppTest::Types::EnumParam& data) {
Fw::QueuedComponentBase::MsgDispatchStatus status;
this->component.internalEnum_internalInterfaceInvoke(data.args.val);
status = this->doDispatch();
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK);
ASSERT_EQ(this->component.enumInterface.args.val, data.args.val);
}
void Tester ::testInternalInterface(FppTest::Types::ArrayParam& data) {
Fw::QueuedComponentBase::MsgDispatchStatus status;
this->component.internalArray_internalInterfaceInvoke(data.args.val);
status = this->doDispatch();
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK);
ASSERT_EQ(this->component.arrayInterface.args.val, data.args.val);
}
void Tester ::testInternalInterface(FppTest::Types::StructParam& data) {
Fw::QueuedComponentBase::MsgDispatchStatus status;
this->component.internalStruct_internalInterfaceInvoke(data.args.val);
status = this->doDispatch();
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK);
ASSERT_EQ(this->component.structInterface.args.val, data.args.val);
}
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/ParamTests.hpp | // ======================================================================
// \title ParamTests.hpp
// \author T. Chieu
// \brief hpp file for parameter tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
// ----------------------------------------------------------------------
// Parameter test declarations
// ----------------------------------------------------------------------
#define PARAM_CMD_TEST_DECL(TYPE) void testParamCommand(NATIVE_INT_TYPE portNum, FppTest::Types::TYPE& data);
#define PARAM_CMD_TEST_DECLS \
PARAM_CMD_TEST_DECL(BoolParam) \
PARAM_CMD_TEST_DECL(U32Param) \
PARAM_CMD_TEST_DECL(PrmStringParam) \
PARAM_CMD_TEST_DECL(EnumParam) \
PARAM_CMD_TEST_DECL(ArrayParam) \
PARAM_CMD_TEST_DECL(StructParam)
| hpp |
fprime | data/projects/fprime/FppTest/component/tests/InternalInterfaceTests.hpp | // ======================================================================
// \title InternalInterfaceTests.hpp
// \author T. Chieu
// \brief hpp file for internal interface tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Internal interface test declarations
// ----------------------------------------------------------------------
#define INTERNAL_INT_TEST_DECL(TYPE) void testInternalInterface(FppTest::Types::TYPE& data);
#define INTERNAL_INT_TEST_DECLS \
INTERNAL_INT_TEST_DECL(NoParams) \
INTERNAL_INT_TEST_DECL(PrimitiveParams) \
INTERNAL_INT_TEST_DECL(InternalInterfaceStringParams) \
INTERNAL_INT_TEST_DECL(EnumParam) \
INTERNAL_INT_TEST_DECL(ArrayParam) \
INTERNAL_INT_TEST_DECL(StructParam)
| hpp |
fprime | data/projects/fprime/FppTest/component/tests/AsyncTesterHelpers.cpp | // ======================================================================
// \title AsyncTesterHelpers.cpp
// \author T. Chieu
// \brief cpp file for async tester helper functions
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Tester.hpp"
void Tester ::connectAsyncPorts() {
// arrayArgsAsync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_arrayArgsAsync(i, this->component.get_arrayArgsAsync_InputPort(i));
}
// enumArgsAsync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_enumArgsAsync(i, this->component.get_enumArgsAsync_InputPort(i));
}
// noArgsAsync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_noArgsAsync(i, this->component.get_noArgsAsync_InputPort(i));
}
// primitiveArgsAsync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_primitiveArgsAsync(i, this->component.get_primitiveArgsAsync_InputPort(i));
}
// stringArgsAsync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_stringArgsAsync(i, this->component.get_stringArgsAsync_InputPort(i));
}
// structArgsAsync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_structArgsAsync(i, this->component.get_structArgsAsync_InputPort(i));
}
// serialAsync
for (NATIVE_INT_TYPE i = 0; i < 3; ++i) {
this->connect_to_serialAsync(i, this->component.get_serialAsync_InputPort(i));
}
// serialAsyncAssert
this->connect_to_serialAsyncAssert(0, this->component.get_serialAsyncAssert_InputPort(0));
// serialAsyncBlockPriority
this->connect_to_serialAsyncBlockPriority(0, this->component.get_serialAsyncBlockPriority_InputPort(0));
// serialAsyncDropPriority
this->connect_to_serialAsyncDropPriority(0, this->component.get_serialAsyncDropPriority_InputPort(0));
}
Fw::QueuedComponentBase::MsgDispatchStatus Tester ::doDispatch() {
return component.doDispatch();
}
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/PortTests.hpp | // ======================================================================
// \title PortTests.hpp
// \author T. Chieu
// \brief hpp file for port tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FppTest/component/active/SerialPortIndexEnumAc.hpp"
#include "FppTest/component/active/TypedPortIndexEnumAc.hpp"
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Port test declarations
// ----------------------------------------------------------------------
#define PORT_TEST_INVOKE_DECL(PORT_KIND, TYPE) \
void test##PORT_KIND##PortInvoke(NATIVE_INT_TYPE portNum, FppTest::Types::TYPE& port);
#define PORT_TEST_INVOKE_DECLS(PORT_KIND) \
PORT_TEST_INVOKE_DECL(PORT_KIND, NoParams) \
PORT_TEST_INVOKE_DECL(PORT_KIND, PrimitiveParams) \
PORT_TEST_INVOKE_DECL(PORT_KIND, PortStringParams) \
PORT_TEST_INVOKE_DECL(PORT_KIND, EnumParams) \
PORT_TEST_INVOKE_DECL(PORT_KIND, ArrayParams) \
PORT_TEST_INVOKE_DECL(PORT_KIND, StructParams) \
PORT_TEST_INVOKE_DECL(PORT_KIND, NoParamReturn) \
PORT_TEST_INVOKE_DECL(PORT_KIND, PrimitiveReturn) \
PORT_TEST_INVOKE_DECL(PORT_KIND, EnumReturn) \
PORT_TEST_INVOKE_DECL(PORT_KIND, ArrayReturn) \
PORT_TEST_INVOKE_DECL(PORT_KIND, StructReturn)
#define PORT_TEST_INVOKE_SERIAL_HELPER_DECL(PORT_KIND) \
void invoke##PORT_KIND##SerialPort(NATIVE_INT_TYPE portNum, Fw::SerialBuffer& buf);
#define PORT_TEST_INVOKE_SERIAL_DECL(PORT_KIND, TYPE) \
void test##PORT_KIND##PortInvokeSerial(NATIVE_INT_TYPE portNum, FppTest::Types::TYPE& port);
#define PORT_TEST_INVOKE_SERIAL_DECLS(PORT_KIND) \
PORT_TEST_INVOKE_SERIAL_DECL(PORT_KIND, NoParams) \
PORT_TEST_INVOKE_SERIAL_DECL(PORT_KIND, PrimitiveParams) \
PORT_TEST_INVOKE_SERIAL_DECL(PORT_KIND, PortStringParams) \
PORT_TEST_INVOKE_SERIAL_DECL(PORT_KIND, EnumParams) \
PORT_TEST_INVOKE_SERIAL_DECL(PORT_KIND, ArrayParams) \
PORT_TEST_INVOKE_SERIAL_DECL(PORT_KIND, StructParams)
#define PORT_TEST_CHECK_DECL(PORT_KIND, TYPE) void test##PORT_KIND##PortCheck(FppTest::Types::TYPE& port);
#define PORT_TEST_CHECK_DECLS(PORT_KIND) \
PORT_TEST_CHECK_DECL(PORT_KIND, NoParams) \
PORT_TEST_CHECK_DECL(PORT_KIND, PrimitiveParams) \
PORT_TEST_CHECK_DECL(PORT_KIND, PortStringParams) \
PORT_TEST_CHECK_DECL(PORT_KIND, EnumParams) \
PORT_TEST_CHECK_DECL(PORT_KIND, ArrayParams) \
PORT_TEST_CHECK_DECL(PORT_KIND, StructParams) \
PORT_TEST_CHECK_DECL(PORT_KIND, NoParamReturn) \
PORT_TEST_CHECK_DECL(PORT_KIND, PrimitiveReturn) \
PORT_TEST_CHECK_DECL(PORT_KIND, EnumReturn) \
PORT_TEST_CHECK_DECL(PORT_KIND, ArrayReturn) \
PORT_TEST_CHECK_DECL(PORT_KIND, StructReturn)
#define PORT_TEST_CHECK_SERIAL_DECL(PORT_KIND, TYPE) void test##PORT_KIND##PortCheckSerial(FppTest::Types::TYPE& port);
#define PORT_TEST_CHECK_SERIAL_DECLS(PORT_KIND) \
PORT_TEST_CHECK_SERIAL_DECL(PORT_KIND, NoParams) \
PORT_TEST_CHECK_SERIAL_DECL(PORT_KIND, PrimitiveParams) \
PORT_TEST_CHECK_SERIAL_DECL(PORT_KIND, PortStringParams) \
PORT_TEST_CHECK_SERIAL_DECL(PORT_KIND, EnumParams) \
PORT_TEST_CHECK_SERIAL_DECL(PORT_KIND, ArrayParams) \
PORT_TEST_CHECK_SERIAL_DECL(PORT_KIND, StructParams)
#define PORT_TEST_DECLS_KIND(PORT_KIND) \
PORT_TEST_INVOKE_DECLS(PORT_KIND) \
PORT_TEST_INVOKE_SERIAL_HELPER_DECL(PORT_KIND) \
PORT_TEST_INVOKE_SERIAL_DECLS(PORT_KIND) \
PORT_TEST_CHECK_DECLS(PORT_KIND) \
PORT_TEST_CHECK_SERIAL_DECLS(PORT_KIND)
#define PORT_TEST_DECLS \
PORT_TEST_DECLS_KIND(Sync) \
PORT_TEST_DECLS_KIND(Guarded)
#define PORT_TEST_DECLS_ASYNC PORT_TEST_DECLS_KIND(Async)
// ----------------------------------------------------------------------
// Invoke typed input ports
// ----------------------------------------------------------------------
#define PORT_TEST_INVOKE_DEFS(PORT_KIND) \
void Tester ::test##PORT_KIND##PortInvoke(NATIVE_INT_TYPE portNum, FppTest::Types::NoParams& port) { \
ASSERT_TRUE(component.isConnected_noArgsOut_OutputPort(portNum)); \
ASSERT_TRUE(this->isConnected_to_noArgs##PORT_KIND(portNum)); \
\
this->invoke_to_noArgs##PORT_KIND(portNum); \
} \
\
void Tester ::test##PORT_KIND##PortInvoke(NATIVE_INT_TYPE portNum, FppTest::Types::PrimitiveParams& port) { \
ASSERT_TRUE(component.isConnected_primitiveArgsOut_OutputPort(portNum)); \
ASSERT_TRUE(this->isConnected_to_primitiveArgs##PORT_KIND(portNum)); \
\
this->invoke_to_primitiveArgs##PORT_KIND(portNum, port.args.val1, port.args.val2, port.args.val3, \
port.args.val4, port.args.val5, port.args.val6); \
} \
\
void Tester ::test##PORT_KIND##PortInvoke(NATIVE_INT_TYPE portNum, FppTest::Types::PortStringParams& port) { \
ASSERT_TRUE(component.isConnected_stringArgsOut_OutputPort(portNum)); \
ASSERT_TRUE(this->isConnected_to_stringArgs##PORT_KIND(portNum)); \
\
this->invoke_to_stringArgs##PORT_KIND(portNum, port.args.val1, port.args.val2, port.args.val3, \
port.args.val4); \
} \
\
void Tester ::test##PORT_KIND##PortInvoke(NATIVE_INT_TYPE portNum, FppTest::Types::EnumParams& port) { \
ASSERT_TRUE(component.isConnected_enumArgsOut_OutputPort(portNum)); \
ASSERT_TRUE(this->isConnected_to_enumArgs##PORT_KIND(portNum)); \
\
this->invoke_to_enumArgs##PORT_KIND(portNum, port.args.val1, port.args.val2); \
} \
\
void Tester ::test##PORT_KIND##PortInvoke(NATIVE_INT_TYPE portNum, FppTest::Types::ArrayParams& port) { \
ASSERT_TRUE(component.isConnected_arrayArgsOut_OutputPort(portNum)); \
ASSERT_TRUE(this->isConnected_to_arrayArgs##PORT_KIND(portNum)); \
\
this->invoke_to_arrayArgs##PORT_KIND(portNum, port.args.val1, port.args.val2); \
} \
\
void Tester ::test##PORT_KIND##PortInvoke(NATIVE_INT_TYPE portNum, FppTest::Types::StructParams& port) { \
ASSERT_TRUE(component.isConnected_structArgsOut_OutputPort(portNum)); \
ASSERT_TRUE(this->isConnected_to_structArgs##PORT_KIND(portNum)); \
\
this->invoke_to_structArgs##PORT_KIND(portNum, port.args.val1, port.args.val2); \
}
#define PORT_TEST_INVOKE_RETURN_DEFS(PORT_KIND) \
void Tester ::test##PORT_KIND##PortInvoke(NATIVE_INT_TYPE portNum, FppTest::Types::NoParamReturn& port) { \
ASSERT_TRUE(component.isConnected_noArgsReturnOut_OutputPort(portNum)); \
ASSERT_TRUE(this->isConnected_to_noArgsReturn##PORT_KIND(portNum)); \
\
bool returnVal = this->invoke_to_noArgsReturn##PORT_KIND(portNum); \
\
ASSERT_EQ(returnVal, this->noParamReturnVal.val); \
} \
\
void Tester ::test##PORT_KIND##PortInvoke(NATIVE_INT_TYPE portNum, FppTest::Types::PrimitiveReturn& port) { \
ASSERT_TRUE(component.isConnected_primitiveReturnOut_OutputPort(portNum)); \
ASSERT_TRUE(this->isConnected_to_primitiveReturn##PORT_KIND(portNum)); \
\
U32 returnVal = this->invoke_to_primitiveReturn##PORT_KIND( \
portNum, port.args.val1, port.args.val2, port.args.val3, port.args.val4, port.args.val5, port.args.val6); \
\
ASSERT_EQ(returnVal, this->primitiveReturnVal.val); \
} \
\
void Tester ::test##PORT_KIND##PortInvoke(NATIVE_INT_TYPE portNum, FppTest::Types::EnumReturn& port) { \
ASSERT_TRUE(component.isConnected_enumReturnOut_OutputPort(portNum)); \
ASSERT_TRUE(this->isConnected_to_enumReturn##PORT_KIND(portNum)); \
\
FormalParamEnum returnVal = this->invoke_to_enumReturn##PORT_KIND(portNum, port.args.val1, port.args.val2); \
\
ASSERT_EQ(returnVal, this->enumReturnVal.val); \
} \
\
void Tester ::test##PORT_KIND##PortInvoke(NATIVE_INT_TYPE portNum, FppTest::Types::ArrayReturn& port) { \
ASSERT_TRUE(component.isConnected_arrayReturnOut_OutputPort(portNum)); \
ASSERT_TRUE(this->isConnected_to_arrayReturn##PORT_KIND(portNum)); \
\
FormalParamArray returnVal = this->invoke_to_arrayReturn##PORT_KIND(portNum, port.args.val1, port.args.val2); \
\
ASSERT_EQ(returnVal, this->arrayReturnVal.val); \
} \
\
void Tester ::test##PORT_KIND##PortInvoke(NATIVE_INT_TYPE portNum, FppTest::Types::StructReturn& port) { \
ASSERT_TRUE(component.isConnected_structReturnOut_OutputPort(portNum)); \
ASSERT_TRUE(this->isConnected_to_structReturn##PORT_KIND(portNum)); \
\
FormalParamStruct returnVal = \
this->invoke_to_structReturn##PORT_KIND(portNum, port.args.val1, port.args.val2); \
\
ASSERT_EQ(returnVal, this->structReturnVal.val); \
}
// ----------------------------------------------------------------------
// Invoke serial input ports
// ----------------------------------------------------------------------
#define PORT_TEST_INVOKE_SERIAL_HELPER_DEF(PORT_KIND) \
void Tester ::invoke##PORT_KIND##SerialPort(NATIVE_INT_TYPE portNum, Fw::SerialBuffer& buf) { \
ASSERT_TRUE(this->isConnected_to_serial##PORT_KIND(portNum)); \
this->invoke_to_serial##PORT_KIND(portNum, buf); \
}
#define PORT_TEST_INVOKE_SERIAL_HELPER_DEF_ASYNC \
void Tester ::invokeAsyncSerialPort(NATIVE_INT_TYPE portNum, Fw::SerialBuffer& buf) { \
Fw::QueuedComponentBase::MsgDispatchStatus status; \
\
switch (portNum) { \
case SerialPortIndex::NO_ARGS: \
case SerialPortIndex::PRIMITIVE: \
case SerialPortIndex::STRING: \
ASSERT_TRUE(this->isConnected_to_serialAsync(portNum)); \
this->invoke_to_serialAsync(portNum, buf); \
break; \
\
case SerialPortIndex::ENUM: \
ASSERT_TRUE(this->isConnected_to_serialAsyncAssert(0)); \
this->invoke_to_serialAsyncAssert(0, buf); \
break; \
\
case SerialPortIndex::ARRAY: \
ASSERT_TRUE(this->isConnected_to_serialAsyncBlockPriority(0)); \
this->invoke_to_serialAsyncBlockPriority(0, buf); \
break; \
\
case SerialPortIndex::STRUCT: \
ASSERT_TRUE(this->isConnected_to_serialAsyncDropPriority(0)); \
this->invoke_to_serialAsyncDropPriority(0, buf); \
break; \
} \
\
status = this->doDispatch(); \
\
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK); \
}
#define PORT_TEST_INVOKE_SERIAL_DEFS(PORT_KIND) \
void Tester ::test##PORT_KIND##PortInvokeSerial(NATIVE_INT_TYPE portNum, FppTest::Types::NoParams& port) { \
ASSERT_TRUE(component.isConnected_serialOut_OutputPort(portNum)); \
\
U8 data[0]; \
Fw::SerialBuffer buf(data, sizeof(data)); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::NO_ARGS, buf); \
} \
\
void Tester ::test##PORT_KIND##PortInvokeSerial(NATIVE_INT_TYPE portNum, FppTest::Types::PrimitiveParams& port) { \
ASSERT_TRUE(component.isConnected_serialOut_OutputPort(portNum)); \
\
Fw::SerializeStatus status; \
\
/* Check unsuccessful deserialization of first parameter */ \
U8 invalidData1[0]; \
Fw::SerialBuffer invalidBuf1(invalidData1, sizeof(invalidData1)); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::PRIMITIVE, invalidBuf1); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check unsuccessful deserialization of second parameter */ \
U8 invalidData2[sizeof(U32)]; \
Fw::SerialBuffer invalidBuf2(invalidData2, sizeof(invalidData2)); \
\
status = invalidBuf2.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::PRIMITIVE, invalidBuf2); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check unsuccessful deserialization of third parameter */ \
U8 invalidData3[sizeof(U32) * 2]; \
Fw::SerialBuffer invalidBuf3(invalidData3, sizeof(invalidData3)); \
\
status = invalidBuf3.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = invalidBuf3.serialize(port.args.val2); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::PRIMITIVE, invalidBuf3); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check unsuccessful deserialization of fourth parameter */ \
U8 invalidData4[(sizeof(U32) * 2) + sizeof(F32)]; \
Fw::SerialBuffer invalidBuf4(invalidData4, sizeof(invalidData4)); \
\
status = invalidBuf4.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = invalidBuf4.serialize(port.args.val2); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = invalidBuf4.serialize(port.args.val3); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::PRIMITIVE, invalidBuf4); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check unsuccessful deserialization of fifth parameter */ \
U8 invalidData5[(sizeof(U32) * 2) + (sizeof(F32) * 2)]; \
Fw::SerialBuffer invalidBuf5(invalidData5, sizeof(invalidData5)); \
\
status = invalidBuf5.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = invalidBuf5.serialize(port.args.val2); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = invalidBuf5.serialize(port.args.val3); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = invalidBuf5.serialize(port.args.val4); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::PRIMITIVE, invalidBuf5); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check unsuccessful deserialization of sixth parameter */ \
U8 invalidData6[(sizeof(U32) * 2) + (sizeof(F32) * 2) + sizeof(U8)]; \
Fw::SerialBuffer invalidBuf6(invalidData6, sizeof(invalidData6)); \
\
status = invalidBuf6.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = invalidBuf6.serialize(port.args.val2); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = invalidBuf6.serialize(port.args.val3); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = invalidBuf6.serialize(port.args.val4); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = invalidBuf6.serialize(port.args.val5); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::PRIMITIVE, invalidBuf6); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check successful serialization */ \
U8 data[InputPrimitiveArgsPort::SERIALIZED_SIZE]; \
Fw::SerialBuffer buf(data, sizeof(data)); \
\
status = buf.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = buf.serialize(port.args.val2); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = buf.serialize(port.args.val3); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = buf.serialize(port.args.val4); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = buf.serialize(port.args.val5); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = buf.serialize(port.args.val6); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::PRIMITIVE, buf); \
\
this->checkSerializeStatusSuccess(); \
} \
\
void Tester ::test##PORT_KIND##PortInvokeSerial(NATIVE_INT_TYPE portNum, FppTest::Types::PortStringParams& port) { \
ASSERT_TRUE(component.isConnected_serialOut_OutputPort(portNum)); \
\
Fw::SerializeStatus status; \
\
/* Check unsuccessful deserialization of first parameter */ \
U8 invalidData1[0]; \
Fw::SerialBuffer invalidBuf1(invalidData1, sizeof(invalidData1)); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::STRING, invalidBuf1); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check unsuccessful deserialization of second parameter */ \
U8 invalidData2[StringArgsPortStrings::StringSize80::SERIALIZED_SIZE]; \
Fw::SerialBuffer invalidBuf2(invalidData2, sizeof(invalidData2)); \
\
status = invalidBuf2.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::STRING, invalidBuf2); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check unsuccessful deserialization of third parameter */ \
U8 invalidData3[StringArgsPortStrings::StringSize80::SERIALIZED_SIZE * 2]; \
Fw::SerialBuffer invalidBuf3(invalidData3, sizeof(invalidData3)); \
\
status = invalidBuf3.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = invalidBuf3.serialize(port.args.val2); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::STRING, invalidBuf3); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check unsuccessful deserialization of fourth parameter */ \
U8 invalidData4[(StringArgsPortStrings::StringSize80::SERIALIZED_SIZE * 2) + \
StringArgsPortStrings::StringSize100::SERIALIZED_SIZE]; \
Fw::SerialBuffer invalidBuf4(invalidData4, sizeof(invalidData4)); \
\
status = invalidBuf4.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = invalidBuf4.serialize(port.args.val2); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = invalidBuf4.serialize(port.args.val3); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::STRING, invalidBuf4); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check successful serialization */ \
U8 data[InputStringArgsPort::SERIALIZED_SIZE]; \
Fw::SerialBuffer buf(data, sizeof(data)); \
\
status = buf.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = buf.serialize(port.args.val2); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = buf.serialize(port.args.val3); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = buf.serialize(port.args.val4); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::STRING, buf); \
\
this->checkSerializeStatusSuccess(); \
} \
\
void Tester ::test##PORT_KIND##PortInvokeSerial(NATIVE_INT_TYPE portNum, FppTest::Types::EnumParams& port) { \
ASSERT_TRUE(component.isConnected_serialOut_OutputPort(portNum)); \
\
Fw::SerializeStatus status; \
\
/* Check unsuccessful deserialization of first parameter */ \
U8 invalidData1[0]; \
Fw::SerialBuffer invalidBuf1(invalidData1, sizeof(invalidData1)); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::ENUM, invalidBuf1); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check unsuccessful deserialization of second parameter */ \
U8 invalidData2[FormalParamEnum::SERIALIZED_SIZE]; \
Fw::SerialBuffer invalidBuf2(invalidData2, sizeof(invalidData2)); \
\
status = invalidBuf2.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::ENUM, invalidBuf2); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check successful serialization */ \
U8 data[InputEnumArgsPort::SERIALIZED_SIZE]; \
Fw::SerialBuffer buf(data, sizeof(data)); \
\
status = buf.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = buf.serialize(port.args.val2); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::ENUM, buf); \
\
this->checkSerializeStatusSuccess(); \
} \
\
void Tester ::test##PORT_KIND##PortInvokeSerial(NATIVE_INT_TYPE portNum, FppTest::Types::ArrayParams& port) { \
ASSERT_TRUE(component.isConnected_serialOut_OutputPort(portNum)); \
\
Fw::SerializeStatus status; \
\
/* Check unsuccessful deserialization of first parameter */ \
U8 invalidData1[0]; \
Fw::SerialBuffer invalidBuf1(invalidData1, sizeof(invalidData1)); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::ARRAY, invalidBuf1); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check unsuccessful deserialization of second parameter */ \
U8 invalidData2[FormalParamArray::SERIALIZED_SIZE]; \
Fw::SerialBuffer invalidBuf2(invalidData2, sizeof(invalidData2)); \
\
status = invalidBuf2.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::ARRAY, invalidBuf2); \
\
this->checkSerializeStatusBufferEmpty(); \
\
U8 data[InputArrayArgsPort::SERIALIZED_SIZE]; \
Fw::SerialBuffer buf(data, sizeof(data)); \
\
status = buf.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = buf.serialize(port.args.val2); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::ARRAY, buf); \
\
this->checkSerializeStatusSuccess(); \
} \
\
void Tester ::test##PORT_KIND##PortInvokeSerial(NATIVE_INT_TYPE portNum, FppTest::Types::StructParams& port) { \
ASSERT_TRUE(component.isConnected_serialOut_OutputPort(portNum)); \
\
Fw::SerializeStatus status; \
\
/* Check unsuccessful deserialization of first parameter */ \
U8 invalidData1[0]; \
Fw::SerialBuffer invalidBuf1(invalidData1, sizeof(invalidData1)); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::STRUCT, invalidBuf1); \
\
this->checkSerializeStatusBufferEmpty(); \
\
/* Check unsuccessful deserialization of second parameter */ \
U8 invalidData2[FormalParamStruct::SERIALIZED_SIZE]; \
Fw::SerialBuffer invalidBuf2(invalidData2, sizeof(invalidData2)); \
\
status = invalidBuf2.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::STRUCT, invalidBuf2); \
\
this->checkSerializeStatusBufferEmpty(); \
\
U8 data[InputStructArgsPort::SERIALIZED_SIZE]; \
Fw::SerialBuffer buf(data, sizeof(data)); \
\
status = buf.serialize(port.args.val1); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = buf.serialize(port.args.val2); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
this->invoke##PORT_KIND##SerialPort(SerialPortIndex::STRUCT, buf); \
\
this->checkSerializeStatusSuccess(); \
}
// ----------------------------------------------------------------------
// Check history of typed output ports
// ----------------------------------------------------------------------
#define PORT_TEST_CHECK_DEFS(PORT_KIND) \
void Tester ::test##PORT_KIND##PortCheck(FppTest::Types::NoParams& port) { \
ASSERT_FROM_PORT_HISTORY_SIZE(1); \
ASSERT_from_noArgsOut_SIZE(1); \
} \
\
void Tester ::test##PORT_KIND##PortCheck(FppTest::Types::PrimitiveParams& port) { \
ASSERT_FROM_PORT_HISTORY_SIZE(1); \
ASSERT_from_primitiveArgsOut_SIZE(1); \
ASSERT_from_primitiveArgsOut(0, port.args.val1, port.args.val2, port.args.val3, port.args.val4, \
port.args.val5, port.args.val6); \
} \
\
void Tester ::test##PORT_KIND##PortCheck(FppTest::Types::PortStringParams& port) { \
ASSERT_FROM_PORT_HISTORY_SIZE(1); \
ASSERT_from_stringArgsOut_SIZE(1); \
ASSERT_from_stringArgsOut(0, port.args.val1, port.args.val2, port.args.val3, port.args.val4); \
} \
\
void Tester ::test##PORT_KIND##PortCheck(FppTest::Types::EnumParams& port) { \
ASSERT_FROM_PORT_HISTORY_SIZE(1); \
ASSERT_from_enumArgsOut_SIZE(1); \
ASSERT_from_enumArgsOut(0, port.args.val1, port.args.val2); \
} \
\
void Tester ::test##PORT_KIND##PortCheck(FppTest::Types::ArrayParams& port) { \
ASSERT_FROM_PORT_HISTORY_SIZE(1); \
ASSERT_from_arrayArgsOut_SIZE(1); \
ASSERT_from_arrayArgsOut(0, port.args.val1, port.args.val2); \
} \
\
void Tester ::test##PORT_KIND##PortCheck(FppTest::Types::StructParams& port) { \
ASSERT_FROM_PORT_HISTORY_SIZE(1); \
ASSERT_from_structArgsOut_SIZE(1); \
ASSERT_from_structArgsOut(0, port.args.val1, port.args.val2); \
}
#define PORT_TEST_CHECK_RETURN_DEFS(PORT_KIND) \
void Tester ::test##PORT_KIND##PortCheck(FppTest::Types::NoParamReturn& port) { \
ASSERT_FROM_PORT_HISTORY_SIZE(1); \
ASSERT_from_noArgsReturnOut_SIZE(1); \
} \
\
void Tester ::test##PORT_KIND##PortCheck(FppTest::Types::PrimitiveReturn& port) { \
ASSERT_FROM_PORT_HISTORY_SIZE(1); \
ASSERT_from_primitiveReturnOut_SIZE(1); \
ASSERT_from_primitiveReturnOut(0, port.args.val1, port.args.val2, port.args.val3, port.args.val4, \
port.args.val5, port.args.val6); \
} \
\
void Tester ::test##PORT_KIND##PortCheck(FppTest::Types::EnumReturn& port) { \
ASSERT_FROM_PORT_HISTORY_SIZE(1); \
ASSERT_from_enumReturnOut_SIZE(1); \
ASSERT_from_enumReturnOut(0, port.args.val1, port.args.val2); \
} \
\
void Tester ::test##PORT_KIND##PortCheck(FppTest::Types::ArrayReturn& port) { \
ASSERT_FROM_PORT_HISTORY_SIZE(1); \
ASSERT_from_arrayReturnOut_SIZE(1); \
ASSERT_from_arrayReturnOut(0, port.args.val1, port.args.val2); \
} \
\
void Tester ::test##PORT_KIND##PortCheck(FppTest::Types::StructReturn& port) { \
ASSERT_FROM_PORT_HISTORY_SIZE(1); \
ASSERT_from_structReturnOut_SIZE(1); \
ASSERT_from_structReturnOut(0, port.args.val1, port.args.val2); \
}
// ----------------------------------------------------------------------
// Check serial output ports
// ----------------------------------------------------------------------
#define PORT_TEST_CHECK_SERIAL_DEFS(PORT_KIND) \
void Tester ::test##PORT_KIND##PortCheckSerial(FppTest::Types::NoParams& port) {} \
\
void Tester ::test##PORT_KIND##PortCheckSerial(FppTest::Types::PrimitiveParams& port) { \
Fw::SerializeStatus status; \
U32 u32, u32Ref; \
F32 f32, f32Ref; \
bool b, bRef; \
\
status = this->primitiveBuf.deserialize(u32); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = this->primitiveBuf.deserialize(u32Ref); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = this->primitiveBuf.deserialize(f32); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = this->primitiveBuf.deserialize(f32Ref); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = this->primitiveBuf.deserialize(b); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = this->primitiveBuf.deserialize(bRef); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
ASSERT_EQ(u32, port.args.val1); \
ASSERT_EQ(u32Ref, port.args.val2); \
ASSERT_EQ(f32, port.args.val3); \
ASSERT_EQ(f32Ref, port.args.val4); \
ASSERT_EQ(b, port.args.val5); \
ASSERT_EQ(bRef, port.args.val6); \
} \
\
void Tester ::test##PORT_KIND##PortCheckSerial(FppTest::Types::PortStringParams& port) { \
Fw::SerializeStatus status; \
StringArgsPortStrings::StringSize80 str80, str80Ref; \
StringArgsPortStrings::StringSize100 str100, str100Ref; \
\
status = this->stringBuf.deserialize(str80); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = this->stringBuf.deserialize(str80Ref); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = this->stringBuf.deserialize(str100); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = this->stringBuf.deserialize(str100Ref); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
ASSERT_EQ(str80, port.args.val1); \
ASSERT_EQ(str80Ref, port.args.val2); \
ASSERT_EQ(str100, port.args.val3); \
ASSERT_EQ(str100Ref, port.args.val4); \
} \
\
void Tester ::test##PORT_KIND##PortCheckSerial(FppTest::Types::EnumParams& port) { \
Fw::SerializeStatus status; \
FormalParamEnum en, enRef; \
\
status = this->enumBuf.deserialize(en); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = this->enumBuf.deserialize(enRef); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
ASSERT_EQ(en, port.args.val1); \
ASSERT_EQ(enRef, port.args.val2); \
} \
\
void Tester ::test##PORT_KIND##PortCheckSerial(FppTest::Types::ArrayParams& port) { \
Fw::SerializeStatus status; \
FormalParamArray a, aRef; \
\
status = this->arrayBuf.deserialize(a); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = this->arrayBuf.deserialize(aRef); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
ASSERT_EQ(a, port.args.val1); \
ASSERT_EQ(aRef, port.args.val2); \
} \
\
void Tester ::test##PORT_KIND##PortCheckSerial(FppTest::Types::StructParams& port) { \
Fw::SerializeStatus status; \
FormalParamStruct s, sRef; \
\
status = this->structBuf.deserialize(s); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
status = this->structBuf.deserialize(sRef); \
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK); \
\
ASSERT_EQ(s, port.args.val1); \
ASSERT_EQ(sRef, port.args.val2); \
}
#define PORT_TEST_DEFS(PORT_KIND) \
PORT_TEST_INVOKE_DEFS(PORT_KIND) \
PORT_TEST_INVOKE_RETURN_DEFS(PORT_KIND) \
PORT_TEST_INVOKE_SERIAL_HELPER_DEF(PORT_KIND) \
PORT_TEST_INVOKE_SERIAL_DEFS(PORT_KIND) \
PORT_TEST_CHECK_DEFS(PORT_KIND) \
PORT_TEST_CHECK_RETURN_DEFS(PORT_KIND) \
PORT_TEST_CHECK_SERIAL_DEFS(PORT_KIND)
#define PORT_TEST_DEFS_ASYNC \
PORT_TEST_INVOKE_DEFS(Async) \
PORT_TEST_INVOKE_SERIAL_HELPER_DEF_ASYNC \
PORT_TEST_INVOKE_SERIAL_DEFS(Async) \
PORT_TEST_CHECK_DEFS(Async) \
PORT_TEST_CHECK_SERIAL_DEFS(Async)
| hpp |
fprime | data/projects/fprime/FppTest/component/tests/AsyncPortTests.cpp | // ======================================================================
// \title AsyncPortTests.cpp
// \author T. Chieu
// \brief cpp file for async port tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "PortTests.hpp"
#include "Tester.hpp"
PORT_TEST_DEFS_ASYNC
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/TimeTests.cpp | // ======================================================================
// \title TimeTests.cpp
// \author T. Chieu
// \brief cpp file for time tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Fw/Time/Time.hpp"
#include "STest/Pick/Pick.hpp"
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Time test
// ----------------------------------------------------------------------
void Tester ::testTime() {
Fw::Time time(STest::Pick::any(), STest::Pick::any());
Fw::Time zero_time(TB_NONE, 0, 0);
Fw::Time result;
this->setTestTime(time);
result = component.getTime();
ASSERT_EQ(result, zero_time);
this->connectTimeGetOut();
ASSERT_TRUE(component.isConnected_timeGetOut_OutputPort(0));
result = component.getTime();
ASSERT_EQ(result, time);
this->connectSpecialPortsSerial();
ASSERT_TRUE(component.isConnected_timeGetOut_OutputPort(0));
result = component.getTime();
ASSERT_EQ(result, time);
}
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/TesterHandlers.cpp | // ======================================================================
// \title TesterHandlers.cpp
// \author T. Chieu
// \brief cpp file for tester handler functions
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
void Tester ::from_arrayArgsOut_handler(const NATIVE_INT_TYPE portNum,
const FormalParamArray& a,
FormalParamArray& aRef) {
this->pushFromPortEntry_arrayArgsOut(a, aRef);
}
FormalParamArray Tester ::from_arrayReturnOut_handler(const NATIVE_INT_TYPE portNum,
const FormalParamArray& a,
FormalParamArray& aRef) {
this->pushFromPortEntry_arrayReturnOut(a, aRef);
return arrayReturnVal.val;
}
void Tester ::from_enumArgsOut_handler(const NATIVE_INT_TYPE portNum,
const FormalParamEnum& en,
FormalParamEnum& enRef) {
this->pushFromPortEntry_enumArgsOut(en, enRef);
}
FormalParamEnum Tester ::from_enumReturnOut_handler(const NATIVE_INT_TYPE portNum,
const FormalParamEnum& en,
FormalParamEnum& enRef) {
this->pushFromPortEntry_enumReturnOut(en, enRef);
return enumReturnVal.val;
}
void Tester ::from_noArgsOut_handler(const NATIVE_INT_TYPE portNum) {
this->pushFromPortEntry_noArgsOut();
}
bool Tester ::from_noArgsReturnOut_handler(const NATIVE_INT_TYPE portNum) {
this->pushFromPortEntry_noArgsReturnOut();
return noParamReturnVal.val;
}
void Tester ::from_primitiveArgsOut_handler(const NATIVE_INT_TYPE portNum,
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef) {
this->pushFromPortEntry_primitiveArgsOut(u32, u32Ref, f32, f32Ref, b, bRef);
}
U32 Tester ::from_primitiveReturnOut_handler(const NATIVE_INT_TYPE portNum,
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef) {
this->pushFromPortEntry_primitiveReturnOut(u32, u32Ref, f32, f32Ref, b, bRef);
return primitiveReturnVal.val;
}
void Tester ::from_stringArgsOut_handler(const NATIVE_INT_TYPE portNum,
const str80String& str80,
str80RefString& str80Ref,
const str100String& str100,
str100RefString& str100Ref) {
this->pushFromPortEntry_stringArgsOut(str80, str80Ref, str100, str100Ref);
}
void Tester ::from_structArgsOut_handler(const NATIVE_INT_TYPE portNum,
const FormalParamStruct& s,
FormalParamStruct& sRef) {
this->pushFromPortEntry_structArgsOut(s, sRef);
}
FormalParamStruct Tester ::from_structReturnOut_handler(const NATIVE_INT_TYPE portNum,
const FormalParamStruct& s,
FormalParamStruct& sRef) {
this->pushFromPortEntry_structReturnOut(s, sRef);
return structReturnVal.val;
}
// ----------------------------------------------------------------------
// Handlers for serial from ports
// ----------------------------------------------------------------------
void Tester ::from_serialOut_handler(NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase& Buffer /*!< The serialization buffer*/
) {
Fw::SerializeStatus status;
switch (portNum) {
case SerialPortIndex::NO_ARGS:
status = Fw::FW_SERIALIZE_OK;
break;
case SerialPortIndex::PRIMITIVE:
status = Buffer.copyRaw(this->primitiveBuf, Buffer.getBuffCapacity());
break;
case SerialPortIndex::STRING:
status = Buffer.copyRaw(this->stringBuf, Buffer.getBuffCapacity());
break;
case SerialPortIndex::ENUM:
status = Buffer.copyRaw(this->enumBuf, Buffer.getBuffCapacity());
break;
case SerialPortIndex::ARRAY:
status = Buffer.copyRaw(this->arrayBuf, Buffer.getBuffCapacity());
break;
case SerialPortIndex::STRUCT:
status = Buffer.copyRaw(this->structBuf, Buffer.getBuffCapacity());
break;
}
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
}
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/AsyncTests.cpp | // ======================================================================
// \title AsyncTests.cpp
// \author T. Chieu
// \brief cpp file for async component tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FppTest/component/types/FormalParamTypes.hpp"
#include "FppTest/typed_tests/ComponentTest.hpp"
#include "FppTest/typed_tests/PortTest.hpp"
// Typed async port tests
using TypedAsyncPortTestImplementations = ::testing::Types<FppTest::Types::NoParams,
FppTest::Types::PrimitiveParams,
FppTest::Types::PortStringParams,
FppTest::Types::EnumParams,
FppTest::Types::ArrayParams,
FppTest::Types::StructParams>;
INSTANTIATE_TYPED_TEST_SUITE_P(FppTest, TypedAsyncPortTest, TypedAsyncPortTestImplementations);
// Serial async port tests
using SerialAsyncPortTestImplementations = ::testing::Types<FppTest::Types::NoParams,
FppTest::Types::PrimitiveParams,
FppTest::Types::PortStringParams,
FppTest::Types::EnumParams,
FppTest::Types::ArrayParams,
FppTest::Types::StructParams>;
INSTANTIATE_TYPED_TEST_SUITE_P(FppTest, SerialAsyncPortTest, SerialAsyncPortTestImplementations);
// Async command tests
using AsyncCommandTestImplementations = ::testing::Types<FppTest::Types::NoParams,
FppTest::Types::PrimitiveParams,
FppTest::Types::CmdStringParams,
FppTest::Types::EnumParam,
FppTest::Types::ArrayParam,
FppTest::Types::StructParam>;
INSTANTIATE_TYPED_TEST_SUITE_P(FppTest, ComponentAsyncCommandTest, AsyncCommandTestImplementations);
// Internal interface tests
using InternalInterfaceTestImplementations = ::testing::Types<FppTest::Types::NoParams,
FppTest::Types::PrimitiveParams,
FppTest::Types::InternalInterfaceStringParams,
FppTest::Types::EnumParam,
FppTest::Types::ArrayParam,
FppTest::Types::StructParam>;
INSTANTIATE_TYPED_TEST_SUITE_P(FppTest, ComponentInternalInterfaceTest, InternalInterfaceTestImplementations);
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/CmdTests.hpp | // ======================================================================
// \title CmdTests.hpp
// \author T. Chieu
// \brief hpp file for command tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Command test declarations
// ----------------------------------------------------------------------
#define CMD_TEST_INVOKE_DECL(TYPE, ASYNC) void invoke##ASYNC##Command(FppTest::Types::TYPE& data);
#define CMD_TEST_INVOKE_DECLS \
void invokeCommand(FwOpcodeType opcode, Fw::CmdArgBuffer& buf); \
CMD_TEST_INVOKE_DECL(NoParams, ) \
CMD_TEST_INVOKE_DECL(PrimitiveParams, ) \
CMD_TEST_INVOKE_DECL(CmdStringParams, ) \
CMD_TEST_INVOKE_DECL(EnumParam, ) \
CMD_TEST_INVOKE_DECL(ArrayParam, ) \
CMD_TEST_INVOKE_DECL(StructParam, )
#define CMD_TEST_INVOKE_DECLS_ASYNC \
void invokeAsyncCommand(FwOpcodeType opcode, Fw::CmdArgBuffer& buf); \
CMD_TEST_INVOKE_DECL(NoParams, Async) \
CMD_TEST_INVOKE_DECL(PrimitiveParams, Async) \
CMD_TEST_INVOKE_DECL(CmdStringParams, Async) \
CMD_TEST_INVOKE_DECL(EnumParam, Async) \
CMD_TEST_INVOKE_DECL(ArrayParam, Async) \
CMD_TEST_INVOKE_DECL(StructParam, Async)
#define CMD_TEST_DECL(TYPE, ASYNC) void test##ASYNC##Command(NATIVE_INT_TYPE portNum, FppTest::Types::TYPE& data);
#define CMD_TEST_DECLS \
CMD_TEST_INVOKE_DECLS \
CMD_TEST_DECL(NoParams, ) \
CMD_TEST_DECL(PrimitiveParams, ) \
CMD_TEST_DECL(CmdStringParams, ) \
CMD_TEST_DECL(EnumParam, ) \
CMD_TEST_DECL(ArrayParam, ) \
CMD_TEST_DECL(StructParam, )
#define CMD_TEST_DECLS_ASYNC \
CMD_TEST_INVOKE_DECLS_ASYNC \
CMD_TEST_DECL(NoParams, Async) \
CMD_TEST_DECL(PrimitiveParams, Async) \
CMD_TEST_DECL(CmdStringParams, Async) \
CMD_TEST_DECL(EnumParam, Async) \
CMD_TEST_DECL(ArrayParam, Async) \
CMD_TEST_DECL(StructParam, Async)
// ----------------------------------------------------------------------
// Command test definitions
// ----------------------------------------------------------------------
#define CMD_TEST_INVOKE_DEFS \
void Tester ::invokeCommand(FwOpcodeType opcode, Fw::CmdArgBuffer& buf) { \
this->sendRawCmd(opcode, 1, buf); \
} \
\
void Tester ::invokeCommand(FppTest::Types::NoParams& data) { \
this->sendCmd_CMD_NO_ARGS(0, 1); \
} \
\
void Tester ::invokeCommand(FppTest::Types::PrimitiveParams& data) { \
this->sendCmd_CMD_PRIMITIVE(0, 1, data.args.val1, data.args.val2, data.args.val3, data.args.val4, \
data.args.val5, data.args.val6); \
} \
\
void Tester ::invokeCommand(FppTest::Types::CmdStringParams& data) { \
this->sendCmd_CMD_STRINGS(0, 1, data.args.val1, data.args.val2); \
} \
\
void Tester ::invokeCommand(FppTest::Types::EnumParam& data) { \
this->sendCmd_CMD_ENUM(0, 1, data.args.val); \
} \
\
void Tester ::invokeCommand(FppTest::Types::ArrayParam& data) { \
this->sendCmd_CMD_ARRAY(0, 1, data.args.val); \
} \
\
void Tester ::invokeCommand(FppTest::Types::StructParam& data) { \
this->sendCmd_CMD_STRUCT(0, 1, data.args.val); \
}
#define CMD_TEST_INVOKE_DEFS_ASYNC \
void Tester ::invokeAsyncCommand(FwOpcodeType opcode, Fw::CmdArgBuffer& buf) { \
Fw::QueuedComponentBase::MsgDispatchStatus status; \
\
this->sendRawCmd(opcode, 1, buf); \
status = this->doDispatch(); \
\
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK); \
} \
\
void Tester ::invokeAsyncCommand(FppTest::Types::NoParams& data) { \
Fw::QueuedComponentBase::MsgDispatchStatus status; \
\
this->sendCmd_CMD_ASYNC_NO_ARGS(0, 1); \
status = this->doDispatch(); \
\
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK); \
} \
\
void Tester ::invokeAsyncCommand(FppTest::Types::PrimitiveParams& data) { \
Fw::QueuedComponentBase::MsgDispatchStatus status; \
\
this->sendCmd_CMD_ASYNC_PRIMITIVE(0, 1, data.args.val1, data.args.val2, data.args.val3, data.args.val4, \
data.args.val5, data.args.val6); \
status = this->doDispatch(); \
\
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK); \
} \
\
void Tester ::invokeAsyncCommand(FppTest::Types::CmdStringParams& data) { \
Fw::QueuedComponentBase::MsgDispatchStatus status; \
\
this->sendCmd_CMD_ASYNC_STRINGS(0, 1, data.args.val1, data.args.val2); \
status = this->doDispatch(); \
\
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK); \
} \
\
void Tester ::invokeAsyncCommand(FppTest::Types::EnumParam& data) { \
Fw::QueuedComponentBase::MsgDispatchStatus status; \
\
this->sendCmd_CMD_ASYNC_ENUM(0, 1, data.args.val); \
status = this->doDispatch(); \
\
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK); \
} \
\
void Tester ::invokeAsyncCommand(FppTest::Types::ArrayParam& data) { \
Fw::QueuedComponentBase::MsgDispatchStatus status; \
\
this->sendCmd_CMD_ASYNC_ARRAY(0, 1, data.args.val); \
status = this->doDispatch(); \
\
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK); \
} \
\
void Tester ::invokeAsyncCommand(FppTest::Types::StructParam& data) { \
Fw::QueuedComponentBase::MsgDispatchStatus status; \
\
this->sendCmd_CMD_ASYNC_STRUCT(0, 1, data.args.val); \
status = this->doDispatch(); \
\
ASSERT_EQ(status, Fw::QueuedComponentBase::MsgDispatchStatus::MSG_DISPATCH_OK); \
}
#define CMD_TEST_DEFS(ASYNC, _ASYNC) \
void Tester ::test##ASYNC##Command(NATIVE_INT_TYPE portNum, FppTest::Types::NoParams& data) { \
ASSERT_TRUE(this->isConnected_to_cmdIn(portNum)); \
ASSERT_TRUE(component.isConnected_cmdRegOut_OutputPort(portNum)); \
ASSERT_TRUE(component.isConnected_cmdResponseOut_OutputPort(portNum)); \
\
component.regCommands(); \
\
Fw::CmdArgBuffer buf; \
\
/* Test success */ \
this->invoke##ASYNC##Command(data); \
ASSERT_CMD_RESPONSE_SIZE(1); \
ASSERT_CMD_RESPONSE(0, component.OPCODE_CMD##_ASYNC##_NO_ARGS, 1, Fw::CmdResponse::OK); \
\
/* Test too many arguments */ \
buf.serialize(0); \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_NO_ARGS, buf); \
ASSERT_CMD_RESPONSE_SIZE(2); \
ASSERT_CMD_RESPONSE(1, component.OPCODE_CMD##_ASYNC##_NO_ARGS, 1, Fw::CmdResponse::FORMAT_ERROR); \
} \
\
void Tester ::test##ASYNC##Command(NATIVE_INT_TYPE portNum, FppTest::Types::PrimitiveParams& data) { \
ASSERT_TRUE(this->isConnected_to_cmdIn(portNum)); \
ASSERT_TRUE(component.isConnected_cmdRegOut_OutputPort(portNum)); \
ASSERT_TRUE(component.isConnected_cmdResponseOut_OutputPort(portNum)); \
\
component.regCommands(); \
\
Fw::CmdArgBuffer buf; \
\
/* Test incorrect deserialization of first argument */ \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_PRIMITIVE, buf); \
ASSERT_CMD_RESPONSE_SIZE(1); \
ASSERT_CMD_RESPONSE(0, component.OPCODE_CMD##_ASYNC##_PRIMITIVE, 1, Fw::CmdResponse::FORMAT_ERROR); \
\
/* Test incorrect deserialization of second argument */ \
buf.serialize(data.args.val1); \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_PRIMITIVE, buf); \
ASSERT_CMD_RESPONSE_SIZE(2); \
ASSERT_CMD_RESPONSE(1, component.OPCODE_CMD##_ASYNC##_PRIMITIVE, 1, Fw::CmdResponse::FORMAT_ERROR); \
\
/* Test incorrect deserialization of third argument */ \
buf.serialize(data.args.val2); \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_PRIMITIVE, buf); \
ASSERT_CMD_RESPONSE_SIZE(3); \
ASSERT_CMD_RESPONSE(2, component.OPCODE_CMD##_ASYNC##_PRIMITIVE, 1, Fw::CmdResponse::FORMAT_ERROR); \
\
/* Test incorrect deserialization of fourth argument */ \
buf.serialize(data.args.val3); \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_PRIMITIVE, buf); \
ASSERT_CMD_RESPONSE_SIZE(4); \
ASSERT_CMD_RESPONSE(3, component.OPCODE_CMD##_ASYNC##_PRIMITIVE, 1, Fw::CmdResponse::FORMAT_ERROR); \
\
/* Test incorrect deserialization of fifth argument */ \
buf.serialize(data.args.val4); \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_PRIMITIVE, buf); \
ASSERT_CMD_RESPONSE_SIZE(5); \
ASSERT_CMD_RESPONSE(4, component.OPCODE_CMD##_ASYNC##_PRIMITIVE, 1, Fw::CmdResponse::FORMAT_ERROR); \
\
/* Test incorrect deserialization of sixth argument */ \
buf.serialize(data.args.val5); \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_PRIMITIVE, buf); \
ASSERT_CMD_RESPONSE_SIZE(6); \
ASSERT_CMD_RESPONSE(5, component.OPCODE_CMD##_ASYNC##_PRIMITIVE, 1, Fw::CmdResponse::FORMAT_ERROR); \
\
/* Test success */ \
buf.serialize(data.args.val6); \
this->invoke##ASYNC##Command(data); \
\
ASSERT_CMD_RESPONSE_SIZE(7); \
ASSERT_CMD_RESPONSE(6, component.OPCODE_CMD##_ASYNC##_PRIMITIVE, 1, Fw::CmdResponse::OK); \
ASSERT_EQ(component.primitiveCmd.args.val1, data.args.val1); \
ASSERT_EQ(component.primitiveCmd.args.val2, data.args.val2); \
ASSERT_EQ(component.primitiveCmd.args.val3, data.args.val3); \
ASSERT_EQ(component.primitiveCmd.args.val4, data.args.val4); \
ASSERT_EQ(component.primitiveCmd.args.val5, data.args.val5); \
ASSERT_EQ(component.primitiveCmd.args.val6, data.args.val6); \
\
/* Test too many arguments */ \
buf.serialize(data.args.val5); \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_PRIMITIVE, buf); \
ASSERT_CMD_RESPONSE_SIZE(8); \
ASSERT_CMD_RESPONSE(7, component.OPCODE_CMD##_ASYNC##_PRIMITIVE, 1, Fw::CmdResponse::FORMAT_ERROR); \
} \
\
void Tester ::test##ASYNC##Command(NATIVE_INT_TYPE portNum, FppTest::Types::CmdStringParams& data) { \
ASSERT_TRUE(this->isConnected_to_cmdIn(portNum)); \
ASSERT_TRUE(component.isConnected_cmdRegOut_OutputPort(portNum)); \
ASSERT_TRUE(component.isConnected_cmdResponseOut_OutputPort(portNum)); \
\
component.regCommands(); \
\
Fw::CmdArgBuffer buf; \
\
/* Test incorrect serialization of first argument */ \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_STRINGS, buf); \
ASSERT_CMD_RESPONSE_SIZE(1); \
ASSERT_CMD_RESPONSE(0, component.OPCODE_CMD##_ASYNC##_STRINGS, 1, Fw::CmdResponse::FORMAT_ERROR); \
\
/* Test incorrect serialization of second argument */ \
buf.serialize(data.args.val1); \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_STRINGS, buf); \
ASSERT_CMD_RESPONSE_SIZE(2); \
ASSERT_CMD_RESPONSE(1, component.OPCODE_CMD##_ASYNC##_STRINGS, 1, Fw::CmdResponse::FORMAT_ERROR); \
\
/* Test success */ \
buf.serialize(data.args.val2); \
this->invoke##ASYNC##Command(data); \
\
ASSERT_CMD_RESPONSE_SIZE(3); \
ASSERT_CMD_RESPONSE(2, component.OPCODE_CMD##_ASYNC##_STRINGS, 1, Fw::CmdResponse::OK); \
ASSERT_EQ(component.stringCmd.args.val1, data.args.val1); \
ASSERT_EQ(component.stringCmd.args.val2, data.args.val2); \
\
/* Test too many arguments */ \
buf.serialize(data.args.val1); \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_STRINGS, buf); \
ASSERT_CMD_RESPONSE_SIZE(4); \
ASSERT_CMD_RESPONSE(3, component.OPCODE_CMD##_ASYNC##_STRINGS, 1, Fw::CmdResponse::FORMAT_ERROR); \
} \
\
void Tester ::test##ASYNC##Command(NATIVE_INT_TYPE portNum, FppTest::Types::EnumParam& data) { \
ASSERT_TRUE(this->isConnected_to_cmdIn(portNum)); \
ASSERT_TRUE(component.isConnected_cmdRegOut_OutputPort(portNum)); \
ASSERT_TRUE(component.isConnected_cmdResponseOut_OutputPort(portNum)); \
\
component.regCommands(); \
\
Fw::CmdArgBuffer buf; \
\
/* Test incorrect serialization of first argument */ \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_ENUM, buf); \
ASSERT_CMD_RESPONSE_SIZE(1); \
ASSERT_CMD_RESPONSE(0, component.OPCODE_CMD##_ASYNC##_ENUM, 1, Fw::CmdResponse::FORMAT_ERROR); \
\
/* Test success */ \
buf.serialize(data.args.val); \
this->invoke##ASYNC##Command(data); \
\
ASSERT_CMD_RESPONSE_SIZE(2); \
ASSERT_CMD_RESPONSE(1, component.OPCODE_CMD##_ASYNC##_ENUM, 1, Fw::CmdResponse::OK); \
ASSERT_EQ(component.enumCmd.args.val, data.args.val); \
\
/* Test too many arguments */ \
buf.serialize(data.args.val); \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_ENUM, buf); \
ASSERT_CMD_RESPONSE_SIZE(3); \
ASSERT_CMD_RESPONSE(2, component.OPCODE_CMD##_ASYNC##_ENUM, 1, Fw::CmdResponse::FORMAT_ERROR); \
} \
\
void Tester ::test##ASYNC##Command(NATIVE_INT_TYPE portNum, FppTest::Types::ArrayParam& data) { \
ASSERT_TRUE(this->isConnected_to_cmdIn(portNum)); \
ASSERT_TRUE(component.isConnected_cmdRegOut_OutputPort(portNum)); \
ASSERT_TRUE(component.isConnected_cmdResponseOut_OutputPort(portNum)); \
\
component.regCommands(); \
\
Fw::CmdArgBuffer buf; \
\
/* Test incorrect serialization of first argument */ \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_ARRAY, buf); \
ASSERT_CMD_RESPONSE_SIZE(1); \
ASSERT_CMD_RESPONSE(0, component.OPCODE_CMD##_ASYNC##_ARRAY, 1, Fw::CmdResponse::FORMAT_ERROR); \
\
/* Test success */ \
buf.serialize(data.args.val); \
this->invoke##ASYNC##Command(data); \
\
ASSERT_CMD_RESPONSE_SIZE(2); \
ASSERT_CMD_RESPONSE(1, component.OPCODE_CMD##_ASYNC##_ARRAY, 1, Fw::CmdResponse::OK); \
ASSERT_EQ(component.arrayCmd.args.val, data.args.val); \
\
/* Test too many arguments */ \
buf.serialize(data.args.val); \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_ARRAY, buf); \
ASSERT_CMD_RESPONSE_SIZE(3); \
ASSERT_CMD_RESPONSE(2, component.OPCODE_CMD##_ASYNC##_ARRAY, 1, Fw::CmdResponse::FORMAT_ERROR); \
} \
\
void Tester ::test##ASYNC##Command(NATIVE_INT_TYPE portNum, FppTest::Types::StructParam& data) { \
ASSERT_TRUE(this->isConnected_to_cmdIn(portNum)); \
ASSERT_TRUE(component.isConnected_cmdRegOut_OutputPort(portNum)); \
ASSERT_TRUE(component.isConnected_cmdResponseOut_OutputPort(portNum)); \
\
component.regCommands(); \
\
Fw::CmdArgBuffer buf; \
\
/* Test incorrect serialization of first argument */ \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_STRUCT, buf); \
ASSERT_CMD_RESPONSE_SIZE(1); \
ASSERT_CMD_RESPONSE(0, component.OPCODE_CMD##_ASYNC##_STRUCT, 1, Fw::CmdResponse::FORMAT_ERROR); \
\
/* Test success */ \
buf.serialize(data.args.val); \
this->invoke##ASYNC##Command(data); \
\
ASSERT_CMD_RESPONSE_SIZE(2); \
ASSERT_CMD_RESPONSE(1, component.OPCODE_CMD##_ASYNC##_STRUCT, 1, Fw::CmdResponse::OK); \
ASSERT_EQ(component.structCmd.args.val, data.args.val); \
\
/* Test too many arguments */ \
buf.serialize(data.args.val); \
this->invoke##ASYNC##Command(component.OPCODE_CMD##_ASYNC##_STRUCT, buf); \
ASSERT_CMD_RESPONSE_SIZE(3); \
ASSERT_CMD_RESPONSE(2, component.OPCODE_CMD##_ASYNC##_STRUCT, 1, Fw::CmdResponse::FORMAT_ERROR); \
}
| hpp |
fprime | data/projects/fprime/FppTest/component/tests/TesterHelpers.cpp | // ======================================================================
// \title TesterHelpers.cpp
// \author T. Chieu
// \brief cpp file for tester helper functions
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void Tester ::connectPorts() {
// arrayArgsGuarded
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_arrayArgsGuarded(i, this->component.get_arrayArgsGuarded_InputPort(i));
}
// arrayArgsSync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_arrayArgsSync(i, this->component.get_arrayArgsSync_InputPort(i));
}
// arrayReturnGuarded
this->connect_to_arrayReturnGuarded(0, this->component.get_arrayReturnGuarded_InputPort(0));
// arrayReturnSync
this->connect_to_arrayReturnSync(0, this->component.get_arrayReturnSync_InputPort(0));
// cmdIn
this->connect_to_cmdIn(0, this->component.get_cmdIn_InputPort(0));
// enumArgsGuarded
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_enumArgsGuarded(i, this->component.get_enumArgsGuarded_InputPort(i));
}
// enumArgsSync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_enumArgsSync(i, this->component.get_enumArgsSync_InputPort(i));
}
// enumReturnGuarded
this->connect_to_enumReturnGuarded(0, this->component.get_enumReturnGuarded_InputPort(0));
// enumReturnSync
this->connect_to_enumReturnSync(0, this->component.get_enumReturnSync_InputPort(0));
// noArgsGuarded
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_noArgsGuarded(i, this->component.get_noArgsGuarded_InputPort(i));
}
// noArgsReturnGuarded
this->connect_to_noArgsReturnGuarded(0, this->component.get_noArgsReturnGuarded_InputPort(0));
// noArgsReturnSync
this->connect_to_noArgsReturnSync(0, this->component.get_noArgsReturnSync_InputPort(0));
// noArgsSync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_noArgsSync(i, this->component.get_noArgsSync_InputPort(i));
}
// primitiveArgsGuarded
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_primitiveArgsGuarded(i, this->component.get_primitiveArgsGuarded_InputPort(i));
}
// primitiveArgsSync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_primitiveArgsSync(i, this->component.get_primitiveArgsSync_InputPort(i));
}
// primitiveReturnGuarded
this->connect_to_primitiveReturnGuarded(0, this->component.get_primitiveReturnGuarded_InputPort(0));
// primitiveReturnSync
this->connect_to_primitiveReturnSync(0, this->component.get_primitiveReturnSync_InputPort(0));
// stringArgsGuarded
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_stringArgsGuarded(i, this->component.get_stringArgsGuarded_InputPort(i));
}
// stringArgsSync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_stringArgsSync(i, this->component.get_stringArgsSync_InputPort(i));
}
// structArgsGuarded
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_structArgsGuarded(i, this->component.get_structArgsGuarded_InputPort(i));
}
// structArgsSync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_structArgsSync(i, this->component.get_structArgsSync_InputPort(i));
}
// structReturnGuarded
this->connect_to_structReturnGuarded(0, this->component.get_structReturnGuarded_InputPort(0));
// structReturnSync
this->connect_to_structReturnSync(0, this->component.get_structReturnSync_InputPort(0));
// arrayArgsOut
this->component.set_arrayArgsOut_OutputPort(TypedPortIndex::TYPED,
this->get_from_arrayArgsOut(TypedPortIndex::TYPED));
// arrayReturnOut
this->component.set_arrayReturnOut_OutputPort(0, this->get_from_arrayReturnOut(0));
// cmdRegOut
this->component.set_cmdRegOut_OutputPort(0, this->get_from_cmdRegOut(0));
// cmdResponseOut
this->component.set_cmdResponseOut_OutputPort(0, this->get_from_cmdResponseOut(0));
// enumArgsOut
this->component.set_enumArgsOut_OutputPort(TypedPortIndex::TYPED,
this->get_from_enumArgsOut(TypedPortIndex::TYPED));
// enumReturnOut
this->component.set_enumReturnOut_OutputPort(0, this->get_from_enumReturnOut(0));
// eventOut
this->component.set_eventOut_OutputPort(0, this->get_from_eventOut(0));
// noArgsOut
this->component.set_noArgsOut_OutputPort(TypedPortIndex::TYPED, this->get_from_noArgsOut(TypedPortIndex::TYPED));
// noArgsReturnOut
this->component.set_noArgsReturnOut_OutputPort(0, this->get_from_noArgsReturnOut(0));
// primitiveArgsOut
this->component.set_primitiveArgsOut_OutputPort(TypedPortIndex::TYPED,
this->get_from_primitiveArgsOut(TypedPortIndex::TYPED));
// primitiveReturnOut
this->component.set_primitiveReturnOut_OutputPort(0, this->get_from_primitiveReturnOut(0));
// stringArgsOut
this->component.set_stringArgsOut_OutputPort(TypedPortIndex::TYPED,
this->get_from_stringArgsOut(TypedPortIndex::TYPED));
// structArgsOut
this->component.set_structArgsOut_OutputPort(TypedPortIndex::TYPED,
this->get_from_structArgsOut(TypedPortIndex::TYPED));
// structReturnOut
this->component.set_structReturnOut_OutputPort(0, this->get_from_structReturnOut(0));
// textEventOut
this->component.set_textEventOut_OutputPort(0, this->get_from_textEventOut(0));
// tlmOut
this->component.set_tlmOut_OutputPort(0, this->get_from_tlmOut(0));
// ----------------------------------------------------------------------
// Connect special ports
// ----------------------------------------------------------------------
// prmGetOut
this->component.set_prmGetOut_OutputPort(0, this->get_from_prmGetIn(0));
// ----------------------------------------------------------------------
// Connect serial output ports
// ----------------------------------------------------------------------
this->component.set_noArgsOut_OutputPort(TypedPortIndex::SERIAL,
this->get_from_serialOut(SerialPortIndex::NO_ARGS));
this->component.set_primitiveArgsOut_OutputPort(TypedPortIndex::SERIAL,
this->get_from_serialOut(SerialPortIndex::PRIMITIVE));
this->component.set_stringArgsOut_OutputPort(TypedPortIndex::SERIAL,
this->get_from_serialOut(SerialPortIndex::STRING));
this->component.set_enumArgsOut_OutputPort(TypedPortIndex::SERIAL, this->get_from_serialOut(SerialPortIndex::ENUM));
this->component.set_arrayArgsOut_OutputPort(TypedPortIndex::SERIAL,
this->get_from_serialOut(SerialPortIndex::ARRAY));
this->component.set_structArgsOut_OutputPort(TypedPortIndex::SERIAL,
this->get_from_serialOut(SerialPortIndex::STRUCT));
this->component.set_serialOut_OutputPort(SerialPortIndex::NO_ARGS,
this->get_from_noArgsOut(TypedPortIndex::SERIAL));
this->component.set_serialOut_OutputPort(SerialPortIndex::PRIMITIVE,
this->get_from_primitiveArgsOut(TypedPortIndex::SERIAL));
this->component.set_serialOut_OutputPort(SerialPortIndex::STRING,
this->get_from_stringArgsOut(TypedPortIndex::SERIAL));
this->component.set_serialOut_OutputPort(SerialPortIndex::ENUM, this->get_from_enumArgsOut(TypedPortIndex::SERIAL));
this->component.set_serialOut_OutputPort(SerialPortIndex::ARRAY,
this->get_from_arrayArgsOut(TypedPortIndex::SERIAL));
this->component.set_serialOut_OutputPort(SerialPortIndex::STRUCT,
this->get_from_structArgsOut(TypedPortIndex::SERIAL));
// ----------------------------------------------------------------------
// Connect serial input ports
// ----------------------------------------------------------------------
// serialGuarded
for (NATIVE_INT_TYPE i = 0; i < 6; ++i) {
this->connect_to_serialGuarded(i, this->component.get_serialGuarded_InputPort(i));
}
// serialSync
for (NATIVE_INT_TYPE i = 0; i < 6; ++i) {
this->connect_to_serialSync(i, this->component.get_serialSync_InputPort(i));
}
}
void Tester ::connectPrmSetIn() {
// prmSetOut
this->component.set_prmSetOut_OutputPort(0, this->get_from_prmSetIn(0));
}
void Tester ::connectTimeGetOut() {
// timeGetOut
this->component.set_timeGetOut_OutputPort(0, this->get_from_timeGetOut(0));
}
void Tester ::connectSpecialPortsSerial() {
// cmdResponseOut
this->component.set_cmdResponseOut_OutputPort(0, this->get_from_serialOut(0));
// cmdRegOut
this->component.set_cmdRegOut_OutputPort(0, this->get_from_serialOut(0));
// eventOut
this->component.set_eventOut_OutputPort(0, this->get_from_serialOut(0));
// textEventOut
this->component.set_textEventOut_OutputPort(0, this->get_from_serialOut(0));
// tlmOut
this->component.set_tlmOut_OutputPort(0, this->get_from_serialOut(0));
// prmSetOut
this->component.set_prmSetOut_OutputPort(0, this->get_from_serialOut(0));
// timeGetOut
this->component.set_timeGetOut_OutputPort(0, this->get_from_serialOut(0));
}
void Tester ::setPrmValid(Fw::ParamValid valid) {
this->prmValid = valid;
}
void Tester ::checkSerializeStatusSuccess() {
ASSERT_EQ(component.serializeStatus, Fw::FW_SERIALIZE_OK);
}
void Tester ::checkSerializeStatusBufferEmpty() {
ASSERT_EQ(component.serializeStatus, Fw::FW_DESERIALIZE_BUFFER_EMPTY);
}
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/Tests.cpp | // ======================================================================
// \title Tests.cpp
// \author T. Chieu
// \brief cpp file for component tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FppTest/component/active/StringArgsPortAc.hpp"
#include "FppTest/component/types/FormalParamTypes.hpp"
#include "FppTest/typed_tests/ComponentTest.hpp"
#include "FppTest/typed_tests/PortTest.hpp"
#include "FppTest/typed_tests/StringTest.hpp"
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(TypedAsyncPortTest);
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SerialAsyncPortTest);
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(ComponentAsyncCommandTest);
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(ComponentInternalInterfaceTest);
// Typed port tests
using TypedPortTestImplementations = ::testing::Types<FppTest::Types::NoParams,
FppTest::Types::PrimitiveParams,
FppTest::Types::PortStringParams,
FppTest::Types::EnumParams,
FppTest::Types::ArrayParams,
FppTest::Types::StructParams,
FppTest::Types::NoParamReturn,
FppTest::Types::PrimitiveReturn,
FppTest::Types::EnumReturn,
FppTest::Types::ArrayReturn,
FppTest::Types::StructReturn>;
INSTANTIATE_TYPED_TEST_SUITE_P(FppTest, TypedPortTest, TypedPortTestImplementations);
// Serial port tests
using SerialPortTestImplementations = ::testing::Types<FppTest::Types::NoParams,
FppTest::Types::PrimitiveParams,
FppTest::Types::PortStringParams,
FppTest::Types::EnumParams,
FppTest::Types::ArrayParams,
FppTest::Types::StructParams>;
INSTANTIATE_TYPED_TEST_SUITE_P(FppTest, SerialPortTest, SerialPortTestImplementations);
// String tests
using StringTestImplementations =
::testing::Types<StringArgsPortStrings::StringSize80, StringArgsPortStrings::StringSize100>;
INSTANTIATE_TYPED_TEST_SUITE_P(Array, StringTest, StringTestImplementations);
template <>
U32 FppTest::String::getSize<StringArgsPortStrings::StringSize100>() {
return 100;
}
// Command tests
using CommandTestImplementations = ::testing::Types<FppTest::Types::NoParams,
FppTest::Types::PrimitiveParams,
FppTest::Types::CmdStringParams,
FppTest::Types::EnumParam,
FppTest::Types::ArrayParam,
FppTest::Types::StructParam>;
INSTANTIATE_TYPED_TEST_SUITE_P(FppTest, ComponentCommandTest, CommandTestImplementations);
// Event tests
using EventTestImplementations = ::testing::Types<FppTest::Types::NoParams,
FppTest::Types::PrimitiveParams,
FppTest::Types::LogStringParams,
FppTest::Types::EnumParam,
FppTest::Types::ArrayParam,
FppTest::Types::StructParam,
FppTest::Types::BoolParam>;
INSTANTIATE_TYPED_TEST_SUITE_P(FppTest, ComponentEventTest, EventTestImplementations);
// Telemetry tests
using TelemetryTestImplementations = ::testing::Types<FppTest::Types::U32Param,
FppTest::Types::F32Param,
FppTest::Types::TlmStringParam,
FppTest::Types::EnumParam,
FppTest::Types::ArrayParam,
FppTest::Types::StructParam>;
INSTANTIATE_TYPED_TEST_SUITE_P(FppTest, ComponentTelemetryTest, TelemetryTestImplementations);
// Parameter tests
TEST(ComponentParameterTest, ParameterTest) {
Tester tester;
tester.setPrmValid(Fw::ParamValid::VALID);
tester.testParam();
tester.setPrmValid(Fw::ParamValid::INVALID);
tester.testParam();
}
// Parameter tests
using ParamCommandTestImplementations = ::testing::Types<FppTest::Types::BoolParam,
FppTest::Types::U32Param,
FppTest::Types::PrmStringParam,
FppTest::Types::EnumParam,
FppTest::Types::ArrayParam,
FppTest::Types::StructParam>;
INSTANTIATE_TYPED_TEST_SUITE_P(FppTest, ComponentParamCommandTest, ParamCommandTestImplementations);
// Time tests
TEST(ComponentTimeTest, TimeTest) {
Tester tester;
tester.testTime();
}
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/CmdTests.cpp | // ======================================================================
// \title CmdTests.cpp
// \author T. Chieu
// \brief cpp file for command tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "CmdTests.hpp"
#include "Fw/Cmd/CmdArgBuffer.hpp"
CMD_TEST_INVOKE_DEFS
CMD_TEST_DEFS(, )
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/EventTests.hpp | // ======================================================================
// \title EventTests.hpp
// \author T. Chieu
// \brief hpp file for event tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
// ----------------------------------------------------------------------
// Event test declarations
// ----------------------------------------------------------------------
#define EVENT_TEST_DECL(TYPE) void testEvent(NATIVE_INT_TYPE portNum, FppTest::Types::TYPE& data);
#define EVENT_TEST_HELPER_DECL(TYPE) \
void testEventHelper(NATIVE_INT_TYPE portNum, FppTest::Types::TYPE& data, NATIVE_UINT_TYPE size);
#define EVENT_TEST_DECLS \
EVENT_TEST_DECL(NoParams) \
EVENT_TEST_HELPER_DECL(PrimitiveParams) \
EVENT_TEST_DECL(PrimitiveParams) \
EVENT_TEST_DECL(LogStringParams) \
EVENT_TEST_DECL(EnumParam) \
EVENT_TEST_HELPER_DECL(ArrayParam) \
EVENT_TEST_DECL(ArrayParam) \
EVENT_TEST_DECL(StructParam) \
EVENT_TEST_HELPER_DECL(BoolParam) \
EVENT_TEST_DECL(BoolParam)
| hpp |
fprime | data/projects/fprime/FppTest/component/tests/ParamTests.cpp | // ======================================================================
// \title ParamTests.cpp
// \author T. Chieu
// \brief cpp file for parameter tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Parameter tests
// ----------------------------------------------------------------------
void Tester ::testParam() {
ASSERT_TRUE(component.isConnected_prmGetOut_OutputPort(0));
component.loadParameters();
Fw::ParamValid valid;
bool boolVal = component.paramGet_ParamBool(valid);
ASSERT_EQ(valid, prmValid);
if (valid == Fw::ParamValid::VALID) {
ASSERT_EQ(boolVal, boolPrm.args.val);
}
U32 u32Val = component.paramGet_ParamU32(valid);
ASSERT_EQ(valid, prmValid);
if (valid == Fw::ParamValid::VALID) {
ASSERT_EQ(u32Val, u32Prm.args.val);
}
Fw::ParamString stringVal = component.paramGet_ParamString(valid);
if (valid == Fw::ParamValid::VALID) {
ASSERT_EQ(stringVal, stringPrm.args.val);
} else {
ASSERT_EQ(valid, Fw::ParamValid::DEFAULT);
}
FormalParamEnum enumVal = component.paramGet_ParamEnum(valid);
ASSERT_EQ(valid, prmValid);
if (valid == Fw::ParamValid::VALID) {
ASSERT_EQ(enumVal, enumPrm.args.val);
}
FormalParamArray arrayVal = component.paramGet_ParamArray(valid);
if (valid == Fw::ParamValid::VALID) {
ASSERT_EQ(arrayVal, arrayPrm.args.val);
} else {
ASSERT_EQ(valid, Fw::ParamValid::DEFAULT);
}
FormalParamStruct structVal = component.paramGet_ParamStruct(valid);
ASSERT_EQ(valid, prmValid);
if (valid == Fw::ParamValid::VALID) {
ASSERT_EQ(structVal, structPrm.args.val);
}
}
void Tester ::testParamCommand(NATIVE_INT_TYPE portNum, FppTest::Types::BoolParam& data) {
Fw::CmdArgBuffer buf;
// Test unsuccessful saving of param
this->sendRawCmd(component.OPCODE_PARAMBOOL_SAVE, 1, buf);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0, component.OPCODE_PARAMBOOL_SAVE, 1, Fw::CmdResponse::EXECUTION_ERROR);
this->connectPrmSetIn();
ASSERT_TRUE(component.isConnected_prmSetOut_OutputPort(portNum));
// Test incorrect deserialization when setting param
this->sendRawCmd(component.OPCODE_PARAMBOOL_SET, 1, buf);
ASSERT_CMD_RESPONSE_SIZE(2);
ASSERT_CMD_RESPONSE(1, component.OPCODE_PARAMBOOL_SET, 1, Fw::CmdResponse::VALIDATION_ERROR);
// Test successful setting of param
this->paramSet_ParamBool(data.args.val, Fw::ParamValid::VALID);
this->paramSend_ParamBool(0, 1);
ASSERT_CMD_RESPONSE_SIZE(3);
ASSERT_CMD_RESPONSE(2, component.OPCODE_PARAMBOOL_SET, 1, Fw::CmdResponse::OK);
// Test successful saving of param
this->paramSave_ParamBool(0, 1);
ASSERT_CMD_RESPONSE_SIZE(4);
ASSERT_CMD_RESPONSE(3, component.OPCODE_PARAMBOOL_SAVE, 1, Fw::CmdResponse::OK);
ASSERT_EQ(boolPrm.args.val, data.args.val);
}
void Tester ::testParamCommand(NATIVE_INT_TYPE portNum, FppTest::Types::U32Param& data) {
Fw::CmdArgBuffer buf;
// Test unsuccessful saving of param
this->sendRawCmd(component.OPCODE_PARAMU32_SAVE, 1, buf);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0, component.OPCODE_PARAMU32_SAVE, 1, Fw::CmdResponse::EXECUTION_ERROR);
this->connectPrmSetIn();
ASSERT_TRUE(component.isConnected_prmSetOut_OutputPort(portNum));
// Test incorrect deserialization when setting param
this->sendRawCmd(component.OPCODE_PARAMU32_SET, 1, buf);
ASSERT_CMD_RESPONSE_SIZE(2);
ASSERT_CMD_RESPONSE(1, component.OPCODE_PARAMU32_SET, 1, Fw::CmdResponse::VALIDATION_ERROR);
// Test successful setting of param
this->paramSet_ParamU32(data.args.val, Fw::ParamValid::VALID);
this->paramSend_ParamU32(0, 1);
ASSERT_CMD_RESPONSE_SIZE(3);
ASSERT_CMD_RESPONSE(2, component.OPCODE_PARAMU32_SET, 1, Fw::CmdResponse::OK);
// Test successful saving of param
this->paramSave_ParamU32(0, 1);
ASSERT_CMD_RESPONSE_SIZE(4);
ASSERT_CMD_RESPONSE(3, component.OPCODE_PARAMU32_SAVE, 1, Fw::CmdResponse::OK);
ASSERT_EQ(u32Prm.args.val, data.args.val);
}
void Tester ::testParamCommand(NATIVE_INT_TYPE portNum, FppTest::Types::PrmStringParam& data) {
Fw::CmdArgBuffer buf;
// Test unsuccessful saving of param
this->sendRawCmd(component.OPCODE_PARAMSTRING_SAVE, 1, buf);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0, component.OPCODE_PARAMSTRING_SAVE, 1, Fw::CmdResponse::EXECUTION_ERROR);
this->connectPrmSetIn();
ASSERT_TRUE(component.isConnected_prmSetOut_OutputPort(portNum));
// Test incorrect deserialization when setting param
this->sendRawCmd(component.OPCODE_PARAMSTRING_SET, 1, buf);
ASSERT_CMD_RESPONSE_SIZE(2);
ASSERT_CMD_RESPONSE(1, component.OPCODE_PARAMSTRING_SET, 1, Fw::CmdResponse::VALIDATION_ERROR);
// Test successful setting of param
this->paramSet_ParamString(data.args.val, Fw::ParamValid::VALID);
this->paramSend_ParamString(0, 1);
ASSERT_CMD_RESPONSE_SIZE(3);
ASSERT_CMD_RESPONSE(2, component.OPCODE_PARAMSTRING_SET, 1, Fw::CmdResponse::OK);
// Test successful saving of param
this->paramSave_ParamString(0, 1);
ASSERT_CMD_RESPONSE_SIZE(4);
ASSERT_CMD_RESPONSE(3, component.OPCODE_PARAMSTRING_SAVE, 1, Fw::CmdResponse::OK);
ASSERT_EQ(stringPrm.args.val, data.args.val);
}
void Tester ::testParamCommand(NATIVE_INT_TYPE portNum, FppTest::Types::EnumParam& data) {
Fw::CmdArgBuffer buf;
// Test unsuccessful saving of param
this->sendRawCmd(component.OPCODE_PARAMENUM_SAVE, 1, buf);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0, component.OPCODE_PARAMENUM_SAVE, 1, Fw::CmdResponse::EXECUTION_ERROR);
this->connectPrmSetIn();
ASSERT_TRUE(component.isConnected_prmSetOut_OutputPort(portNum));
// Test incorrect deserialization when setting param
this->sendRawCmd(component.OPCODE_PARAMENUM_SET, 1, buf);
ASSERT_CMD_RESPONSE_SIZE(2);
ASSERT_CMD_RESPONSE(1, component.OPCODE_PARAMENUM_SET, 1, Fw::CmdResponse::VALIDATION_ERROR);
// Test successful setting of param
this->paramSet_ParamEnum(data.args.val, Fw::ParamValid::VALID);
this->paramSend_ParamEnum(0, 1);
ASSERT_CMD_RESPONSE_SIZE(3);
ASSERT_CMD_RESPONSE(2, component.OPCODE_PARAMENUM_SET, 1, Fw::CmdResponse::OK);
// Test successful saving of param
this->paramSave_ParamEnum(0, 1);
ASSERT_CMD_RESPONSE_SIZE(4);
ASSERT_CMD_RESPONSE(3, component.OPCODE_PARAMENUM_SAVE, 1, Fw::CmdResponse::OK);
ASSERT_EQ(enumPrm.args.val, data.args.val);
}
void Tester ::testParamCommand(NATIVE_INT_TYPE portNum, FppTest::Types::ArrayParam& data) {
Fw::CmdArgBuffer buf;
// Test unsuccessful saving of param
this->sendRawCmd(component.OPCODE_PARAMARRAY_SAVE, 1, buf);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0, component.OPCODE_PARAMARRAY_SAVE, 1, Fw::CmdResponse::EXECUTION_ERROR);
this->connectPrmSetIn();
ASSERT_TRUE(component.isConnected_prmSetOut_OutputPort(portNum));
// Test incorrect deserialization when setting param
this->sendRawCmd(component.OPCODE_PARAMARRAY_SET, 1, buf);
ASSERT_CMD_RESPONSE_SIZE(2);
ASSERT_CMD_RESPONSE(1, component.OPCODE_PARAMARRAY_SET, 1, Fw::CmdResponse::VALIDATION_ERROR);
// Test successful setting of param
this->paramSet_ParamArray(data.args.val, Fw::ParamValid::VALID);
this->paramSend_ParamArray(0, 1);
ASSERT_CMD_RESPONSE_SIZE(3);
ASSERT_CMD_RESPONSE(2, component.OPCODE_PARAMARRAY_SET, 1, Fw::CmdResponse::OK);
// Test successful saving of param
this->paramSave_ParamArray(0, 1);
ASSERT_CMD_RESPONSE_SIZE(4);
ASSERT_CMD_RESPONSE(3, component.OPCODE_PARAMARRAY_SAVE, 1, Fw::CmdResponse::OK);
ASSERT_EQ(arrayPrm.args.val, data.args.val);
}
void Tester ::testParamCommand(NATIVE_INT_TYPE portNum, FppTest::Types::StructParam& data) {
Fw::CmdArgBuffer buf;
// Test unsuccessful saving of param
this->sendRawCmd(component.OPCODE_PARAMSTRUCT_SAVE, 1, buf);
ASSERT_CMD_RESPONSE_SIZE(1);
ASSERT_CMD_RESPONSE(0, component.OPCODE_PARAMSTRUCT_SAVE, 1, Fw::CmdResponse::EXECUTION_ERROR);
this->connectPrmSetIn();
ASSERT_TRUE(component.isConnected_prmSetOut_OutputPort(portNum));
// Test incorrect deserialization when setting param
this->sendRawCmd(component.OPCODE_PARAMSTRUCT_SET, 1, buf);
ASSERT_CMD_RESPONSE_SIZE(2);
ASSERT_CMD_RESPONSE(1, component.OPCODE_PARAMSTRUCT_SET, 1, Fw::CmdResponse::VALIDATION_ERROR);
// Test successful setting of param
this->paramSet_ParamStruct(data.args.val, Fw::ParamValid::VALID);
this->paramSend_ParamStruct(0, 1);
ASSERT_CMD_RESPONSE_SIZE(3);
ASSERT_CMD_RESPONSE(2, component.OPCODE_PARAMSTRUCT_SET, 1, Fw::CmdResponse::OK);
// Test successful saving of param
this->paramSave_ParamStruct(0, 1);
ASSERT_CMD_RESPONSE_SIZE(4);
ASSERT_CMD_RESPONSE(3, component.OPCODE_PARAMSTRUCT_SAVE, 1, Fw::CmdResponse::OK);
ASSERT_EQ(structPrm.args.val, data.args.val);
}
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/PortTests.cpp | // ======================================================================
// \title PortTests.cpp
// \author T. Chieu
// \brief cpp file for port tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "PortTests.hpp"
#include "Tester.hpp"
PORT_TEST_DEFS(Sync)
PORT_TEST_DEFS(Guarded)
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/EventTests.cpp | // ======================================================================
// \title EventTests.cpp
// \author T. Chieu
// \brief cpp file for event tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Event tests
// ----------------------------------------------------------------------
void Tester ::testEvent(NATIVE_INT_TYPE portNum, FppTest::Types::NoParams& data) {
ASSERT_TRUE(component.isConnected_eventOut_OutputPort(portNum));
ASSERT_TRUE(component.isConnected_textEventOut_OutputPort(portNum));
component.log_ACTIVITY_HI_EventNoArgs();
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_EventNoArgs_SIZE(1);
this->printTextLogHistory(stdout);
}
void Tester ::testEventHelper(NATIVE_INT_TYPE portNum, FppTest::Types::PrimitiveParams& data, NATIVE_UINT_TYPE size) {
component.log_ACTIVITY_LO_EventPrimitive(data.args.val1, data.args.val2, data.args.val3, data.args.val4,
data.args.val5, data.args.val6);
ASSERT_EVENTS_SIZE(size);
ASSERT_EVENTS_EventPrimitive_SIZE(size);
ASSERT_EVENTS_EventPrimitive(portNum, data.args.val1, data.args.val2, data.args.val3, data.args.val4,
data.args.val5, data.args.val6);
}
void Tester ::testEvent(NATIVE_INT_TYPE portNum, FppTest::Types::PrimitiveParams& data) {
ASSERT_TRUE(component.isConnected_eventOut_OutputPort(portNum));
ASSERT_TRUE(component.isConnected_textEventOut_OutputPort(portNum));
for (U32 i = 0; i < component.EVENTID_EVENTPRIMITIVE_THROTTLE; i++) {
testEventHelper(portNum, data, i + 1);
}
// Test that throttling works
testEventHelper(portNum, data, component.EVENTID_EVENTPRIMITIVE_THROTTLE);
// Test throttle reset
component.log_ACTIVITY_LO_EventPrimitive_ThrottleClear();
testEventHelper(portNum, data, component.EVENTID_EVENTPRIMITIVE_THROTTLE + 1);
this->printTextLogHistory(stdout);
}
void Tester ::testEvent(NATIVE_INT_TYPE portNum, FppTest::Types::LogStringParams& data) {
component.log_COMMAND_EventString(data.args.val1, data.args.val2);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_EventString_SIZE(1);
ASSERT_EVENTS_EventString(portNum, data.args.val1.toChar(), data.args.val2.toChar());
this->printTextLogHistory(stdout);
}
void Tester ::testEvent(NATIVE_INT_TYPE portNum, FppTest::Types::EnumParam& data) {
ASSERT_TRUE(component.isConnected_eventOut_OutputPort(portNum));
ASSERT_TRUE(component.isConnected_textEventOut_OutputPort(portNum));
component.log_DIAGNOSTIC_EventEnum(data.args.val);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_EventEnum_SIZE(1);
ASSERT_EVENTS_EventEnum(portNum, data.args.val);
this->printTextLogHistory(stdout);
}
void Tester ::testEventHelper(NATIVE_INT_TYPE portNum, FppTest::Types::ArrayParam& data, NATIVE_UINT_TYPE size) {
ASSERT_TRUE(component.isConnected_eventOut_OutputPort(portNum));
ASSERT_TRUE(component.isConnected_textEventOut_OutputPort(portNum));
component.log_FATAL_EventArray(data.args.val);
ASSERT_EVENTS_SIZE(size);
ASSERT_EVENTS_EventArray_SIZE(size);
ASSERT_EVENTS_EventArray(portNum, data.args.val);
}
void Tester ::testEvent(NATIVE_INT_TYPE portNum, FppTest::Types::ArrayParam& data) {
ASSERT_TRUE(component.isConnected_eventOut_OutputPort(portNum));
ASSERT_TRUE(component.isConnected_textEventOut_OutputPort(portNum));
for (U32 i = 0; i < component.EVENTID_EVENTARRAY_THROTTLE; i++) {
testEventHelper(portNum, data, i + 1);
}
// Test that throttling works
testEventHelper(portNum, data, component.EVENTID_EVENTARRAY_THROTTLE);
// Test throttle reset
component.log_FATAL_EventArray_ThrottleClear();
testEventHelper(portNum, data, component.EVENTID_EVENTARRAY_THROTTLE + 1);
this->printTextLogHistory(stdout);
}
void Tester ::testEvent(NATIVE_INT_TYPE portNum, FppTest::Types::StructParam& data) {
ASSERT_TRUE(component.isConnected_eventOut_OutputPort(portNum));
ASSERT_TRUE(component.isConnected_textEventOut_OutputPort(portNum));
component.log_WARNING_HI_EventStruct(data.args.val);
ASSERT_EVENTS_SIZE(1);
ASSERT_EVENTS_EventStruct_SIZE(1);
ASSERT_EVENTS_EventStruct(portNum, data.args.val);
this->printTextLogHistory(stdout);
}
void Tester ::testEventHelper(NATIVE_INT_TYPE portNum, FppTest::Types::BoolParam& data, NATIVE_UINT_TYPE size) {
ASSERT_TRUE(component.isConnected_eventOut_OutputPort(portNum));
ASSERT_TRUE(component.isConnected_textEventOut_OutputPort(portNum));
component.log_WARNING_LO_EventBool(data.args.val);
ASSERT_EVENTS_SIZE(size);
ASSERT_EVENTS_EventBool_SIZE(size);
ASSERT_EVENTS_EventBool(portNum, data.args.val);
}
void Tester ::testEvent(NATIVE_INT_TYPE portNum, FppTest::Types::BoolParam& data) {
ASSERT_TRUE(component.isConnected_eventOut_OutputPort(portNum));
ASSERT_TRUE(component.isConnected_textEventOut_OutputPort(portNum));
for (U32 i = 0; i < component.EVENTID_EVENTBOOL_THROTTLE; i++) {
testEventHelper(portNum, data, i + 1);
}
// Test that throttling works
testEventHelper(portNum, data, component.EVENTID_EVENTBOOL_THROTTLE);
// Test throttle reset
component.log_WARNING_LO_EventBool_ThrottleClear();
testEventHelper(portNum, data, component.EVENTID_EVENTBOOL_THROTTLE + 1);
this->printTextLogHistory(stdout);
}
| cpp |
fprime | data/projects/fprime/FppTest/component/tests/TlmTests.hpp | // ======================================================================
// \title TlmTests.hpp
// \author T. Chieu
// \brief hpp file for telemetry tests
//
// \copyright
// Copyright (C) 2009-2023 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
// ----------------------------------------------------------------------
// Telemetry test declarations
// ----------------------------------------------------------------------
#define TLM_TEST_DECL(TYPE) void testTelemetry(NATIVE_INT_TYPE portNum, FppTest::Types::TYPE##Param& data);
#define TLM_TEST_DECLS \
TLM_TEST_DECL(U32) \
TLM_TEST_DECL(F32) \
TLM_TEST_DECL(TlmString) \
TLM_TEST_DECL(Enum) \
TLM_TEST_DECL(Array) \
TLM_TEST_DECL(Struct)
// ----------------------------------------------------------------------
// Telemetry test definitions
// ----------------------------------------------------------------------
#define TLM_TEST_DEF(TYPE) \
void Tester ::testTelemetry(NATIVE_INT_TYPE portNum, FppTest::Types::TYPE##Param& data) { \
ASSERT_TRUE(component.isConnected_tlmOut_OutputPort(portNum)); \
\
component.tlmWrite_Channel##TYPE(data.args.val); \
\
ASSERT_TLM_SIZE(1); \
ASSERT_TLM_Channel##TYPE##_SIZE(1); \
ASSERT_TLM_Channel##TYPE(0, data.args.val); \
\
Fw::Time time = Fw::ZERO_TIME; \
component.tlmWrite_Channel##TYPE(data.args.val, time); \
\
ASSERT_TLM_SIZE(2); \
ASSERT_TLM_Channel##TYPE##_SIZE(2); \
ASSERT_TLM_Channel##TYPE(0, data.args.val); \
}
#define TLM_TEST_DEFS \
TLM_TEST_DEF(U32) \
TLM_TEST_DEF(F32) \
\
void Tester ::testTelemetry(NATIVE_INT_TYPE portNum, FppTest::Types::TlmStringParam& data) { \
ASSERT_TRUE(component.isConnected_tlmOut_OutputPort(portNum)); \
\
component.tlmWrite_ChannelString(data.args.val); \
\
ASSERT_TLM_SIZE(1); \
ASSERT_TLM_ChannelString_SIZE(1); \
ASSERT_TLM_ChannelString(0, data.args.val.toChar()); \
\
/* Test unchanged value */ \
component.tlmWrite_ChannelString(data.args.val); \
\
ASSERT_TLM_SIZE(1); \
ASSERT_TLM_ChannelString_SIZE(1); \
\
FppTest::Types::TlmStringParam data2; \
while (data2.args.val == data.args.val) { \
data2 = FppTest::Types::TlmStringParam(); \
} \
\
Fw::Time time = Fw::ZERO_TIME; \
component.tlmWrite_ChannelString(data2.args.val, time); \
\
ASSERT_TLM_SIZE(2); \
ASSERT_TLM_ChannelString_SIZE(2); \
ASSERT_TLM_ChannelString(1, data2.args.val.toChar()); \
} \
\
TLM_TEST_DEF(Enum) \
TLM_TEST_DEF(Array) \
TLM_TEST_DEF(Struct)
| hpp |
fprime | data/projects/fprime/FppTest/component/tests/TestMain.cpp | // ----------------------------------------------------------------------
// TestMain.cpp
// ----------------------------------------------------------------------
#include "STest/Random/Random.hpp"
#include "gtest/gtest.h"
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
STest::Random::seed();
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/FppTest/component/passive/PassiveTest.cpp | // ======================================================================
// \title PassiveTest.cpp
// \author tiffany
// \brief cpp file for PassiveTest component implementation class
// ======================================================================
#include "PassiveTest.hpp"
#include <FpConfig.hpp>
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
PassiveTest ::
PassiveTest(
const char *const compName
) : PassiveTestComponentBase(compName)
{
}
void PassiveTest ::
init(
NATIVE_INT_TYPE instance
)
{
PassiveTestComponentBase::init(instance);
}
PassiveTest ::
~PassiveTest()
{
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void PassiveTest ::
arrayArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
this->arrayArgsOut_out(portNum, a, aRef);
}
void PassiveTest ::
arrayArgsSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
this->arrayArgsOut_out(portNum, a, aRef);
}
FormalParamArray PassiveTest ::
arrayReturnGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
return this->arrayReturnOut_out(portNum, a, aRef);
}
FormalParamArray PassiveTest ::
arrayReturnSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
return this->arrayReturnOut_out(portNum, a, aRef);
}
void PassiveTest ::
cmdOut_handler(
NATIVE_INT_TYPE portNum,
FwOpcodeType opCode,
U32 cmdSeq,
Fw::CmdArgBuffer& args
)
{
}
void PassiveTest ::
enumArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
this->enumArgsOut_out(portNum, en, enRef);
}
void PassiveTest ::
enumArgsSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
this->enumArgsOut_out(portNum, en, enRef);
}
FormalParamEnum PassiveTest ::
enumReturnGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
return this->enumReturnOut_out(portNum, en, enRef);
}
FormalParamEnum PassiveTest ::
enumReturnSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
return this->enumReturnOut_out(portNum, en, enRef);
}
void PassiveTest ::
noArgsGuarded_handler(
const NATIVE_INT_TYPE portNum
)
{
this->noArgsOut_out(portNum);
}
bool PassiveTest ::
noArgsReturnGuarded_handler(
const NATIVE_INT_TYPE portNum
)
{
return this->noArgsReturnOut_out(portNum);
}
bool PassiveTest ::
noArgsReturnSync_handler(
const NATIVE_INT_TYPE portNum
)
{
return this->noArgsReturnOut_out(portNum);
}
void PassiveTest ::
noArgsSync_handler(
const NATIVE_INT_TYPE portNum
)
{
this->noArgsOut_out(portNum);
}
void PassiveTest ::
primitiveArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
this->primitiveArgsOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
void PassiveTest ::
primitiveArgsSync_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
this->primitiveArgsOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
U32 PassiveTest ::
primitiveReturnGuarded_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
return this->primitiveReturnOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
U32 PassiveTest ::
primitiveReturnSync_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
return this->primitiveReturnOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
void PassiveTest ::
stringArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
const str80String &str80,
str80RefString &str80Ref,
const str100String &str100,
str100RefString &str100Ref
)
{
this->stringArgsOut_out(
portNum,
str80,
str80Ref,
str100,
str100Ref
);
}
void PassiveTest ::
stringArgsSync_handler(
const NATIVE_INT_TYPE portNum,
const str80String &str80,
str80RefString &str80Ref,
const str100String &str100,
str100RefString &str100Ref
)
{
this->stringArgsOut_out(
portNum,
str80,
str80Ref,
str100,
str100Ref
);
}
void PassiveTest ::
structArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
this->structArgsOut_out(portNum, s, sRef);
}
void PassiveTest ::
structArgsSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
this->structArgsOut_out(portNum, s, sRef);
}
FormalParamStruct PassiveTest ::
structReturnGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
return this->structReturnOut_out(portNum, s, sRef);
}
FormalParamStruct PassiveTest ::
structReturnSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
return this->structReturnOut_out(portNum, s, sRef);
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined serial input ports
// ----------------------------------------------------------------------
void PassiveTest ::
serialGuarded_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(portNum, Buffer);
}
void PassiveTest ::
serialSync_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(portNum, Buffer);
}
// ----------------------------------------------------------------------
// Command handler implementations
// ----------------------------------------------------------------------
void PassiveTest ::
CMD_NO_ARGS_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq
)
{
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void PassiveTest ::
CMD_PRIMITIVE_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
U32 u32_1,
U32 u32_2,
F32 f32_1,
F32 f32_2,
bool b1,
bool b2
)
{
this->primitiveCmd.args.val1 = u32_1;
this->primitiveCmd.args.val2 = u32_2;
this->primitiveCmd.args.val3 = f32_1;
this->primitiveCmd.args.val4 = f32_2;
this->primitiveCmd.args.val5 = b1;
this->primitiveCmd.args.val6 = b2;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void PassiveTest ::
CMD_STRINGS_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
const Fw::CmdStringArg& str1,
const Fw::CmdStringArg& str2
)
{
this->stringCmd.args.val1 = str1;
this->stringCmd.args.val2 = str2;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void PassiveTest ::
CMD_ENUM_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamEnum en
)
{
this->enumCmd.args.val = en;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void PassiveTest ::
CMD_ARRAY_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamArray arr
)
{
this->arrayCmd.args.val = arr;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void PassiveTest ::
CMD_STRUCT_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamStruct str
)
{
this->structCmd.args.val = str;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
| cpp |
fprime | data/projects/fprime/FppTest/component/passive/PassiveTest.hpp | // ======================================================================
// \title PassiveTest.hpp
// \author tiffany
// \brief hpp file for PassiveTest component implementation class
// ======================================================================
#ifndef PassiveTest_HPP
#define PassiveTest_HPP
#include "FppTest/component/passive/PassiveTestComponentAc.hpp"
#include "FppTest/component/types/FormalParamTypes.hpp"
class PassiveTest :
public PassiveTestComponentBase
{
public:
// ----------------------------------------------------------------------
// Component construction and destruction
// ----------------------------------------------------------------------
//! Construct PassiveTest object
PassiveTest(
const char* const compName //!< The component name
);
//! Initialize PassiveTest object
void init(
NATIVE_INT_TYPE instance = 0 //!< The instance number
);
//! Destroy PassiveTest object
~PassiveTest();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for arrayArgsGuarded
void arrayArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for arrayArgsSync
void arrayArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for arrayReturnGuarded
FormalParamArray arrayReturnGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for arrayReturnSync
FormalParamArray arrayReturnSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for cmdOut
void cmdOut_handler(
NATIVE_INT_TYPE portNum, //!< The port number
FwOpcodeType opCode, //!< Command Op Code
U32 cmdSeq, //!< Command Sequence
Fw::CmdArgBuffer& args //!< Buffer containing arguments
);
//! Handler implementation for enumArgsGuarded
void enumArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for enumArgsSync
void enumArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for enumReturnGuarded
FormalParamEnum enumReturnGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for enumReturnSync
FormalParamEnum enumReturnSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for noArgsGuarded
void noArgsGuarded_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for noArgsReturnGuarded
bool noArgsReturnGuarded_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for noArgsReturnSync
bool noArgsReturnSync_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for noArgsSync
void noArgsSync_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for primitiveArgsGuarded
void primitiveArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for primitiveArgsSync
void primitiveArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for primitiveReturnGuarded
U32 primitiveReturnGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for primitiveReturnSync
U32 primitiveReturnSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for stringArgsGuarded
void stringArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const StringArgsPortStrings::StringSize80& str80, //!< A string of size 80
StringArgsPortStrings::StringSize80& str80Ref,
const StringArgsPortStrings::StringSize100& str100, //!< A string of size 100
StringArgsPortStrings::StringSize100& str100Ref
);
//! Handler implementation for stringArgsSync
void stringArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const StringArgsPortStrings::StringSize80& str80, //!< A string of size 80
StringArgsPortStrings::StringSize80& str80Ref,
const StringArgsPortStrings::StringSize100& str100, //!< A string of size 100
StringArgsPortStrings::StringSize100& str100Ref
);
//! Handler implementation for structArgsGuarded
void structArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
//! Handler implementation for structArgsSync
void structArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
//! Handler implementation for structReturnGuarded
FormalParamStruct structReturnGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
//! Handler implementation for structReturnSync
FormalParamStruct structReturnSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined serial input ports
// ----------------------------------------------------------------------
//! Handler implementation for serialGuarded
void serialGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
//! Handler implementation for serialSync
void serialSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for commands
// ----------------------------------------------------------------------
//! Handler implementation for command CMD_NO_ARGS
void CMD_NO_ARGS_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq //!< The command sequence number
);
//! Handler implementation for command CMD_PRIMITIVE
void CMD_PRIMITIVE_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
U32 u32_1, //!< A U32
U32 u32_2, //!< A U32
F32 f32_1, //!< An F32
F32 f32_2, //!< An F32
bool b1, //!< A boolean
bool b2 //!< A boolean
);
//! Handler implementation for command CMD_STRINGS
void CMD_STRINGS_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
const Fw::CmdStringArg& str1, //!< A string
const Fw::CmdStringArg& str2 //!< Another string
);
//! Handler implementation for command CMD_ENUM
void CMD_ENUM_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamEnum en //!< An enum
);
//! Handler implementation for command CMD_ARRAY
void CMD_ARRAY_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamArray arr //!< An array
);
//! Handler implementation for command CMD_STRUCT
void CMD_STRUCT_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamStruct str //!< A struct
);
public:
//! Enables checking the serialization status of serial port invocations
Fw::SerializeStatus serializeStatus;
// Command test values
FppTest::Types::PrimitiveParams primitiveCmd;
FppTest::Types::CmdStringParams stringCmd;
FppTest::Types::EnumParam enumCmd;
FppTest::Types::ArrayParam arrayCmd;
FppTest::Types::StructParam structCmd;
};
#endif
| hpp |
fprime | data/projects/fprime/FppTest/component/passive/test/ut/Tester.cpp | // ======================================================================
// \title PassiveTest/test/ut/Tester.cpp
// \author tiffany
// \brief cpp file for PassiveTest test harness implementation class
// ======================================================================
#include "STest/Pick/Pick.hpp"
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
Tester ::Tester()
: PassiveTestGTestBase("Tester", Tester::MAX_HISTORY_SIZE),
component("PassiveTest"),
primitiveBuf(primitiveData, sizeof(primitiveData)),
stringBuf(stringData, sizeof(stringData)),
enumBuf(enumData, sizeof(enumData)),
arrayBuf(arrayData, sizeof(arrayData)),
structBuf(structData, sizeof(structData)),
serialBuf(serialData, sizeof(serialData)),
time(STest::Pick::any(), STest::Pick::any()) {
this->initComponents();
this->connectPorts();
}
Tester ::~Tester() {}
void Tester ::initComponents() {
this->init();
this->component.init(Tester::TEST_INSTANCE_ID);
}
Fw::ParamValid Tester ::from_prmGetIn_handler(const NATIVE_INT_TYPE portNum, FwPrmIdType id, Fw::ParamBuffer& val) {
val.resetSer();
Fw::SerializeStatus status;
U32 id_base = component.getIdBase();
FW_ASSERT(id >= id_base);
switch (id - id_base) {
case PassiveTestComponentBase::PARAMID_PARAMBOOL:
status = val.serialize(boolPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case PassiveTestComponentBase::PARAMID_PARAMU32:
status = val.serialize(u32Prm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case PassiveTestComponentBase::PARAMID_PARAMSTRING:
status = val.serialize(stringPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case PassiveTestComponentBase::PARAMID_PARAMENUM:
status = val.serialize(enumPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case PassiveTestComponentBase::PARAMID_PARAMARRAY:
status = val.serialize(arrayPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case PassiveTestComponentBase::PARAMID_PARAMSTRUCT:
status = val.serialize(structPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
}
this->pushFromPortEntry_prmGetIn(id, val);
return prmValid;
}
void Tester ::from_prmSetIn_handler(const NATIVE_INT_TYPE portNum, FwPrmIdType id, Fw::ParamBuffer& val) {
Fw::SerializeStatus status;
U32 id_base = component.getIdBase();
FW_ASSERT(id >= id_base);
switch (id - id_base) {
case PassiveTestComponentBase::PARAMID_PARAMBOOL:
status = val.deserialize(boolPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case PassiveTestComponentBase::PARAMID_PARAMU32:
status = val.deserialize(u32Prm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case PassiveTestComponentBase::PARAMID_PARAMSTRING:
status = val.deserialize(stringPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case PassiveTestComponentBase::PARAMID_PARAMENUM:
status = val.deserialize(enumPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case PassiveTestComponentBase::PARAMID_PARAMARRAY:
status = val.deserialize(arrayPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case PassiveTestComponentBase::PARAMID_PARAMSTRUCT:
status = val.deserialize(structPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
}
this->pushFromPortEntry_prmSetIn(id, val);
}
| cpp |
fprime | data/projects/fprime/FppTest/component/passive/test/ut/Tester.hpp | // ======================================================================
// \title PassiveTest/test/ut/Tester.hpp
// \author tiffany
// \brief hpp file for PassiveTest test harness implementation class
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include "FppTest/component/active/SerialPortIndexEnumAc.hpp"
#include "FppTest/component/active/TypedPortIndexEnumAc.hpp"
#include "FppTest/component/passive/PassiveTest.hpp"
#include "FppTest/component/tests/CmdTests.hpp"
#include "FppTest/component/tests/EventTests.hpp"
#include "FppTest/component/tests/ParamTests.hpp"
#include "FppTest/component/tests/PortTests.hpp"
#include "FppTest/component/tests/TlmTests.hpp"
#include "FppTest/component/types/FormalParamTypes.hpp"
#include "PassiveTestGTestBase.hpp"
class Tester : public PassiveTestGTestBase {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
// Maximum size of histories storing events, telemetry, and port outputs
static const NATIVE_INT_TYPE MAX_HISTORY_SIZE = 100;
// Instance ID supplied to the component instance under test
static const NATIVE_INT_TYPE TEST_INSTANCE_ID = 0;
// Queue depth supplied to component instance under test
static const NATIVE_INT_TYPE TEST_INSTANCE_QUEUE_DEPTH = 10;
//! Construct object Tester
//!
Tester();
//! Destroy object Tester
//!
~Tester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
PORT_TEST_DECLS
CMD_TEST_DECLS
EVENT_TEST_DECLS
TLM_TEST_DECLS
void testParam();
PARAM_CMD_TEST_DECLS
void testTime();
PRIVATE:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_arrayArgsOut
//!
void from_arrayArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamArray& a, /*!<
An array
*/
FormalParamArray& aRef /*!<
An array ref
*/
);
//! Handler for from_arrayReturnOut
//!
FormalParamArray from_arrayReturnOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamArray& a, /*!<
An array
*/
FormalParamArray& aRef /*!<
An array ref
*/
);
//! Handler for from_enumArgsOut
//!
void from_enumArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamEnum& en, /*!<
An enum
*/
FormalParamEnum& enRef /*!<
An enum ref
*/
);
//! Handler for from_enumReturnOut
//!
FormalParamEnum from_enumReturnOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamEnum& en, /*!<
An enum
*/
FormalParamEnum& enRef /*!<
An enum ref
*/
);
//! Handler for from_noArgsOut
//!
void from_noArgsOut_handler(const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Handler for from_noArgsReturnOut
//!
bool from_noArgsReturnOut_handler(const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Handler for from_primitiveArgsOut
//!
void from_primitiveArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef);
//! Handler for from_primitiveReturnOut
//!
U32 from_primitiveReturnOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef);
//! Handler for from_prmGetIn
//!
Fw::ParamValid from_prmGetIn_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
FwPrmIdType id, /*!<
Parameter ID
*/
Fw::ParamBuffer& val /*!<
Buffer containing serialized parameter value
*/
);
//! Handler for from_prmGetIn
//!
void from_prmSetIn_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
FwPrmIdType id, /*!<
Parameter ID
*/
Fw::ParamBuffer& val /*!<
Buffer containing serialized parameter value
*/
);
//! Handler for from_stringArgsOut
//!
void from_stringArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const str80String& str80, /*!<
A string of size 80
*/
str80RefString& str80Ref,
const str100String& str100, /*!<
A string of size 100
*/
str100RefString& str100Ref);
//! Handler for from_structArgsOut
//!
void from_structArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamStruct& s, /*!<
A struct
*/
FormalParamStruct& sRef /*!<
A struct ref
*/
);
//! Handler for from_structReturnOut
//!
FormalParamStruct from_structReturnOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamStruct& s, /*!<
A struct
*/
FormalParamStruct& sRef /*!<
A struct ref
*/
);
PRIVATE:
// ----------------------------------------------------------------------
// Handlers for serial from ports
// ----------------------------------------------------------------------
//! Handler for from_serialOut
//!
void from_serialOut_handler(NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase& Buffer /*!< The serialization buffer*/
);
public:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Connect prmSetIn port
void connectPrmSetIn();
//! Connect timeGetOut port
void connectTimeGetOut();
//! Connect serial ports to special ports
void connectSpecialPortsSerial();
//! Set prmValid
void setPrmValid(Fw::ParamValid valid);
//! Initialize components
//!
void initComponents();
//! Check successful status of a serial port invocation
void checkSerializeStatusSuccess();
//! Check unsuccessful status of a serial port invocation
void checkSerializeStatusBufferEmpty();
PRIVATE:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
PassiveTest component;
// Values returned by typed output ports
FppTest::Types::BoolType noParamReturnVal;
FppTest::Types::U32Type primitiveReturnVal;
FppTest::Types::EnumType enumReturnVal;
FppTest::Types::ArrayType arrayReturnVal;
FppTest::Types::StructType structReturnVal;
// Buffers from serial output ports;
U8 primitiveData[InputPrimitiveArgsPort::SERIALIZED_SIZE];
U8 stringData[InputStringArgsPort::SERIALIZED_SIZE];
U8 enumData[InputEnumArgsPort::SERIALIZED_SIZE];
U8 arrayData[InputArrayArgsPort::SERIALIZED_SIZE];
U8 structData[InputStructArgsPort::SERIALIZED_SIZE];
U8 serialData[SERIAL_ARGS_BUFFER_CAPACITY];
Fw::SerialBuffer primitiveBuf;
Fw::SerialBuffer stringBuf;
Fw::SerialBuffer enumBuf;
Fw::SerialBuffer arrayBuf;
Fw::SerialBuffer structBuf;
Fw::SerialBuffer serialBuf;
// Parameter test values
FppTest::Types::BoolParam boolPrm;
FppTest::Types::U32Param u32Prm;
FppTest::Types::PrmStringParam stringPrm;
FppTest::Types::EnumParam enumPrm;
FppTest::Types::ArrayParam arrayPrm;
FppTest::Types::StructParam structPrm;
Fw::ParamValid prmValid;
// Time test values
Fw::Time time;
};
#endif
| hpp |
fprime | data/projects/fprime/FppTest/component/active/ActiveTest.cpp | // ======================================================================
// \title ActiveTest.cpp
// \author tiffany
// \brief cpp file for ActiveTest component implementation class
// ======================================================================
#include "ActiveTest.hpp"
#include <FpConfig.hpp>
#include "FppTest/component/active/SerialPortIndexEnumAc.hpp"
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
ActiveTest ::
ActiveTest(
const char *const compName
) : ActiveTestComponentBase(compName)
{
}
void ActiveTest ::
init(
NATIVE_INT_TYPE queueDepth,
NATIVE_INT_TYPE msgSize,
NATIVE_INT_TYPE instance
)
{
ActiveTestComponentBase::init(queueDepth, msgSize, instance);
}
ActiveTest ::
~ActiveTest()
{
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void ActiveTest ::
arrayArgsAsync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
this->arrayArgsOut_out(portNum, a, aRef);
}
void ActiveTest ::
enumArgsAsync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
this->enumArgsOut_out(portNum, en, enRef);
}
void ActiveTest ::
noArgsAsync_handler(
const NATIVE_INT_TYPE portNum
)
{
this->noArgsOut_out(portNum);
}
void ActiveTest ::
primitiveArgsAsync_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
this->primitiveArgsOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
void ActiveTest ::
structArgsAsync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
this->structArgsOut_out(portNum, s, sRef);
}
void ActiveTest ::
stringArgsAsync_handler(
const NATIVE_INT_TYPE portNum,
const str80String &str80,
str80RefString &str80Ref,
const str100String &str100,
str100RefString &str100Ref
)
{
this->stringArgsOut_out(
portNum,
str80,
str80Ref,
str100,
str100Ref
);
}
void ActiveTest ::
arrayArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
this->arrayArgsOut_out(portNum, a, aRef);
}
void ActiveTest ::
arrayArgsSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
this->arrayArgsOut_out(portNum, a, aRef);
}
FormalParamArray ActiveTest ::
arrayReturnGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
return this->arrayReturnOut_out(portNum, a, aRef);
}
FormalParamArray ActiveTest ::
arrayReturnSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
return this->arrayReturnOut_out(portNum, a, aRef);
}
void ActiveTest ::
cmdOut_handler(
NATIVE_INT_TYPE portNum,
FwOpcodeType opCode,
U32 cmdSeq,
Fw::CmdArgBuffer& args
)
{
}
void ActiveTest ::
enumArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
this->enumArgsOut_out(portNum, en, enRef);
}
void ActiveTest ::
enumArgsSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
this->enumArgsOut_out(portNum, en, enRef);
}
FormalParamEnum ActiveTest ::
enumReturnGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
return this->enumReturnOut_out(portNum, en, enRef);
}
FormalParamEnum ActiveTest ::
enumReturnSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
return this->enumReturnOut_out(portNum, en, enRef);
}
void ActiveTest ::
noArgsGuarded_handler(
const NATIVE_INT_TYPE portNum
)
{
this->noArgsOut_out(portNum);
}
bool ActiveTest ::
noArgsReturnGuarded_handler(
const NATIVE_INT_TYPE portNum
)
{
return this->noArgsReturnOut_out(portNum);
}
bool ActiveTest ::
noArgsReturnSync_handler(
const NATIVE_INT_TYPE portNum
)
{
return this->noArgsReturnOut_out(portNum);
}
void ActiveTest ::
noArgsSync_handler(
const NATIVE_INT_TYPE portNum
)
{
this->noArgsOut_out(portNum);
}
void ActiveTest ::
primitiveArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
this->primitiveArgsOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
void ActiveTest ::
primitiveArgsSync_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
this->primitiveArgsOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
U32 ActiveTest ::
primitiveReturnGuarded_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
return this->primitiveReturnOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
U32 ActiveTest ::
primitiveReturnSync_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
return this->primitiveReturnOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
void ActiveTest ::
stringArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
const str80String &str80,
str80RefString &str80Ref,
const str100String &str100,
str100RefString &str100Ref
)
{
this->stringArgsOut_out(
portNum,
str80,
str80Ref,
str100,
str100Ref
);
}
void ActiveTest ::
stringArgsSync_handler(
const NATIVE_INT_TYPE portNum,
const str80String &str80,
str80RefString &str80Ref,
const str100String &str100,
str100RefString &str100Ref
)
{
this->stringArgsOut_out(
portNum,
str80,
str80Ref,
str100,
str100Ref
);
}
void ActiveTest ::
structArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
this->structArgsOut_out(portNum, s, sRef);
}
void ActiveTest ::
structArgsSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
this->structArgsOut_out(portNum, s, sRef);
}
FormalParamStruct ActiveTest ::
structReturnGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
return this->structReturnOut_out(portNum, s, sRef);
}
FormalParamStruct ActiveTest ::
structReturnSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
return this->structReturnOut_out(portNum, s, sRef);
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined serial input ports
// ----------------------------------------------------------------------
void ActiveTest ::
serialAsync_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(portNum, Buffer);
}
void ActiveTest ::
serialAsyncAssert_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(SerialPortIndex::ENUM, Buffer);
}
void ActiveTest ::
serialAsyncBlockPriority_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(SerialPortIndex::ARRAY, Buffer);
}
void ActiveTest ::
serialAsyncDropPriority_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(SerialPortIndex::STRUCT, Buffer);
}
void ActiveTest ::
serialGuarded_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(portNum, Buffer);
}
void ActiveTest ::
serialSync_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(portNum, Buffer);
}
// ----------------------------------------------------------------------
// Command handler implementations
// ----------------------------------------------------------------------
void ActiveTest ::
CMD_ASYNC_NO_ARGS_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq
)
{
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void ActiveTest ::
CMD_ASYNC_PRIMITIVE_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
U32 u32_1,
U32 u32_2,
F32 f32_1,
F32 f32_2,
bool b1,
bool b2
)
{
this->primitiveCmd.args.val1 = u32_1;
this->primitiveCmd.args.val2 = u32_2;
this->primitiveCmd.args.val3 = f32_1;
this->primitiveCmd.args.val4 = f32_2;
this->primitiveCmd.args.val5 = b1;
this->primitiveCmd.args.val6 = b2;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void ActiveTest ::
CMD_ASYNC_STRINGS_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
const Fw::CmdStringArg& str1,
const Fw::CmdStringArg& str2
)
{
this->stringCmd.args.val1 = str1;
this->stringCmd.args.val2 = str2;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void ActiveTest ::
CMD_ASYNC_ENUM_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamEnum en
)
{
this->enumCmd.args.val = en;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void ActiveTest ::
CMD_ASYNC_ARRAY_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamArray arr
)
{
this->arrayCmd.args.val = arr;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void ActiveTest ::
CMD_ASYNC_STRUCT_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamStruct str
)
{
this->structCmd.args.val = str;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void ActiveTest ::
CMD_NO_ARGS_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq
)
{
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void ActiveTest ::
CMD_PRIMITIVE_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
U32 u32_1,
U32 u32_2,
F32 f32_1,
F32 f32_2,
bool b1,
bool b2
)
{
this->primitiveCmd.args.val1 = u32_1;
this->primitiveCmd.args.val2 = u32_2;
this->primitiveCmd.args.val3 = f32_1;
this->primitiveCmd.args.val4 = f32_2;
this->primitiveCmd.args.val5 = b1;
this->primitiveCmd.args.val6 = b2;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void ActiveTest ::
CMD_STRINGS_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
const Fw::CmdStringArg& str1,
const Fw::CmdStringArg& str2
)
{
this->stringCmd.args.val1 = str1;
this->stringCmd.args.val2 = str2;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void ActiveTest ::
CMD_ENUM_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamEnum en
)
{
this->enumCmd.args.val = en;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void ActiveTest ::
CMD_ARRAY_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamArray arr
)
{
this->arrayCmd.args.val = arr;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void ActiveTest ::
CMD_STRUCT_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamStruct str
)
{
this->structCmd.args.val = str;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
// ----------------------------------------------------------------------
// Internal interface handlers
// ----------------------------------------------------------------------
//! Internal interface handler for internalArray
void ActiveTest ::
internalArray_internalInterfaceHandler(
const FormalParamArray& arr //!< An array
)
{
this->arrayInterface.args.val = arr;
}
//! Internal interface handler for internalEnum
void ActiveTest ::
internalEnum_internalInterfaceHandler(
const FormalParamEnum& en //!< An enum
)
{
this->enumInterface.args.val = en;
}
//! Internal interface handler for internalNoArgs
void ActiveTest ::
internalNoArgs_internalInterfaceHandler()
{
}
//! Internal interface handler for internalPrimitive
void ActiveTest ::
internalPrimitive_internalInterfaceHandler(
U32 u32_1, //!< A U32
U32 u32_2, //!< A U32
F32 f32_1, //!< An F32
F32 f32_2, //!< An F32
bool b1, //!< A boolean
bool b2 //!< A boolean
)
{
this->primitiveInterface.args.val1 = u32_1;
this->primitiveInterface.args.val2 = u32_2;
this->primitiveInterface.args.val3 = f32_1;
this->primitiveInterface.args.val4 = f32_2;
this->primitiveInterface.args.val5 = b1;
this->primitiveInterface.args.val6 = b2;
}
//! Internal interface handler for internalString
void ActiveTest ::
internalString_internalInterfaceHandler(
const Fw::InternalInterfaceString& str1, //!< A string
const Fw::InternalInterfaceString& str2 //!< Another string
)
{
this->stringInterface.args.val1 = str1;
this->stringInterface.args.val2 = str2;
}
//! Internal interface handler for internalStruct
void ActiveTest ::
internalStruct_internalInterfaceHandler(
const FormalParamStruct& str //!< A struct
)
{
this->structInterface.args.val = str;
}
| cpp |
fprime | data/projects/fprime/FppTest/component/active/ActiveTest.hpp | // ======================================================================
// \title ActiveTest.hpp
// \author tiffany
// \brief hpp file for ActiveTest component implementation class
// ======================================================================
#ifndef ActiveTest_HPP
#define ActiveTest_HPP
#include "FppTest/component/active/ActiveTestComponentAc.hpp"
#include "FppTest/component/types/FormalParamTypes.hpp"
class ActiveTest :
public ActiveTestComponentBase
{
public:
// ----------------------------------------------------------------------
// Component construction and destruction
// ----------------------------------------------------------------------
//! Construct ActiveTest object
ActiveTest(
const char* const compName //!< The component name
);
//! Initialize ActiveTest object
void init(
NATIVE_INT_TYPE queueDepth, //!< The queue depth
NATIVE_INT_TYPE msgSize, //!< The message size
NATIVE_INT_TYPE instance = 0 //!< The instance number
);
//! Destroy ActiveTest object
~ActiveTest();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for arrayArgsAsync
void arrayArgsAsync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for arrayArgsGuarded
void arrayArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for arrayArgsSync
void arrayArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for arrayReturnGuarded
FormalParamArray arrayReturnGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for arrayReturnSync
FormalParamArray arrayReturnSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for cmdOut
void cmdOut_handler(
NATIVE_INT_TYPE portNum, //!< The port number
FwOpcodeType opCode, //!< Command Op Code
U32 cmdSeq, //!< Command Sequence
Fw::CmdArgBuffer& args //!< Buffer containing arguments
);
//! Handler implementation for enumArgsAsync
void enumArgsAsync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for enumArgsGuarded
void enumArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for enumArgsSync
void enumArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for enumReturnGuarded
FormalParamEnum enumReturnGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for enumReturnSync
FormalParamEnum enumReturnSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for noArgsAsync
void noArgsAsync_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for noArgsGuarded
void noArgsGuarded_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for noArgsReturnGuarded
bool noArgsReturnGuarded_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for noArgsReturnSync
bool noArgsReturnSync_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for noArgsSync
void noArgsSync_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for primitiveArgsAsync
void primitiveArgsAsync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for primitiveArgsGuarded
void primitiveArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for primitiveArgsSync
void primitiveArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for primitiveReturnGuarded
U32 primitiveReturnGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for primitiveReturnSync
U32 primitiveReturnSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for stringArgsAsync
void stringArgsAsync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const StringArgsPortStrings::StringSize80& str80, //!< A string of size 80
StringArgsPortStrings::StringSize80& str80Ref,
const StringArgsPortStrings::StringSize100& str100, //!< A string of size 100
StringArgsPortStrings::StringSize100& str100Ref
);
//! Handler implementation for stringArgsGuarded
void stringArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const StringArgsPortStrings::StringSize80& str80, //!< A string of size 80
StringArgsPortStrings::StringSize80& str80Ref,
const StringArgsPortStrings::StringSize100& str100, //!< A string of size 100
StringArgsPortStrings::StringSize100& str100Ref
);
//! Handler implementation for stringArgsSync
void stringArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const StringArgsPortStrings::StringSize80& str80, //!< A string of size 80
StringArgsPortStrings::StringSize80& str80Ref,
const StringArgsPortStrings::StringSize100& str100, //!< A string of size 100
StringArgsPortStrings::StringSize100& str100Ref
);
//! Handler implementation for structArgsAsync
void structArgsAsync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
//! Handler implementation for structArgsGuarded
void structArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
//! Handler implementation for structArgsSync
void structArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
//! Handler implementation for structReturnGuarded
FormalParamStruct structReturnGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
//! Handler implementation for structReturnSync
FormalParamStruct structReturnSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined serial input ports
// ----------------------------------------------------------------------
//! Handler implementation for serialAsync
void serialAsync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
//! Handler implementation for serialAsyncAssert
void serialAsyncAssert_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
//! Handler implementation for serialAsyncBlockPriority
void serialAsyncBlockPriority_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
//! Handler implementation for serialAsyncDropPriority
void serialAsyncDropPriority_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
//! Handler implementation for serialGuarded
void serialGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
//! Handler implementation for serialSync
void serialSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for commands
// ----------------------------------------------------------------------
//! Handler implementation for command CMD_NO_ARGS
void CMD_NO_ARGS_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq //!< The command sequence number
);
//! Handler implementation for command CMD_PRIMITIVE
void CMD_PRIMITIVE_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
U32 u32_1, //!< A U32
U32 u32_2, //!< A U32
F32 f32_1, //!< An F32
F32 f32_2, //!< An F32
bool b1, //!< A boolean
bool b2 //!< A boolean
);
//! Handler implementation for command CMD_STRINGS
void CMD_STRINGS_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
const Fw::CmdStringArg& str1, //!< A string
const Fw::CmdStringArg& str2 //!< Another string
);
//! Handler implementation for command CMD_ENUM
void CMD_ENUM_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamEnum en //!< An enum
);
//! Handler implementation for command CMD_ARRAY
void CMD_ARRAY_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamArray arr //!< An array
);
//! Handler implementation for command CMD_STRUCT
void CMD_STRUCT_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamStruct str //!< A struct
);
//! Handler implementation for command CMD_ASYNC_NO_ARGS
void CMD_ASYNC_NO_ARGS_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq //!< The command sequence number
);
//! Handler implementation for command CMD_ASYNC_PRIMITIVE
void CMD_ASYNC_PRIMITIVE_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
U32 u32_1, //!< A U32
U32 u32_2, //!< A U32
F32 f32_1, //!< An F32
F32 f32_2, //!< An F32
bool b1, //!< A boolean
bool b2 //!< A boolean
);
//! Handler implementation for command CMD_ASYNC_STRINGS
void CMD_ASYNC_STRINGS_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
const Fw::CmdStringArg& str1, //!< A string
const Fw::CmdStringArg& str2 //!< Another string
);
//! Handler implementation for command CMD_ASYNC_ENUM
void CMD_ASYNC_ENUM_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamEnum en //!< An enum
);
//! Handler implementation for command CMD_ASYNC_ARRAY
void CMD_ASYNC_ARRAY_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamArray arr //!< An array
);
//! Handler implementation for command CMD_ASYNC_STRUCT
void CMD_ASYNC_STRUCT_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamStruct str //!< A struct
);
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined internal interfaces
// ----------------------------------------------------------------------
//! Handler implementation for internalArray
void internalArray_internalInterfaceHandler(
const FormalParamArray& arr //!< An array
);
//! Handler implementation for internalEnum
void internalEnum_internalInterfaceHandler(
const FormalParamEnum& en //!< An enum
);
//! Handler implementation for internalNoArgs
void internalNoArgs_internalInterfaceHandler();
//! Handler implementation for internalPrimitive
void internalPrimitive_internalInterfaceHandler(
U32 u32_1, //!< A U32
U32 u32_2, //!< A U32
F32 f32_1, //!< An F32
F32 f32_2, //!< An F32
bool b1, //!< A boolean
bool b2 //!< A boolean
);
//! Handler implementation for internalString
void internalString_internalInterfaceHandler(
const Fw::InternalInterfaceString& str1, //!< A string
const Fw::InternalInterfaceString& str2 //!< Another string
);
//! Handler implementation for internalStruct
void internalStruct_internalInterfaceHandler(
const FormalParamStruct& str //!< A struct
);
public:
//! Enables checking the serialization status of serial port invocations
Fw::SerializeStatus serializeStatus;
// Command test values
FppTest::Types::PrimitiveParams primitiveCmd;
FppTest::Types::CmdStringParams stringCmd;
FppTest::Types::EnumParam enumCmd;
FppTest::Types::ArrayParam arrayCmd;
FppTest::Types::StructParam structCmd;
// Internal interface test values
FppTest::Types::PrimitiveParams primitiveInterface;
FppTest::Types::InternalInterfaceStringParams stringInterface;
FppTest::Types::EnumParam enumInterface;
FppTest::Types::ArrayParam arrayInterface;
FppTest::Types::StructParam structInterface;
};
#endif
| hpp |
fprime | data/projects/fprime/FppTest/component/active/test/ut/Tester.cpp | // ======================================================================
// \title ActiveTest/test/ut/Tester.cpp
// \author tiffany
// \brief cpp file for ActiveTest test harness implementation class
// ======================================================================
#include "STest/Pick/Pick.hpp"
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
Tester ::Tester()
: ActiveTestGTestBase("Tester", Tester::MAX_HISTORY_SIZE),
component("ActiveTest"),
primitiveBuf(primitiveData, sizeof(primitiveData)),
stringBuf(stringData, sizeof(stringData)),
enumBuf(enumData, sizeof(enumData)),
arrayBuf(arrayData, sizeof(arrayData)),
structBuf(structData, sizeof(structData)),
serialBuf(serialData, sizeof(serialData)),
time(STest::Pick::any(), STest::Pick::any()) {
this->initComponents();
this->connectPorts();
this->connectAsyncPorts();
}
Tester ::~Tester() {}
void Tester ::initComponents() {
this->init();
this->component.init(Tester::TEST_INSTANCE_QUEUE_DEPTH, Tester::TEST_INSTANCE_ID);
}
Fw::ParamValid Tester ::from_prmGetIn_handler(const NATIVE_INT_TYPE portNum, FwPrmIdType id, Fw::ParamBuffer& val) {
val.resetSer();
Fw::SerializeStatus status;
U32 id_base = component.getIdBase();
FW_ASSERT(id >= id_base);
switch (id - id_base) {
case ActiveTestComponentBase::PARAMID_PARAMBOOL:
status = val.serialize(boolPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case ActiveTestComponentBase::PARAMID_PARAMU32:
status = val.serialize(u32Prm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case ActiveTestComponentBase::PARAMID_PARAMSTRING:
status = val.serialize(stringPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case ActiveTestComponentBase::PARAMID_PARAMENUM:
status = val.serialize(enumPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case ActiveTestComponentBase::PARAMID_PARAMARRAY:
status = val.serialize(arrayPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case ActiveTestComponentBase::PARAMID_PARAMSTRUCT:
status = val.serialize(structPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
}
this->pushFromPortEntry_prmGetIn(id, val);
return prmValid;
}
void Tester ::from_prmSetIn_handler(const NATIVE_INT_TYPE portNum, FwPrmIdType id, Fw::ParamBuffer& val) {
Fw::SerializeStatus status;
U32 id_base = component.getIdBase();
FW_ASSERT(id >= id_base);
switch (id - id_base) {
case ActiveTestComponentBase::PARAMID_PARAMBOOL:
status = val.deserialize(boolPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case ActiveTestComponentBase::PARAMID_PARAMU32:
status = val.deserialize(u32Prm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case ActiveTestComponentBase::PARAMID_PARAMSTRING:
status = val.deserialize(stringPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case ActiveTestComponentBase::PARAMID_PARAMENUM:
status = val.deserialize(enumPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case ActiveTestComponentBase::PARAMID_PARAMARRAY:
status = val.deserialize(arrayPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case ActiveTestComponentBase::PARAMID_PARAMSTRUCT:
status = val.deserialize(structPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
}
this->pushFromPortEntry_prmSetIn(id, val);
}
| cpp |
fprime | data/projects/fprime/FppTest/component/active/test/ut/Tester.hpp | // ======================================================================
// \title ActiveTest/test/ut/Tester.hpp
// \author tiffany
// \brief hpp file for ActiveTest test harness implementation class
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include "ActiveTestGTestBase.hpp"
#include "FppTest/component/active/ActiveTest.hpp"
#include "FppTest/component/active/SerialPortIndexEnumAc.hpp"
#include "FppTest/component/active/TypedPortIndexEnumAc.hpp"
#include "FppTest/component/tests/CmdTests.hpp"
#include "FppTest/component/tests/EventTests.hpp"
#include "FppTest/component/tests/InternalInterfaceTests.hpp"
#include "FppTest/component/tests/ParamTests.hpp"
#include "FppTest/component/tests/PortTests.hpp"
#include "FppTest/component/tests/TlmTests.hpp"
#include "FppTest/component/types/FormalParamTypes.hpp"
class Tester : public ActiveTestGTestBase {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
// Maximum size of histories storing events, telemetry, and port outputs
static const NATIVE_INT_TYPE MAX_HISTORY_SIZE = 100;
// Instance ID supplied to the component instance under test
static const NATIVE_INT_TYPE TEST_INSTANCE_ID = 0;
// Queue depth supplied to component instance under test
static const NATIVE_INT_TYPE TEST_INSTANCE_QUEUE_DEPTH = 10;
//! Construct object Tester
//!
Tester();
//! Destroy object Tester
//!
~Tester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
PORT_TEST_DECLS
PORT_TEST_DECLS_ASYNC
CMD_TEST_DECLS
CMD_TEST_DECLS_ASYNC
EVENT_TEST_DECLS
TLM_TEST_DECLS
void testParam();
PARAM_CMD_TEST_DECLS
INTERNAL_INT_TEST_DECLS
void testTime();
PRIVATE:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_arrayArgsOut
//!
void from_arrayArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamArray& a, /*!<
An array
*/
FormalParamArray& aRef /*!<
An array ref
*/
);
//! Handler for from_arrayReturnOut
//!
FormalParamArray from_arrayReturnOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamArray& a, /*!<
An array
*/
FormalParamArray& aRef /*!<
An array ref
*/
);
//! Handler for from_enumArgsOut
//!
void from_enumArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamEnum& en, /*!<
An enum
*/
FormalParamEnum& enRef /*!<
An enum ref
*/
);
//! Handler for from_enumReturnOut
//!
FormalParamEnum from_enumReturnOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamEnum& en, /*!<
An enum
*/
FormalParamEnum& enRef /*!<
An enum ref
*/
);
//! Handler for from_noArgsOut
//!
void from_noArgsOut_handler(const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Handler for from_noArgsReturnOut
//!
bool from_noArgsReturnOut_handler(const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Handler for from_primitiveArgsOut
//!
void from_primitiveArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef);
//! Handler for from_primitiveReturnOut
//!
U32 from_primitiveReturnOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef);
//! Handler for from_prmGetIn
//!
Fw::ParamValid from_prmGetIn_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
FwPrmIdType id, /*!<
Parameter ID
*/
Fw::ParamBuffer& val /*!<
Buffer containing serialized parameter value
*/
);
//! Handler for from_prmGetIn
//!
void from_prmSetIn_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
FwPrmIdType id, /*!<
Parameter ID
*/
Fw::ParamBuffer& val /*!<
Buffer containing serialized parameter value
*/
);
//! Handler for from_stringArgsOut
//!
void from_stringArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const str80String& str80, /*!<
A string of size 80
*/
str80RefString& str80Ref,
const str100String& str100, /*!<
A string of size 100
*/
str100RefString& str100Ref);
//! Handler for from_structArgsOut
//!
void from_structArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamStruct& s, /*!<
A struct
*/
FormalParamStruct& sRef /*!<
A struct ref
*/
);
//! Handler for from_structReturnOut
//!
FormalParamStruct from_structReturnOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamStruct& s, /*!<
A struct
*/
FormalParamStruct& sRef /*!<
A struct ref
*/
);
PRIVATE:
// ----------------------------------------------------------------------
// Handlers for serial from ports
// ----------------------------------------------------------------------
//! Handler for from_serialOut
//!
void from_serialOut_handler(NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase& Buffer /*!< The serialization buffer*/
);
public:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Connect async ports
void connectAsyncPorts();
//! Connect prmSetIn port
void connectPrmSetIn();
//! Connect timeGetOut port
void connectTimeGetOut();
//! Connect serial ports to special ports
void connectSpecialPortsSerial();
//! Set prmValid
void setPrmValid(Fw::ParamValid valid);
//! Call doDispatch() on component under test
Fw::QueuedComponentBase::MsgDispatchStatus doDispatch();
//! Initialize components
//!
void initComponents();
//! Check successful status of a serial port invocation
void checkSerializeStatusSuccess();
//! Check unsuccessful status of a serial port invocation
void checkSerializeStatusBufferEmpty();
PRIVATE:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
ActiveTest component;
// Values returned by typed output ports
FppTest::Types::BoolType noParamReturnVal;
FppTest::Types::U32Type primitiveReturnVal;
FppTest::Types::EnumType enumReturnVal;
FppTest::Types::ArrayType arrayReturnVal;
FppTest::Types::StructType structReturnVal;
// Buffers from serial output ports;
U8 primitiveData[InputPrimitiveArgsPort::SERIALIZED_SIZE];
U8 stringData[InputStringArgsPort::SERIALIZED_SIZE];
U8 enumData[InputEnumArgsPort::SERIALIZED_SIZE];
U8 arrayData[InputArrayArgsPort::SERIALIZED_SIZE];
U8 structData[InputStructArgsPort::SERIALIZED_SIZE];
U8 serialData[SERIAL_ARGS_BUFFER_CAPACITY];
Fw::SerialBuffer primitiveBuf;
Fw::SerialBuffer stringBuf;
Fw::SerialBuffer enumBuf;
Fw::SerialBuffer arrayBuf;
Fw::SerialBuffer structBuf;
Fw::SerialBuffer serialBuf;
// Parameter test values
FppTest::Types::BoolParam boolPrm;
FppTest::Types::U32Param u32Prm;
FppTest::Types::PrmStringParam stringPrm;
FppTest::Types::EnumParam enumPrm;
FppTest::Types::ArrayParam arrayPrm;
FppTest::Types::StructParam structPrm;
Fw::ParamValid prmValid;
// Time test values
Fw::Time time;
};
#endif
| hpp |
fprime | data/projects/fprime/FppTest/component/empty/Empty.cpp | // ======================================================================
// \title Empty.cpp
// \author tiffany
// \brief cpp file for Empty component implementation class
// ======================================================================
#include "Empty.hpp"
#include <FpConfig.hpp>
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
Empty ::
Empty(
const char *const compName
) : EmptyComponentBase(compName)
{
}
void Empty ::
init(
NATIVE_INT_TYPE instance
)
{
EmptyComponentBase::init(instance);
}
Empty ::
~Empty()
{
}
| cpp |
fprime | data/projects/fprime/FppTest/component/empty/Empty.hpp | // ======================================================================
// \title Empty.hpp
// \author tiffany
// \brief hpp file for Empty component implementation class
// ======================================================================
#ifndef Empty_HPP
#define Empty_HPP
#include "FppTest/component/empty/EmptyComponentAc.hpp"
class Empty :
public EmptyComponentBase
{
public:
// ----------------------------------------------------------------------
// Component construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct Empty object
Empty(
const char* const compName //!< The component name
);
//! Initialize Empty object
void init(
NATIVE_INT_TYPE instance = 0 //!< The instance number
);
//! Destroy Empty object
~Empty();
};
#endif
| hpp |
fprime | data/projects/fprime/FppTest/component/empty/test/ut/TesterHelpers.cpp | // ======================================================================
// \title Empty/test/ut/TesterHelpers.cpp
// \author Auto-generated
// \brief cpp file for Empty component test harness base class
//
// NOTE: this file was automatically generated
//
// ======================================================================
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void Tester ::connectPorts() {}
void Tester ::initComponents() {
this->init();
this->component.init(Tester::TEST_INSTANCE_ID);
}
| cpp |
fprime | data/projects/fprime/FppTest/component/empty/test/ut/Tester.cpp | // ======================================================================
// \title Empty/test/ut/Tester.cpp
// \author tiffany
// \brief cpp file for Empty test harness implementation class
// ======================================================================
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
Tester ::Tester() : EmptyGTestBase("Tester", Tester::MAX_HISTORY_SIZE), component("Empty") {
this->initComponents();
this->connectPorts();
}
Tester ::~Tester() {}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void Tester ::test() {
// Nothing else to test in an empty component
}
| cpp |
fprime | data/projects/fprime/FppTest/component/empty/test/ut/Tester.hpp | // ======================================================================
// \title Empty/test/ut/Tester.hpp
// \author tiffany
// \brief hpp file for Empty test harness implementation class
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include "EmptyGTestBase.hpp"
#include "FppTest/component/empty/Empty.hpp"
class Tester : public EmptyGTestBase {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
// Maximum size of histories storing events, telemetry, and port outputs
static const NATIVE_INT_TYPE MAX_HISTORY_SIZE = 10;
// Instance ID supplied to the component instance under test
static const NATIVE_INT_TYPE TEST_INSTANCE_ID = 0;
//! Construct object Tester
//!
Tester();
//! Destroy object Tester
//!
~Tester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void test();
PRIVATE:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
PRIVATE:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
Empty component;
};
#endif
| hpp |
fprime | data/projects/fprime/FppTest/component/empty/test/ut/TestMain.cpp | // ----------------------------------------------------------------------
// TestMain.cpp
// ----------------------------------------------------------------------
#include "Tester.hpp"
TEST(Nominal, ToDo) {
Tester tester;
tester.test();
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/FppTest/component/queued/QueuedTest.cpp | // ======================================================================
// \title QueuedTest.cpp
// \author tiffany
// \brief cpp file for QueuedTest component implementation class
// ======================================================================
#include "QueuedTest.hpp"
#include <FpConfig.hpp>
#include "FppTest/component/active/SerialPortIndexEnumAc.hpp"
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
QueuedTest ::
QueuedTest(
const char *const compName
) : QueuedTestComponentBase(compName)
{
}
void QueuedTest ::
init(
NATIVE_INT_TYPE queueDepth,
NATIVE_INT_TYPE msgSize,
NATIVE_INT_TYPE instance
)
{
QueuedTestComponentBase::init(queueDepth, msgSize, instance);
}
QueuedTest ::
~QueuedTest()
{
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void QueuedTest ::
arrayArgsAsync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
this->arrayArgsOut_out(portNum, a, aRef);
}
void QueuedTest ::
enumArgsAsync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
this->enumArgsOut_out(portNum, en, enRef);
}
void QueuedTest ::
noArgsAsync_handler(
const NATIVE_INT_TYPE portNum
)
{
this->noArgsOut_out(portNum);
}
void QueuedTest ::
primitiveArgsAsync_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
this->primitiveArgsOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
void QueuedTest ::
structArgsAsync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
this->structArgsOut_out(portNum, s, sRef);
}
void QueuedTest ::
stringArgsAsync_handler(
const NATIVE_INT_TYPE portNum,
const str80String &str80,
str80RefString &str80Ref,
const str100String &str100,
str100RefString &str100Ref
)
{
this->stringArgsOut_out(
portNum,
str80,
str80Ref,
str100,
str100Ref
);
}
void QueuedTest ::
arrayArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
this->arrayArgsOut_out(portNum, a, aRef);
}
void QueuedTest ::
arrayArgsSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
this->arrayArgsOut_out(portNum, a, aRef);
}
FormalParamArray QueuedTest ::
arrayReturnGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
return this->arrayReturnOut_out(portNum, a, aRef);
}
FormalParamArray QueuedTest ::
arrayReturnSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamArray &a,
FormalParamArray &aRef
)
{
return this->arrayReturnOut_out(portNum, a, aRef);
}
void QueuedTest ::
cmdOut_handler(
NATIVE_INT_TYPE portNum,
FwOpcodeType opCode,
U32 cmdSeq,
Fw::CmdArgBuffer& args
)
{
}
void QueuedTest ::
enumArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
this->enumArgsOut_out(portNum, en, enRef);
}
void QueuedTest ::
enumArgsSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
this->enumArgsOut_out(portNum, en, enRef);
}
FormalParamEnum QueuedTest ::
enumReturnGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
return this->enumReturnOut_out(portNum, en, enRef);
}
FormalParamEnum QueuedTest ::
enumReturnSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamEnum &en,
FormalParamEnum &enRef
)
{
return this->enumReturnOut_out(portNum, en, enRef);
}
void QueuedTest ::
noArgsGuarded_handler(
const NATIVE_INT_TYPE portNum
)
{
this->noArgsOut_out(portNum);
}
bool QueuedTest ::
noArgsReturnGuarded_handler(
const NATIVE_INT_TYPE portNum
)
{
return this->noArgsReturnOut_out(portNum);
}
bool QueuedTest ::
noArgsReturnSync_handler(
const NATIVE_INT_TYPE portNum
)
{
return this->noArgsReturnOut_out(portNum);
}
void QueuedTest ::
noArgsSync_handler(
const NATIVE_INT_TYPE portNum
)
{
this->noArgsOut_out(portNum);
}
void QueuedTest ::
primitiveArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
this->primitiveArgsOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
void QueuedTest ::
primitiveArgsSync_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
this->primitiveArgsOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
U32 QueuedTest ::
primitiveReturnGuarded_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
return this->primitiveReturnOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
U32 QueuedTest ::
primitiveReturnSync_handler(
const NATIVE_INT_TYPE portNum,
U32 u32,
U32 &u32Ref,
F32 f32,
F32 &f32Ref,
bool b,
bool &bRef
)
{
return this->primitiveReturnOut_out(
portNum,
u32,
u32Ref,
f32,
f32Ref,
b,
bRef
);
}
void QueuedTest ::
stringArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
const str80String &str80,
str80RefString &str80Ref,
const str100String &str100,
str100RefString &str100Ref
)
{
this->stringArgsOut_out(
portNum,
str80,
str80Ref,
str100,
str100Ref
);
}
void QueuedTest ::
stringArgsSync_handler(
const NATIVE_INT_TYPE portNum,
const str80String &str80,
str80RefString &str80Ref,
const str100String &str100,
str100RefString &str100Ref
)
{
this->stringArgsOut_out(
portNum,
str80,
str80Ref,
str100,
str100Ref
);
}
void QueuedTest ::
structArgsGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
this->structArgsOut_out(portNum, s, sRef);
}
void QueuedTest ::
structArgsSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
this->structArgsOut_out(portNum, s, sRef);
}
FormalParamStruct QueuedTest ::
structReturnGuarded_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
return this->structReturnOut_out(portNum, s, sRef);
}
FormalParamStruct QueuedTest ::
structReturnSync_handler(
const NATIVE_INT_TYPE portNum,
const FormalParamStruct &s,
FormalParamStruct &sRef
)
{
return this->structReturnOut_out(portNum, s, sRef);
}
// ----------------------------------------------------------------------
// Handler implementations for user-defined serial input ports
// ----------------------------------------------------------------------
void QueuedTest ::
serialAsync_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(portNum, Buffer);
}
void QueuedTest ::
serialAsyncAssert_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(SerialPortIndex::ENUM, Buffer);
}
void QueuedTest ::
serialAsyncBlockPriority_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(SerialPortIndex::ARRAY, Buffer);
}
void QueuedTest ::
serialAsyncDropPriority_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(SerialPortIndex::STRUCT, Buffer);
}
void QueuedTest ::
serialGuarded_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(portNum, Buffer);
}
void QueuedTest ::
serialSync_handler(
NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase &Buffer /*!< The serialization buffer*/
)
{
this->serializeStatus = this->serialOut_out(portNum, Buffer);
}
// ----------------------------------------------------------------------
// Command handler implementations
// ----------------------------------------------------------------------
void QueuedTest ::
CMD_ASYNC_NO_ARGS_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq
)
{
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void QueuedTest ::
CMD_ASYNC_PRIMITIVE_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
U32 u32_1,
U32 u32_2,
F32 f32_1,
F32 f32_2,
bool b1,
bool b2
)
{
this->primitiveCmd.args.val1 = u32_1;
this->primitiveCmd.args.val2 = u32_2;
this->primitiveCmd.args.val3 = f32_1;
this->primitiveCmd.args.val4 = f32_2;
this->primitiveCmd.args.val5 = b1;
this->primitiveCmd.args.val6 = b2;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void QueuedTest ::
CMD_ASYNC_STRINGS_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
const Fw::CmdStringArg& str1,
const Fw::CmdStringArg& str2
)
{
this->stringCmd.args.val1 = str1;
this->stringCmd.args.val2 = str2;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void QueuedTest ::
CMD_ASYNC_ENUM_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamEnum en
)
{
this->enumCmd.args.val = en;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void QueuedTest ::
CMD_ASYNC_ARRAY_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamArray arr
)
{
this->arrayCmd.args.val = arr;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void QueuedTest ::
CMD_ASYNC_STRUCT_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamStruct str
)
{
this->structCmd.args.val = str;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void QueuedTest ::
CMD_NO_ARGS_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq
)
{
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void QueuedTest ::
CMD_PRIMITIVE_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
U32 u32_1,
U32 u32_2,
F32 f32_1,
F32 f32_2,
bool b1,
bool b2
)
{
this->primitiveCmd.args.val1 = u32_1;
this->primitiveCmd.args.val2 = u32_2;
this->primitiveCmd.args.val3 = f32_1;
this->primitiveCmd.args.val4 = f32_2;
this->primitiveCmd.args.val5 = b1;
this->primitiveCmd.args.val6 = b2;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void QueuedTest ::
CMD_STRINGS_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
const Fw::CmdStringArg& str1,
const Fw::CmdStringArg& str2
)
{
this->stringCmd.args.val1 = str1;
this->stringCmd.args.val2 = str2;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void QueuedTest ::
CMD_ENUM_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamEnum en
)
{
this->enumCmd.args.val = en;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void QueuedTest ::
CMD_ARRAY_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamArray arr
)
{
this->arrayCmd.args.val = arr;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
void QueuedTest ::
CMD_STRUCT_cmdHandler(
const FwOpcodeType opCode,
const U32 cmdSeq,
FormalParamStruct str
)
{
this->structCmd.args.val = str;
this->cmdResponse_out(opCode,cmdSeq,Fw::CmdResponse::OK);
}
// ----------------------------------------------------------------------
// Internal interface handlers
// ----------------------------------------------------------------------
//! Internal interface handler for internalArray
void QueuedTest ::
internalArray_internalInterfaceHandler(
const FormalParamArray& arr //!< An array
)
{
this->arrayInterface.args.val = arr;
}
//! Internal interface handler for internalEnum
void QueuedTest ::
internalEnum_internalInterfaceHandler(
const FormalParamEnum& en //!< An enum
)
{
this->enumInterface.args.val = en;
}
//! Internal interface handler for internalNoArgs
void QueuedTest ::
internalNoArgs_internalInterfaceHandler()
{
}
//! Internal interface handler for internalPrimitive
void QueuedTest ::
internalPrimitive_internalInterfaceHandler(
U32 u32_1, //!< A U32
U32 u32_2, //!< A U32
F32 f32_1, //!< An F32
F32 f32_2, //!< An F32
bool b1, //!< A boolean
bool b2 //!< A boolean
)
{
this->primitiveInterface.args.val1 = u32_1;
this->primitiveInterface.args.val2 = u32_2;
this->primitiveInterface.args.val3 = f32_1;
this->primitiveInterface.args.val4 = f32_2;
this->primitiveInterface.args.val5 = b1;
this->primitiveInterface.args.val6 = b2;
}
//! Internal interface handler for internalString
void QueuedTest ::
internalString_internalInterfaceHandler(
const Fw::InternalInterfaceString& str1, //!< A string
const Fw::InternalInterfaceString& str2 //!< Another string
)
{
this->stringInterface.args.val1 = str1;
this->stringInterface.args.val2 = str2;
}
//! Internal interface handler for internalStruct
void QueuedTest ::
internalStruct_internalInterfaceHandler(
const FormalParamStruct& str //!< A struct
)
{
this->structInterface.args.val = str;
}
| cpp |
fprime | data/projects/fprime/FppTest/component/queued/QueuedTest.hpp | // ======================================================================
// \title QueuedTest.hpp
// \author tiffany
// \brief hpp file for QueuedTest component implementation class
// ======================================================================
#ifndef QueuedTest_HPP
#define QueuedTest_HPP
#include "FppTest/component/queued/QueuedTestComponentAc.hpp"
#include "FppTest/component/types/FormalParamTypes.hpp"
class QueuedTest :
public QueuedTestComponentBase
{
public:
// ----------------------------------------------------------------------
// Component construction and destruction
// ----------------------------------------------------------------------
//! Construct QueuedTest object
QueuedTest(
const char* const compName //!< The component name
);
//! Initialize QueuedTest object
void init(
NATIVE_INT_TYPE queueDepth, //!< The queue depth
NATIVE_INT_TYPE msgSize, //!< The message size
NATIVE_INT_TYPE instance = 0 //!< The instance number
);
//! Destroy QueuedTest object
~QueuedTest();
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for arrayArgsAsync
void arrayArgsAsync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for arrayArgsGuarded
void arrayArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for arrayArgsSync
void arrayArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for arrayReturnGuarded
FormalParamArray arrayReturnGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for arrayReturnSync
FormalParamArray arrayReturnSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamArray& a, //!< An array
FormalParamArray& aRef //!< An array ref
);
//! Handler implementation for cmdOut
void cmdOut_handler(
NATIVE_INT_TYPE portNum, //!< The port number
FwOpcodeType opCode, //!< Command Op Code
U32 cmdSeq, //!< Command Sequence
Fw::CmdArgBuffer& args //!< Buffer containing arguments
);
//! Handler implementation for enumArgsAsync
void enumArgsAsync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for enumArgsGuarded
void enumArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for enumArgsSync
void enumArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for enumReturnGuarded
FormalParamEnum enumReturnGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for enumReturnSync
FormalParamEnum enumReturnSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamEnum& en, //!< An enum
FormalParamEnum& enRef //!< An enum ref
);
//! Handler implementation for noArgsAsync
void noArgsAsync_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for noArgsGuarded
void noArgsGuarded_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for noArgsReturnGuarded
bool noArgsReturnGuarded_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for noArgsReturnSync
bool noArgsReturnSync_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for noArgsSync
void noArgsSync_handler(
NATIVE_INT_TYPE portNum //!< The port number
);
//! Handler implementation for primitiveArgsAsync
void primitiveArgsAsync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for primitiveArgsGuarded
void primitiveArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for primitiveArgsSync
void primitiveArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for primitiveReturnGuarded
U32 primitiveReturnGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for primitiveReturnSync
U32 primitiveReturnSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef
);
//! Handler implementation for stringArgsAsync
void stringArgsAsync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const StringArgsPortStrings::StringSize80& str80, //!< A string of size 80
StringArgsPortStrings::StringSize80& str80Ref,
const StringArgsPortStrings::StringSize100& str100, //!< A string of size 100
StringArgsPortStrings::StringSize100& str100Ref
);
//! Handler implementation for stringArgsGuarded
void stringArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const StringArgsPortStrings::StringSize80& str80, //!< A string of size 80
StringArgsPortStrings::StringSize80& str80Ref,
const StringArgsPortStrings::StringSize100& str100, //!< A string of size 100
StringArgsPortStrings::StringSize100& str100Ref
);
//! Handler implementation for stringArgsSync
void stringArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const StringArgsPortStrings::StringSize80& str80, //!< A string of size 80
StringArgsPortStrings::StringSize80& str80Ref,
const StringArgsPortStrings::StringSize100& str100, //!< A string of size 100
StringArgsPortStrings::StringSize100& str100Ref
);
//! Handler implementation for structArgsAsync
void structArgsAsync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
//! Handler implementation for structArgsGuarded
void structArgsGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
//! Handler implementation for structArgsSync
void structArgsSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
//! Handler implementation for structReturnGuarded
FormalParamStruct structReturnGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
//! Handler implementation for structReturnSync
FormalParamStruct structReturnSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
const FormalParamStruct& s, //!< A struct
FormalParamStruct& sRef //!< A struct ref
);
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined serial input ports
// ----------------------------------------------------------------------
//! Handler implementation for serialAsync
void serialAsync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
//! Handler implementation for serialAsyncAssert
void serialAsyncAssert_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
//! Handler implementation for serialAsyncBlockPriority
void serialAsyncBlockPriority_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
//! Handler implementation for serialAsyncDropPriority
void serialAsyncDropPriority_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
//! Handler implementation for serialGuarded
void serialGuarded_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
//! Handler implementation for serialSync
void serialSync_handler(
NATIVE_INT_TYPE portNum, //!< The port number
Fw::SerializeBufferBase& buffer //!< The serialization buffer
);
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for commands
// ----------------------------------------------------------------------
//! Handler implementation for command CMD_NO_ARGS
void CMD_NO_ARGS_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq //!< The command sequence number
);
//! Handler implementation for command CMD_PRIMITIVE
void CMD_PRIMITIVE_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
U32 u32_1, //!< A U32
U32 u32_2, //!< A U32
F32 f32_1, //!< An F32
F32 f32_2, //!< An F32
bool b1, //!< A boolean
bool b2 //!< A boolean
);
//! Handler implementation for command CMD_STRINGS
void CMD_STRINGS_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
const Fw::CmdStringArg& str1, //!< A string
const Fw::CmdStringArg& str2 //!< Another string
);
//! Handler implementation for command CMD_ENUM
void CMD_ENUM_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamEnum en //!< An enum
);
//! Handler implementation for command CMD_ARRAY
void CMD_ARRAY_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamArray arr //!< An array
);
//! Handler implementation for command CMD_STRUCT
void CMD_STRUCT_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamStruct str //!< A struct
);
//! Handler implementation for command CMD_ASYNC_NO_ARGS
void CMD_ASYNC_NO_ARGS_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq //!< The command sequence number
);
//! Handler implementation for command CMD_ASYNC_PRIMITIVE
void CMD_ASYNC_PRIMITIVE_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
U32 u32_1, //!< A U32
U32 u32_2, //!< A U32
F32 f32_1, //!< An F32
F32 f32_2, //!< An F32
bool b1, //!< A boolean
bool b2 //!< A boolean
);
//! Handler implementation for command CMD_ASYNC_STRINGS
void CMD_ASYNC_STRINGS_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
const Fw::CmdStringArg& str1, //!< A string
const Fw::CmdStringArg& str2 //!< Another string
);
//! Handler implementation for command CMD_ASYNC_ENUM
void CMD_ASYNC_ENUM_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamEnum en //!< An enum
);
//! Handler implementation for command CMD_ASYNC_ARRAY
void CMD_ASYNC_ARRAY_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamArray arr //!< An array
);
//! Handler implementation for command CMD_ASYNC_STRUCT
void CMD_ASYNC_STRUCT_cmdHandler(
FwOpcodeType opCode, //!< The opcode
U32 cmdSeq, //!< The command sequence number
FormalParamStruct str //!< A struct
);
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined internal interfaces
// ----------------------------------------------------------------------
//! Handler implementation for internalArray
void internalArray_internalInterfaceHandler(
const FormalParamArray& arr //!< An array
);
//! Handler implementation for internalEnum
void internalEnum_internalInterfaceHandler(
const FormalParamEnum& en //!< An enum
);
//! Handler implementation for internalNoArgs
void internalNoArgs_internalInterfaceHandler();
//! Handler implementation for internalPrimitive
void internalPrimitive_internalInterfaceHandler(
U32 u32_1, //!< A U32
U32 u32_2, //!< A U32
F32 f32_1, //!< An F32
F32 f32_2, //!< An F32
bool b1, //!< A boolean
bool b2 //!< A boolean
);
//! Handler implementation for internalString
void internalString_internalInterfaceHandler(
const Fw::InternalInterfaceString& str1, //!< A string
const Fw::InternalInterfaceString& str2 //!< Another string
);
//! Handler implementation for internalStruct
void internalStruct_internalInterfaceHandler(
const FormalParamStruct& str //!< A struct
);
public:
//! Enables checking the serialization status of serial port invocations
Fw::SerializeStatus serializeStatus;
// Command test values
FppTest::Types::PrimitiveParams primitiveCmd;
FppTest::Types::CmdStringParams stringCmd;
FppTest::Types::EnumParam enumCmd;
FppTest::Types::ArrayParam arrayCmd;
FppTest::Types::StructParam structCmd;
// Internal interface test values
FppTest::Types::PrimitiveParams primitiveInterface;
FppTest::Types::InternalInterfaceStringParams stringInterface;
FppTest::Types::EnumParam enumInterface;
FppTest::Types::ArrayParam arrayInterface;
FppTest::Types::StructParam structInterface;
};
#endif
| hpp |
fprime | data/projects/fprime/FppTest/component/queued/test/ut/TesterHelpers.cpp | // ======================================================================
// \title QueuedTest/test/ut/TesterHelpers.cpp
// \author Auto-generated
// \brief cpp file for QueuedTest component test harness base class
//
// NOTE: this file was automatically generated
//
// ======================================================================
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void Tester ::connectPorts() {
// arrayArgsAsyncBlockPriority
this->connect_to_arrayArgsAsyncBlockPriority(0, this->component.get_arrayArgsAsyncBlockPriority_InputPort(0));
// arrayArgsGuarded
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_arrayArgsGuarded(i, this->component.get_arrayArgsGuarded_InputPort(i));
}
// arrayArgsSync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_arrayArgsSync(i, this->component.get_arrayArgsSync_InputPort(i));
}
// arrayReturnGuarded
this->connect_to_arrayReturnGuarded(0, this->component.get_arrayReturnGuarded_InputPort(0));
// arrayReturnSync
this->connect_to_arrayReturnSync(0, this->component.get_arrayReturnSync_InputPort(0));
// cmdIn
this->connect_to_cmdIn(0, this->component.get_cmdIn_InputPort(0));
// enumArgsAsyncAssert
this->connect_to_enumArgsAsyncAssert(0, this->component.get_enumArgsAsyncAssert_InputPort(0));
// enumArgsGuarded
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_enumArgsGuarded(i, this->component.get_enumArgsGuarded_InputPort(i));
}
// enumArgsSync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_enumArgsSync(i, this->component.get_enumArgsSync_InputPort(i));
}
// enumReturnGuarded
this->connect_to_enumReturnGuarded(0, this->component.get_enumReturnGuarded_InputPort(0));
// enumReturnSync
this->connect_to_enumReturnSync(0, this->component.get_enumReturnSync_InputPort(0));
// noArgsAsync
this->connect_to_noArgsAsync(0, this->component.get_noArgsAsync_InputPort(0));
// noArgsGuarded
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_noArgsGuarded(i, this->component.get_noArgsGuarded_InputPort(i));
}
// noArgsReturnGuarded
this->connect_to_noArgsReturnGuarded(0, this->component.get_noArgsReturnGuarded_InputPort(0));
// noArgsReturnSync
this->connect_to_noArgsReturnSync(0, this->component.get_noArgsReturnSync_InputPort(0));
// noArgsSync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_noArgsSync(i, this->component.get_noArgsSync_InputPort(i));
}
// primitiveArgsAsync
this->connect_to_primitiveArgsAsync(0, this->component.get_primitiveArgsAsync_InputPort(0));
// primitiveArgsGuarded
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_primitiveArgsGuarded(i, this->component.get_primitiveArgsGuarded_InputPort(i));
}
// primitiveArgsSync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_primitiveArgsSync(i, this->component.get_primitiveArgsSync_InputPort(i));
}
// primitiveReturnGuarded
this->connect_to_primitiveReturnGuarded(0, this->component.get_primitiveReturnGuarded_InputPort(0));
// primitiveReturnSync
this->connect_to_primitiveReturnSync(0, this->component.get_primitiveReturnSync_InputPort(0));
// stringArgsAsync
this->connect_to_stringArgsAsync(0, this->component.get_stringArgsAsync_InputPort(0));
// stringArgsGuarded
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_stringArgsGuarded(i, this->component.get_stringArgsGuarded_InputPort(i));
}
// stringArgsSync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_stringArgsSync(i, this->component.get_stringArgsSync_InputPort(i));
}
// structArgsAsyncDropPriority
this->connect_to_structArgsAsyncDropPriority(0, this->component.get_structArgsAsyncDropPriority_InputPort(0));
// structArgsGuarded
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_structArgsGuarded(i, this->component.get_structArgsGuarded_InputPort(i));
}
// structArgsSync
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->connect_to_structArgsSync(i, this->component.get_structArgsSync_InputPort(i));
}
// structReturnGuarded
this->connect_to_structReturnGuarded(0, this->component.get_structReturnGuarded_InputPort(0));
// structReturnSync
this->connect_to_structReturnSync(0, this->component.get_structReturnSync_InputPort(0));
// arrayArgsOut
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->component.set_arrayArgsOut_OutputPort(i, this->get_from_arrayArgsOut(i));
}
// arrayReturnOut
this->component.set_arrayReturnOut_OutputPort(0, this->get_from_arrayReturnOut(0));
// cmdRegOut
this->component.set_cmdRegOut_OutputPort(0, this->get_from_cmdRegOut(0));
// cmdResponseOut
this->component.set_cmdResponseOut_OutputPort(0, this->get_from_cmdResponseOut(0));
// enumArgsOut
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->component.set_enumArgsOut_OutputPort(i, this->get_from_enumArgsOut(i));
}
// enumReturnOut
this->component.set_enumReturnOut_OutputPort(0, this->get_from_enumReturnOut(0));
// eventOut
this->component.set_eventOut_OutputPort(0, this->get_from_eventOut(0));
// noArgsOut
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->component.set_noArgsOut_OutputPort(i, this->get_from_noArgsOut(i));
}
// noArgsReturnOut
this->component.set_noArgsReturnOut_OutputPort(0, this->get_from_noArgsReturnOut(0));
// primitiveArgsOut
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->component.set_primitiveArgsOut_OutputPort(i, this->get_from_primitiveArgsOut(i));
}
// primitiveReturnOut
this->component.set_primitiveReturnOut_OutputPort(0, this->get_from_primitiveReturnOut(0));
// prmGetOut
this->component.set_prmGetOut_OutputPort(0, this->get_from_prmGetOut(0));
// prmSetOut
this->component.set_prmSetOut_OutputPort(0, this->get_from_prmSetOut(0));
// stringArgsOut
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->component.set_stringArgsOut_OutputPort(i, this->get_from_stringArgsOut(i));
}
// structArgsOut
for (NATIVE_INT_TYPE i = 0; i < 2; ++i) {
this->component.set_structArgsOut_OutputPort(i, this->get_from_structArgsOut(i));
}
// structReturnOut
this->component.set_structReturnOut_OutputPort(0, this->get_from_structReturnOut(0));
// textEventOut
this->component.set_textEventOut_OutputPort(0, this->get_from_textEventOut(0));
// timeGetOut
this->component.set_timeGetOut_OutputPort(0, this->get_from_timeGetOut(0));
// tlmOut
this->component.set_tlmOut_OutputPort(0, this->get_from_tlmOut(0));
// ----------------------------------------------------------------------
// Connect serial output ports
// ----------------------------------------------------------------------
for (NATIVE_INT_TYPE i = 0; i < 5; ++i) {
this->component.set_serialOut_OutputPort(i, this->get_from_serialOut(i));
}
// ----------------------------------------------------------------------
// Connect serial input ports
// ----------------------------------------------------------------------
// serialAsync
this->connect_to_serialAsync(0, this->component.get_serialAsync_InputPort(0));
// serialAsyncAssert
this->connect_to_serialAsyncAssert(0, this->component.get_serialAsyncAssert_InputPort(0));
// serialAsyncBlockPriority
this->connect_to_serialAsyncBlockPriority(0, this->component.get_serialAsyncBlockPriority_InputPort(0));
// serialAsyncDropPriority
this->connect_to_serialAsyncDropPriority(0, this->component.get_serialAsyncDropPriority_InputPort(0));
// serialGuarded
this->connect_to_serialGuarded(0, this->component.get_serialGuarded_InputPort(0));
// serialSync
this->connect_to_serialSync(0, this->component.get_serialSync_InputPort(0));
}
void Tester ::initComponents() {
this->init();
this->component.init(Tester::TEST_INSTANCE_QUEUE_DEPTH, Tester::TEST_INSTANCE_ID);
}
| cpp |
fprime | data/projects/fprime/FppTest/component/queued/test/ut/Tester.cpp | // ======================================================================
// \title QueuedTest/test/ut/Tester.cpp
// \author tiffany
// \brief cpp file for QueuedTest test harness implementation class
// ======================================================================
#include "STest/Pick/Pick.hpp"
#include "Tester.hpp"
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
Tester ::Tester()
: QueuedTestGTestBase("Tester", Tester::MAX_HISTORY_SIZE),
component("QueuedTest"),
primitiveBuf(primitiveData, sizeof(primitiveData)),
stringBuf(stringData, sizeof(stringData)),
enumBuf(enumData, sizeof(enumData)),
arrayBuf(arrayData, sizeof(arrayData)),
structBuf(structData, sizeof(structData)),
serialBuf(serialData, sizeof(serialData)),
time(STest::Pick::any(), STest::Pick::any()) {
this->initComponents();
this->connectPorts();
this->connectAsyncPorts();
}
Tester ::~Tester() {}
void Tester ::initComponents() {
this->init();
this->component.init(Tester::TEST_INSTANCE_QUEUE_DEPTH, Tester::TEST_INSTANCE_ID);
}
Fw::ParamValid Tester ::from_prmGetIn_handler(const NATIVE_INT_TYPE portNum, FwPrmIdType id, Fw::ParamBuffer& val) {
val.resetSer();
Fw::SerializeStatus status;
U32 id_base = component.getIdBase();
FW_ASSERT(id >= id_base);
switch (id - id_base) {
case QueuedTestComponentBase::PARAMID_PARAMBOOL:
status = val.serialize(boolPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case QueuedTestComponentBase::PARAMID_PARAMU32:
status = val.serialize(u32Prm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case QueuedTestComponentBase::PARAMID_PARAMSTRING:
status = val.serialize(stringPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case QueuedTestComponentBase::PARAMID_PARAMENUM:
status = val.serialize(enumPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case QueuedTestComponentBase::PARAMID_PARAMARRAY:
status = val.serialize(arrayPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case QueuedTestComponentBase::PARAMID_PARAMSTRUCT:
status = val.serialize(structPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
}
this->pushFromPortEntry_prmGetIn(id, val);
return prmValid;
}
void Tester ::from_prmSetIn_handler(const NATIVE_INT_TYPE portNum, FwPrmIdType id, Fw::ParamBuffer& val) {
Fw::SerializeStatus status;
U32 id_base = component.getIdBase();
FW_ASSERT(id >= id_base);
switch (id - id_base) {
case QueuedTestComponentBase::PARAMID_PARAMBOOL:
status = val.deserialize(boolPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case QueuedTestComponentBase::PARAMID_PARAMU32:
status = val.deserialize(u32Prm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case QueuedTestComponentBase::PARAMID_PARAMSTRING:
status = val.deserialize(stringPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case QueuedTestComponentBase::PARAMID_PARAMENUM:
status = val.deserialize(enumPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case QueuedTestComponentBase::PARAMID_PARAMARRAY:
status = val.deserialize(arrayPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
case QueuedTestComponentBase::PARAMID_PARAMSTRUCT:
status = val.deserialize(structPrm.args.val);
FW_ASSERT(status == Fw::FW_SERIALIZE_OK);
break;
}
this->pushFromPortEntry_prmSetIn(id, val);
}
| cpp |
fprime | data/projects/fprime/FppTest/component/queued/test/ut/Tester.hpp | // ======================================================================
// \title QueuedTest/test/ut/Tester.hpp
// \author tiffany
// \brief hpp file for QueuedTest test harness implementation class
// ======================================================================
#ifndef TESTER_HPP
#define TESTER_HPP
#include "FppTest/component/active/SerialPortIndexEnumAc.hpp"
#include "FppTest/component/active/TypedPortIndexEnumAc.hpp"
#include "FppTest/component/queued/QueuedTest.hpp"
#include "FppTest/component/tests/CmdTests.hpp"
#include "FppTest/component/tests/EventTests.hpp"
#include "FppTest/component/tests/InternalInterfaceTests.hpp"
#include "FppTest/component/tests/ParamTests.hpp"
#include "FppTest/component/tests/PortTests.hpp"
#include "FppTest/component/tests/TlmTests.hpp"
#include "FppTest/component/types/FormalParamTypes.hpp"
#include "QueuedTestGTestBase.hpp"
class Tester : public QueuedTestGTestBase {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
// Maximum size of histories storing events, telemetry, and port outputs
static const NATIVE_INT_TYPE MAX_HISTORY_SIZE = 100;
// Instance ID supplied to the component instance under test
static const NATIVE_INT_TYPE TEST_INSTANCE_ID = 0;
// Queue depth supplied to component instance under test
static const NATIVE_INT_TYPE TEST_INSTANCE_QUEUE_DEPTH = 10;
//! Construct object Tester
//!
Tester();
//! Destroy object Tester
//!
~Tester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
PORT_TEST_DECLS
PORT_TEST_DECLS_ASYNC
CMD_TEST_DECLS
CMD_TEST_DECLS_ASYNC
EVENT_TEST_DECLS
TLM_TEST_DECLS
void testParam();
PARAM_CMD_TEST_DECLS
INTERNAL_INT_TEST_DECLS
void testTime();
PRIVATE:
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
//! Handler for from_arrayArgsOut
//!
void from_arrayArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamArray& a, /*!<
An array
*/
FormalParamArray& aRef /*!<
An array ref
*/
);
//! Handler for from_arrayReturnOut
//!
FormalParamArray from_arrayReturnOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamArray& a, /*!<
An array
*/
FormalParamArray& aRef /*!<
An array ref
*/
);
//! Handler for from_enumArgsOut
//!
void from_enumArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamEnum& en, /*!<
An enum
*/
FormalParamEnum& enRef /*!<
An enum ref
*/
);
//! Handler for from_enumReturnOut
//!
FormalParamEnum from_enumReturnOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamEnum& en, /*!<
An enum
*/
FormalParamEnum& enRef /*!<
An enum ref
*/
);
//! Handler for from_noArgsOut
//!
void from_noArgsOut_handler(const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Handler for from_noArgsReturnOut
//!
bool from_noArgsReturnOut_handler(const NATIVE_INT_TYPE portNum /*!< The port number*/
);
//! Handler for from_primitiveArgsOut
//!
void from_primitiveArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef);
//! Handler for from_primitiveReturnOut
//!
U32 from_primitiveReturnOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
U32 u32,
U32& u32Ref,
F32 f32,
F32& f32Ref,
bool b,
bool& bRef);
//! Handler for from_prmGetIn
//!
Fw::ParamValid from_prmGetIn_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
FwPrmIdType id, /*!<
Parameter ID
*/
Fw::ParamBuffer& val /*!<
Buffer containing serialized parameter value
*/
);
//! Handler for from_prmGetIn
//!
void from_prmSetIn_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
FwPrmIdType id, /*!<
Parameter ID
*/
Fw::ParamBuffer& val /*!<
Buffer containing serialized parameter value
*/
);
//! Handler for from_stringArgsOut
//!
void from_stringArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const str80String& str80, /*!<
A string of size 80
*/
str80RefString& str80Ref,
const str100String& str100, /*!<
A string of size 100
*/
str100RefString& str100Ref);
//! Handler for from_structArgsOut
//!
void from_structArgsOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamStruct& s, /*!<
A struct
*/
FormalParamStruct& sRef /*!<
A struct ref
*/
);
//! Handler for from_structReturnOut
//!
FormalParamStruct from_structReturnOut_handler(const NATIVE_INT_TYPE portNum, /*!< The port number*/
const FormalParamStruct& s, /*!<
A struct
*/
FormalParamStruct& sRef /*!<
A struct ref
*/
);
PRIVATE:
// ----------------------------------------------------------------------
// Handlers for serial from ports
// ----------------------------------------------------------------------
//! Handler for from_serialOut
//!
void from_serialOut_handler(NATIVE_INT_TYPE portNum, /*!< The port number*/
Fw::SerializeBufferBase& Buffer /*!< The serialization buffer*/
);
public:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Connect async ports
void connectAsyncPorts();
//! Connect prmSetIn port
void connectPrmSetIn();
//! Connect timeGetOut port
void connectTimeGetOut();
//! Connect serial ports to special ports
void connectSpecialPortsSerial();
//! Set prmValid
void setPrmValid(Fw::ParamValid valid);
//! Call doDispatch() on component under test
Fw::QueuedComponentBase::MsgDispatchStatus doDispatch();
//! Initialize components
//!
void initComponents();
//! Check successful status of a serial port invocation
void checkSerializeStatusSuccess();
//! Check unsuccessful status of a serial port invocation
void checkSerializeStatusBufferEmpty();
PRIVATE:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! The component under test
//!
QueuedTest component;
// Values returned by typed output ports
FppTest::Types::BoolType noParamReturnVal;
FppTest::Types::U32Type primitiveReturnVal;
FppTest::Types::EnumType enumReturnVal;
FppTest::Types::ArrayType arrayReturnVal;
FppTest::Types::StructType structReturnVal;
// Buffers from serial output ports;
U8 primitiveData[InputPrimitiveArgsPort::SERIALIZED_SIZE];
U8 stringData[InputStringArgsPort::SERIALIZED_SIZE];
U8 enumData[InputEnumArgsPort::SERIALIZED_SIZE];
U8 arrayData[InputArrayArgsPort::SERIALIZED_SIZE];
U8 structData[InputStructArgsPort::SERIALIZED_SIZE];
U8 serialData[SERIAL_ARGS_BUFFER_CAPACITY];
Fw::SerialBuffer primitiveBuf;
Fw::SerialBuffer stringBuf;
Fw::SerialBuffer enumBuf;
Fw::SerialBuffer arrayBuf;
Fw::SerialBuffer structBuf;
Fw::SerialBuffer serialBuf;
// Parameter test values
FppTest::Types::BoolParam boolPrm;
FppTest::Types::U32Param u32Prm;
FppTest::Types::PrmStringParam stringPrm;
FppTest::Types::EnumParam enumPrm;
FppTest::Types::ArrayParam arrayPrm;
FppTest::Types::StructParam structPrm;
Fw::ParamValid prmValid;
// Time test values
Fw::Time time;
};
#endif
| hpp |
fprime | data/projects/fprime/FppTest/dp/DpTest.hpp | // ======================================================================
// \title DpTest.hpp
// \author bocchino
// \brief hpp file for DpTest component implementation class
// ======================================================================
#ifndef FppTest_DpTest_HPP
#define FppTest_DpTest_HPP
#include <array>
#include "FppTest/dp/DpTestComponentAc.hpp"
namespace FppTest {
class DpTest : public DpTestComponentBase {
public:
// ----------------------------------------------------------------------
// Constants
// ----------------------------------------------------------------------
static constexpr FwSizeType CONTAINER_1_DATA_SIZE = 100;
static constexpr FwSizeType CONTAINER_1_PACKET_SIZE = DpContainer::getPacketSizeForDataSize(CONTAINER_1_DATA_SIZE);
static constexpr FwSizeType CONTAINER_2_DATA_SIZE = 1000;
static constexpr FwSizeType CONTAINER_2_PACKET_SIZE = DpContainer::getPacketSizeForDataSize(CONTAINER_2_DATA_SIZE);
static constexpr FwSizeType CONTAINER_3_DATA_SIZE = 1000;
static constexpr FwSizeType CONTAINER_3_PACKET_SIZE = DpContainer::getPacketSizeForDataSize(CONTAINER_3_DATA_SIZE);
static constexpr FwSizeType CONTAINER_4_DATA_SIZE = 1000;
static constexpr FwSizeType CONTAINER_4_PACKET_SIZE = DpContainer::getPacketSizeForDataSize(CONTAINER_4_DATA_SIZE);
static constexpr FwSizeType CONTAINER_5_DATA_SIZE = 1000;
static constexpr FwSizeType CONTAINER_5_PACKET_SIZE = DpContainer::getPacketSizeForDataSize(CONTAINER_5_DATA_SIZE);
public:
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
using U8ArrayRecordData = std::array<U8, 256>;
using U32ArrayRecordData = std::array<U32, 100>;
using DataArrayRecordData = std::array<DpTest_Data, 300>;
public:
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
//! Construct object DpTest
DpTest(const char* const compName, //!< The component name
U32 u32RecordData, //!< The U32Record data
U16 dataRecordData, //!< The DataRecord data
const U8ArrayRecordData& u8ArrayRecordData, //!< The U8ArrayRecord data
const U32ArrayRecordData& u32ArrayRecordData, //!< The U32ArrayRecord data
const DataArrayRecordData& dataArrayRecordData //!< The DataArrayRecord data
);
//! Initialize object DpTest
void init(const NATIVE_INT_TYPE queueDepth, //!< The queue depth
const NATIVE_INT_TYPE instance = 0 //!< The instance number
);
//! Destroy object DpTest
~DpTest();
public:
// ----------------------------------------------------------------------
// Public interface methods
// ----------------------------------------------------------------------
//! Set the send time
void setSendTime(Fw::Time time) { this->sendTime = time; }
PRIVATE:
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
//! Handler implementation for schedIn
void schedIn_handler(const NATIVE_INT_TYPE portNum, //!< The port number
U32 context //!< The call order
) override;
PRIVATE:
// ----------------------------------------------------------------------
// Data product handler implementations
// ----------------------------------------------------------------------
//! Receive a data product container of type Container1
//! \return Serialize status
void dpRecv_Container1_handler(DpContainer& container, //!< The container
Fw::Success::T //!< The container status
) override;
//! Receive a data product container of type Container2
//! \return Serialize status
void dpRecv_Container2_handler(DpContainer& container, //!< The container
Fw::Success::T //!< The container status
) override;
//! Receive a data product container of type Container3
//! \return Serialize status
void dpRecv_Container3_handler(DpContainer& container, //!< The container
Fw::Success::T //!< The container status
) override;
//! Receive a data product container of type Container4
//! \return Serialize status
void dpRecv_Container4_handler(DpContainer& container, //!< The container
Fw::Success::T //!< The container status
) override;
//! Receive a data product container of type Container5
//! \return Serialize status
void dpRecv_Container5_handler(DpContainer& container, //!< The container
Fw::Success::T //!< The container status
) override;
PRIVATE:
// ----------------------------------------------------------------------
// Private helper functions
// ----------------------------------------------------------------------
//! Check a container for validity
void checkContainer(const DpContainer& container, //!< The container
FwDpIdType localId, //!< The expected local id
FwSizeType size //!< The expected size
) const;
PRIVATE:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! U32Record data
const U32 u32RecordData;
//! DataRecord data
const U16 dataRecordData;
//! U8ArrayRecord data
const U8ArrayRecordData& u8ArrayRecordData;
//! U32ArrayRecord data
const U32ArrayRecordData& u32ArrayRecordData;
//! DataArrayRecord data
const DataArrayRecordData& dataArrayRecordData;
//! Send time for testing
Fw::Time sendTime;
};
} // end namespace FppTest
#endif
| hpp |
fprime | data/projects/fprime/FppTest/dp/DpTest.cpp | // ======================================================================
// \title DpTest.cpp
// \author bocchino
// \brief cpp file for DpTest component implementation class
// ======================================================================
#include <cstdio>
#include "FppTest/dp/DpTest.hpp"
#include "Fw/Types/Assert.hpp"
namespace FppTest {
// ----------------------------------------------------------------------
// Construction, initialization, and destruction
// ----------------------------------------------------------------------
DpTest ::DpTest(const char* const compName,
U32 u32RecordData,
U16 dataRecordData,
const U8ArrayRecordData& u8ArrayRecordData,
const U32ArrayRecordData& u32ArrayRecordData,
const DataArrayRecordData& dataArrayRecordData)
: DpTestComponentBase(compName),
u32RecordData(u32RecordData),
dataRecordData(dataRecordData),
u8ArrayRecordData(u8ArrayRecordData),
u32ArrayRecordData(u32ArrayRecordData),
dataArrayRecordData(dataArrayRecordData),
sendTime(Fw::ZERO_TIME) {}
void DpTest ::init(const NATIVE_INT_TYPE queueDepth, const NATIVE_INT_TYPE instance) {
DpTestComponentBase::init(queueDepth, instance);
}
DpTest ::~DpTest() {}
// ----------------------------------------------------------------------
// Handler implementations for user-defined typed input ports
// ----------------------------------------------------------------------
void DpTest::schedIn_handler(const NATIVE_INT_TYPE portNum, U32 context) {
// Request a buffer for Container 1
this->dpRequest_Container1(CONTAINER_1_DATA_SIZE);
// Request a buffer for Container 2
this->dpRequest_Container2(CONTAINER_2_DATA_SIZE);
// Request a buffer for Container 3
this->dpRequest_Container3(CONTAINER_3_DATA_SIZE);
// Request a buffer for Container 4
this->dpRequest_Container4(CONTAINER_4_DATA_SIZE);
// Request a buffer for Container 5
this->dpRequest_Container5(CONTAINER_5_DATA_SIZE);
// Get a buffer for Container 1
{
DpContainer container;
Fw::Success status = this->dpGet_Container1(CONTAINER_1_DATA_SIZE, container);
FW_ASSERT(status == Fw::Success::SUCCESS, status);
// Check the container
this->checkContainer(container, ContainerId::Container1, CONTAINER_1_PACKET_SIZE);
}
// Get a buffer for Container 2
{
DpContainer container;
Fw::Success status = this->dpGet_Container2(CONTAINER_2_DATA_SIZE, container);
FW_ASSERT(status == Fw::Success::SUCCESS);
// Check the container
this->checkContainer(container, ContainerId::Container2, CONTAINER_2_PACKET_SIZE);
}
// Get a buffer for Container 3
{
DpContainer container;
Fw::Success status = this->dpGet_Container3(CONTAINER_3_DATA_SIZE, container);
// This one should fail
FW_ASSERT(status == Fw::Success::FAILURE);
}
// Get a buffer for Container 4
{
DpContainer container;
Fw::Success status = this->dpGet_Container4(CONTAINER_4_DATA_SIZE, container);
FW_ASSERT(status == Fw::Success::SUCCESS);
// Check the container
this->checkContainer(container, ContainerId::Container4, CONTAINER_4_PACKET_SIZE);
}
// Get a buffer for Container 5
{
DpContainer container;
Fw::Success status = this->dpGet_Container5(CONTAINER_5_DATA_SIZE, container);
FW_ASSERT(status == Fw::Success::SUCCESS);
// Check the container
this->checkContainer(container, ContainerId::Container5, CONTAINER_5_PACKET_SIZE);
}
}
// ----------------------------------------------------------------------
// Data product handler implementations
// ----------------------------------------------------------------------
void DpTest ::dpRecv_Container1_handler(DpContainer& container, Fw::Success::T status) {
if (status == Fw::Success::SUCCESS) {
auto serializeStatus = Fw::FW_SERIALIZE_OK;
for (FwSizeType i = 0; i < CONTAINER_1_DATA_SIZE; ++i) {
serializeStatus = container.serializeRecord_U32Record(this->u32RecordData);
if (serializeStatus == Fw::FW_SERIALIZE_NO_ROOM_LEFT) {
break;
}
FW_ASSERT(serializeStatus == Fw::FW_SERIALIZE_OK, status);
}
// Use the time stamp from the time get port
this->dpSend(container);
}
}
void DpTest ::dpRecv_Container2_handler(DpContainer& container, Fw::Success::T status) {
if (status == Fw::Success::SUCCESS) {
const DpTest_Data dataRecord(this->dataRecordData);
auto serializeStatus = Fw::FW_SERIALIZE_OK;
for (FwSizeType i = 0; i < CONTAINER_2_DATA_SIZE; ++i) {
serializeStatus = container.serializeRecord_DataRecord(dataRecord);
if (serializeStatus == Fw::FW_SERIALIZE_NO_ROOM_LEFT) {
break;
}
FW_ASSERT(serializeStatus == Fw::FW_SERIALIZE_OK, status);
}
// Provide an explicit time stamp
this->dpSend(container, this->sendTime);
}
}
void DpTest ::dpRecv_Container3_handler(DpContainer& container, Fw::Success::T status) {
if (status == Fw::Success::SUCCESS) {
auto serializeStatus = Fw::FW_SERIALIZE_OK;
for (FwSizeType i = 0; i < CONTAINER_3_DATA_SIZE; ++i) {
serializeStatus =
container.serializeRecord_U8ArrayRecord(this->u8ArrayRecordData.data(), this->u8ArrayRecordData.size());
if (serializeStatus == Fw::FW_SERIALIZE_NO_ROOM_LEFT) {
break;
}
FW_ASSERT(serializeStatus == Fw::FW_SERIALIZE_OK, status);
}
// Use the time stamp from the time get port
this->dpSend(container);
}
}
void DpTest ::dpRecv_Container4_handler(DpContainer& container, Fw::Success::T status) {
if (status == Fw::Success::SUCCESS) {
auto serializeStatus = Fw::FW_SERIALIZE_OK;
for (FwSizeType i = 0; i < CONTAINER_4_DATA_SIZE; ++i) {
serializeStatus = container.serializeRecord_U32ArrayRecord(this->u32ArrayRecordData.data(),
this->u32ArrayRecordData.size());
if (serializeStatus == Fw::FW_SERIALIZE_NO_ROOM_LEFT) {
break;
}
FW_ASSERT(serializeStatus == Fw::FW_SERIALIZE_OK, status);
}
// Use the time stamp from the time get port
this->dpSend(container);
}
}
void DpTest ::dpRecv_Container5_handler(DpContainer& container, Fw::Success::T status) {
if (status == Fw::Success::SUCCESS) {
auto serializeStatus = Fw::FW_SERIALIZE_OK;
for (FwSizeType i = 0; i < CONTAINER_5_DATA_SIZE; ++i) {
serializeStatus = container.serializeRecord_DataArrayRecord(this->dataArrayRecordData.data(),
this->dataArrayRecordData.size());
if (serializeStatus == Fw::FW_SERIALIZE_NO_ROOM_LEFT) {
break;
}
FW_ASSERT(serializeStatus == Fw::FW_SERIALIZE_OK, status);
}
// Use the time stamp from the time get port
this->dpSend(container);
}
}
// ----------------------------------------------------------------------
// Private helper functions
// ----------------------------------------------------------------------
void DpTest::checkContainer(const DpContainer& container, FwDpIdType localId, FwSizeType size) const {
FW_ASSERT(container.getBaseId() == this->getIdBase(), container.getBaseId(), this->getIdBase());
FW_ASSERT(container.getId() == container.getBaseId() + localId, container.getId(), container.getBaseId(),
ContainerId::Container1);
FW_ASSERT(container.getBuffer().getSize() == size, container.getBuffer().getSize(), size);
}
} // end namespace FppTest
| cpp |
fprime | data/projects/fprime/FppTest/dp/test/ut/TesterHelpers.cpp | // ======================================================================
// \title DpTest/test/ut/TesterHelpers.cpp
// \author Auto-generated
// \brief cpp file for DpTest component test harness base class
//
// NOTE: this file was automatically generated
//
// ======================================================================
#include "Tester.hpp"
namespace FppTest {
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void Tester ::connectPorts() {
// productRecvIn
this->connect_to_productRecvIn(0, this->component.get_productRecvIn_InputPort(0));
// schedIn
this->connect_to_schedIn(0, this->component.get_schedIn_InputPort(0));
// productGetOut
this->component.set_productGetOut_OutputPort(0, this->get_from_productGetOut(0));
// productRequestOut
this->component.set_productRequestOut_OutputPort(0, this->get_from_productRequestOut(0));
// productSendOut
this->component.set_productSendOut_OutputPort(0, this->get_from_productSendOut(0));
// timeGetOut
this->component.set_timeGetOut_OutputPort(0, this->get_from_timeGetOut(0));
}
void Tester ::initComponents() {
this->init();
this->component.init(Tester::TEST_INSTANCE_QUEUE_DEPTH, Tester::TEST_INSTANCE_ID);
}
} // end namespace FppTest
| cpp |
fprime | data/projects/fprime/FppTest/dp/test/ut/Tester.cpp | // ======================================================================
// \title DpTest.hpp
// \author bocchino
// \brief cpp file for DpTest test harness implementation class
// ======================================================================
#include <cstdio>
#include <cstring>
#include "FppTest/dp/test/ut/Tester.hpp"
#include "STest/Pick/Pick.hpp"
namespace FppTest {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
Tester::Tester()
: DpTestGTestBase("Tester", Tester::MAX_HISTORY_SIZE),
container1Data{},
container1Buffer(this->container1Data, sizeof this->container1Data),
container2Data{},
container2Buffer(this->container2Data, sizeof this->container2Data),
container3Data{},
container3Buffer(this->container3Data, sizeof this->container3Data),
container4Data{},
container4Buffer(this->container4Data, sizeof this->container4Data),
container5Data{},
container5Buffer(this->container5Data, sizeof this->container5Data),
component("DpTest",
STest::Pick::any(),
STest::Pick::any(),
this->u8ArrayRecordData,
this->u32ArrayRecordData,
this->dataArrayRecordData) {
this->initComponents();
this->connectPorts();
this->component.setIdBase(ID_BASE);
// Fill in arrays with random data
for (U8& elt : this->u8ArrayRecordData) {
elt = static_cast<U8>(STest::Pick::any());
}
for (U32& elt : this->u32ArrayRecordData) {
elt = static_cast<U8>(STest::Pick::any());
}
for (DpTest_Data& elt : this->dataArrayRecordData) {
elt.set(static_cast<U16>(STest::Pick::any()));
}
}
Tester::~Tester() {}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void Tester::schedIn_OK() {
this->invoke_to_schedIn(0, 0);
this->component.doDispatch();
ASSERT_PRODUCT_REQUEST_SIZE(5);
ASSERT_PRODUCT_REQUEST(0, ID_BASE + DpTest::ContainerId::Container1, FwSizeType(DpTest::CONTAINER_1_PACKET_SIZE));
ASSERT_PRODUCT_REQUEST(1, ID_BASE + DpTest::ContainerId::Container2, FwSizeType(DpTest::CONTAINER_2_PACKET_SIZE));
ASSERT_PRODUCT_REQUEST(2, ID_BASE + DpTest::ContainerId::Container3, FwSizeType(DpTest::CONTAINER_3_PACKET_SIZE));
ASSERT_PRODUCT_REQUEST(3, ID_BASE + DpTest::ContainerId::Container4, FwSizeType(DpTest::CONTAINER_4_PACKET_SIZE));
ASSERT_PRODUCT_REQUEST(4, ID_BASE + DpTest::ContainerId::Container5, FwSizeType(DpTest::CONTAINER_5_PACKET_SIZE));
ASSERT_PRODUCT_GET_SIZE(5);
ASSERT_PRODUCT_GET(0, ID_BASE + DpTest::ContainerId::Container1, FwSizeType(DpTest::CONTAINER_1_PACKET_SIZE));
ASSERT_PRODUCT_GET(1, ID_BASE + DpTest::ContainerId::Container2, FwSizeType(DpTest::CONTAINER_2_PACKET_SIZE));
ASSERT_PRODUCT_GET(2, ID_BASE + DpTest::ContainerId::Container3, FwSizeType(DpTest::CONTAINER_3_PACKET_SIZE));
ASSERT_PRODUCT_GET(3, ID_BASE + DpTest::ContainerId::Container4, FwSizeType(DpTest::CONTAINER_4_PACKET_SIZE));
ASSERT_PRODUCT_GET(4, ID_BASE + DpTest::ContainerId::Container5, FwSizeType(DpTest::CONTAINER_5_PACKET_SIZE));
}
void Tester::productRecvIn_Container1_SUCCESS() {
Fw::Buffer buffer;
FwSizeType expectedNumElts;
// Invoke the port and check the header
this->productRecvIn_InvokeAndCheckHeader(DpTest::ContainerId::Container1, sizeof(U32),
DpTest::ContainerPriority::Container1, this->container1Buffer, buffer,
expectedNumElts);
// Check the data
Fw::SerializeBufferBase& serialRepr = buffer.getSerializeRepr();
Fw::TestUtil::DpContainerHeader::checkDeserialAtOffset(serialRepr, Fw::DpContainer::DATA_OFFSET);
for (FwSizeType i = 0; i < expectedNumElts; ++i) {
FwDpIdType id;
U32 elt;
auto status = serialRepr.deserialize(id);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
const FwDpIdType expectedId = this->component.getIdBase() + DpTest::RecordId::U32Record;
ASSERT_EQ(id, expectedId);
status = serialRepr.deserialize(elt);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
ASSERT_EQ(elt, this->component.u32RecordData);
}
}
void Tester::productRecvIn_Container1_FAILURE() {
productRecvIn_CheckFailure(DpTest::ContainerId::Container1, this->container1Buffer);
}
void Tester::productRecvIn_Container2_SUCCESS() {
Fw::Buffer buffer;
FwSizeType expectedNumElts;
// Invoke the port and check the header
this->productRecvIn_InvokeAndCheckHeader(DpTest::ContainerId::Container2, DpTest_Data::SERIALIZED_SIZE,
DpTest::ContainerPriority::Container2, this->container2Buffer, buffer,
expectedNumElts);
// Check the data
Fw::SerializeBufferBase& serialRepr = buffer.getSerializeRepr();
Fw::TestUtil::DpContainerHeader::checkDeserialAtOffset(serialRepr, Fw::DpContainer::DATA_OFFSET);
for (FwSizeType i = 0; i < expectedNumElts; ++i) {
FwDpIdType id;
DpTest_Data elt;
auto status = serialRepr.deserialize(id);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
const FwDpIdType expectedId = this->component.getIdBase() + DpTest::RecordId::DataRecord;
ASSERT_EQ(id, expectedId);
status = serialRepr.deserialize(elt);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
ASSERT_EQ(elt.getu16Field(), this->component.dataRecordData);
}
}
void Tester::productRecvIn_Container2_FAILURE() {
productRecvIn_CheckFailure(DpTest::ContainerId::Container2, this->container2Buffer);
}
void Tester::productRecvIn_Container3_SUCCESS() {
Fw::Buffer buffer;
FwSizeType expectedNumElts;
const FwSizeType dataEltSize = sizeof(FwSizeStoreType) + this->u8ArrayRecordData.size();
// Invoke the port and check the header
this->productRecvIn_InvokeAndCheckHeader(DpTest::ContainerId::Container3, dataEltSize,
DpTest::ContainerPriority::Container3, this->container3Buffer, buffer,
expectedNumElts);
// Check the data
Fw::SerializeBufferBase& serialRepr = buffer.getSerializeRepr();
Fw::TestUtil::DpContainerHeader::checkDeserialAtOffset(serialRepr, Fw::DpContainer::DATA_OFFSET);
for (FwSizeType i = 0; i < expectedNumElts; ++i) {
FwDpIdType id;
auto status = serialRepr.deserialize(id);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
const FwDpIdType expectedId = this->component.getIdBase() + DpTest::RecordId::U8ArrayRecord;
ASSERT_EQ(id, expectedId);
FwSizeType size;
status = serialRepr.deserializeSize(size);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
ASSERT_EQ(size, this->u8ArrayRecordData.size());
const U8* const buffAddr = serialRepr.getBuffAddr();
for (FwSizeType j = 0; j < size; ++j) {
U8 byte;
status = serialRepr.deserialize(byte);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
ASSERT_EQ(byte, this->u8ArrayRecordData.at(j));
}
}
}
void Tester::productRecvIn_Container3_FAILURE() {
productRecvIn_CheckFailure(DpTest::ContainerId::Container3, this->container3Buffer);
}
void Tester::productRecvIn_Container4_SUCCESS() {
Fw::Buffer buffer;
FwSizeType expectedNumElts;
const FwSizeType dataEltSize = sizeof(FwSizeStoreType) + this->u32ArrayRecordData.size() * sizeof(U32);
// Invoke the port and check the header
this->productRecvIn_InvokeAndCheckHeader(DpTest::ContainerId::Container4, dataEltSize,
DpTest::ContainerPriority::Container4, this->container4Buffer, buffer,
expectedNumElts);
// Check the data
Fw::SerializeBufferBase& serialRepr = buffer.getSerializeRepr();
Fw::TestUtil::DpContainerHeader::checkDeserialAtOffset(serialRepr, Fw::DpContainer::DATA_OFFSET);
for (FwSizeType i = 0; i < expectedNumElts; ++i) {
FwDpIdType id;
auto status = serialRepr.deserialize(id);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
const FwDpIdType expectedId = this->component.getIdBase() + DpTest::RecordId::U32ArrayRecord;
ASSERT_EQ(id, expectedId);
FwSizeType size;
status = serialRepr.deserializeSize(size);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
ASSERT_EQ(size, this->u32ArrayRecordData.size());
const U8* const buffAddr = serialRepr.getBuffAddr();
for (FwSizeType j = 0; j < size; ++j) {
U32 elt;
status = serialRepr.deserialize(elt);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
ASSERT_EQ(elt, this->u32ArrayRecordData.at(j));
}
}
}
void Tester::productRecvIn_Container4_FAILURE() {
productRecvIn_CheckFailure(DpTest::ContainerId::Container4, this->container4Buffer);
}
void Tester::productRecvIn_Container5_SUCCESS() {
Fw::Buffer buffer;
FwSizeType expectedNumElts;
const FwSizeType dataEltSize = sizeof(FwSizeStoreType) + this->dataArrayRecordData.size() * DpTest_Data::SERIALIZED_SIZE;
// Invoke the port and check the header
this->productRecvIn_InvokeAndCheckHeader(DpTest::ContainerId::Container5, dataEltSize,
DpTest::ContainerPriority::Container5, this->container5Buffer, buffer,
expectedNumElts);
// Check the data
Fw::SerializeBufferBase& serialRepr = buffer.getSerializeRepr();
Fw::TestUtil::DpContainerHeader::checkDeserialAtOffset(serialRepr, Fw::DpContainer::DATA_OFFSET);
for (FwSizeType i = 0; i < expectedNumElts; ++i) {
FwDpIdType id;
auto status = serialRepr.deserialize(id);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
const FwDpIdType expectedId = this->component.getIdBase() + DpTest::RecordId::DataArrayRecord;
ASSERT_EQ(id, expectedId);
FwSizeType size;
status = serialRepr.deserializeSize(size);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
ASSERT_EQ(size, this->dataArrayRecordData.size());
const U8* const buffAddr = serialRepr.getBuffAddr();
for (FwSizeType j = 0; j < size; ++j) {
DpTest_Data elt;
status = serialRepr.deserialize(elt);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
ASSERT_EQ(elt, this->dataArrayRecordData.at(j));
}
}
}
void Tester::productRecvIn_Container5_FAILURE() {
productRecvIn_CheckFailure(DpTest::ContainerId::Container5, this->container5Buffer);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
Fw::Time Tester::randomizeTestTime() {
const U32 seconds = STest::Pick::any();
const U32 useconds = STest::Pick::startLength(0, 1000000);
const Fw::Time time(seconds, useconds);
this->setTestTime(time);
this->component.setSendTime(time);
return time;
}
void Tester::productRecvIn_InvokeAndCheckHeader(FwDpIdType id,
FwSizeType dataEltSize,
FwDpPriorityType priority,
Fw::Buffer inputBuffer,
Fw::Buffer& outputBuffer,
FwSizeType& expectedNumElts) {
const auto globalId = ID_BASE + id;
// Set the test time
const Fw::Time timeTag = this->randomizeTestTime();
// Invoke the productRecvIn port
this->sendProductResponse(globalId, inputBuffer, Fw::Success::SUCCESS);
this->component.doDispatch();
// Check the port history size
ASSERT_PRODUCT_SEND_SIZE(1);
// Compute the expected data size
const auto& entry = this->productSendHistory->at(0);
const auto bufferSize = entry.buffer.getSize();
FW_ASSERT(bufferSize >= Fw::DpContainer::MIN_PACKET_SIZE);
const auto dataCapacity = bufferSize - Fw::DpContainer::MIN_PACKET_SIZE;
const auto eltSize = sizeof(FwDpIdType) + dataEltSize;
expectedNumElts = dataCapacity / eltSize;
const auto expectedDataSize = expectedNumElts * eltSize;
// DP state should be the default value
Fw::DpState dpState;
// Set up the expected user data
Fw::DpContainer::Header::UserData userData;
memset(&userData[0], 0, sizeof userData);
// Check the history entry
// This sets the output buffer and sets the deserialization pointer
// to the start of the data payload
ASSERT_PRODUCT_SEND(0, globalId, priority, timeTag, 0, userData, dpState, expectedDataSize, outputBuffer);
}
void Tester::productRecvIn_CheckFailure(FwDpIdType id, Fw::Buffer buffer) {
// Invoke the port
const auto globalId = ID_BASE + id;
this->sendProductResponse(globalId, buffer, Fw::Success::FAILURE);
this->component.doDispatch();
// Check the port history size
ASSERT_PRODUCT_SEND_SIZE(0);
}
// ----------------------------------------------------------------------
// Handlers for typed from ports
// ----------------------------------------------------------------------
Fw::Success::T Tester::productGet_handler(FwDpIdType id, FwSizeType size, Fw::Buffer& buffer) {
this->pushProductGetEntry(id, size);
Fw::Success status = Fw::Success::FAILURE;
FW_ASSERT(id >= ID_BASE, id, ID_BASE);
const FwDpIdType localId = id - ID_BASE;
switch (localId) {
case DpTest::ContainerId::Container1:
FW_ASSERT(size == DpTest::CONTAINER_1_PACKET_SIZE);
buffer = this->container1Buffer;
status = Fw::Success::SUCCESS;
break;
case DpTest::ContainerId::Container2:
FW_ASSERT(size == DpTest::CONTAINER_2_PACKET_SIZE);
buffer = this->container2Buffer;
status = Fw::Success::SUCCESS;
break;
case DpTest::ContainerId::Container3:
// Make this one fail for testing purposes
break;
case DpTest::ContainerId::Container4:
FW_ASSERT(size == DpTest::CONTAINER_4_PACKET_SIZE);
buffer = this->container4Buffer;
status = Fw::Success::SUCCESS;
break;
case DpTest::ContainerId::Container5:
FW_ASSERT(size == DpTest::CONTAINER_5_PACKET_SIZE);
buffer = this->container5Buffer;
status = Fw::Success::SUCCESS;
break;
default:
break;
}
return status;
}
} // end namespace FppTest
| cpp |
fprime | data/projects/fprime/FppTest/dp/test/ut/Tester.hpp | // ======================================================================
// \title DpTest/test/ut/Tester.hpp
// \author bocchino
// \brief hpp file for DpTest test harness implementation class
// ======================================================================
#ifndef FppTest_DpTest_Tester_HPP
#define FppTest_DpTest_Tester_HPP
#include "DpTestGTestBase.hpp"
#include "FppTest/dp/DpTest.hpp"
#include "Fw/Dp/test/util/DpContainerHeader.hpp"
#include "STest/Pick/Pick.hpp"
namespace FppTest {
class Tester : public DpTestGTestBase {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
public:
// Maximum size of histories storing events, telemetry, and port outputs
static constexpr FwSizeType MAX_HISTORY_SIZE = 10;
// Instance ID supplied to the component instance under test
static constexpr FwSizeType TEST_INSTANCE_ID = 0;
// Queue depth supplied to component instance under test
static constexpr FwSizeType TEST_INSTANCE_QUEUE_DEPTH = 10;
// The component id base
static constexpr FwDpIdType ID_BASE = 100;
//! Construct object Tester
//!
Tester();
//! Destroy object Tester
//!
~Tester();
public:
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
//! schedIn OK
void schedIn_OK();
//! productRecvIn with Container 1 (SUCCESS)
void productRecvIn_Container1_SUCCESS();
//! productRecvIn with Container 1 (FAILURE)
void productRecvIn_Container1_FAILURE();
//! productRecvIn with Container 2 (SUCCESS)
void productRecvIn_Container2_SUCCESS();
//! productRecvIn with Container 2 (FAILURE)
void productRecvIn_Container2_FAILURE();
//! productRecvIn with Container 3 (SUCCESS)
void productRecvIn_Container3_SUCCESS();
//! productRecvIn with Container 3 (FAILURE)
void productRecvIn_Container3_FAILURE();
//! productRecvIn with Container 4 (SUCCESS)
void productRecvIn_Container4_SUCCESS();
//! productRecvIn with Container 4 (FAILURE)
void productRecvIn_Container4_FAILURE();
//! productRecvIn with Container 5 (SUCCESS)
void productRecvIn_Container5_SUCCESS();
//! productRecvIn with Container 5 (FAILURE)
void productRecvIn_Container5_FAILURE();
PRIVATE:
// ----------------------------------------------------------------------
// Handlers for data product ports
// ----------------------------------------------------------------------
Fw::Success::T productGet_handler(FwDpIdType id, //!< The container ID
FwSizeType size, //!< The size of the requested buffer
Fw::Buffer& buffer //!< The buffer
) override;
PRIVATE:
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
//! Connect ports
//!
void connectPorts();
//! Initialize components
//!
void initComponents();
//! Set and return a random time
//! \return The time
Fw::Time randomizeTestTime();
//! Invoke productRecvIn and check header
//! This sets the output buffer to the received buffer and sets the
//! deserialization pointer to the start of the data payload
void productRecvIn_InvokeAndCheckHeader(FwDpIdType id, //!< The container id
FwSizeType dataEltSize, //!< The data element size
FwDpPriorityType priority, //!< The priority
Fw::Buffer inputBuffer, //!< The buffer to send
Fw::Buffer& outputBuffer, //!< The buffer received (output)
FwSizeType& expectedNumElts //!< The expected number of elements (output)
);
//! Check received buffer with failure status
void productRecvIn_CheckFailure(FwDpIdType id, //!< The container id
Fw::Buffer buffer //!< The buffer
);
PRIVATE:
// ----------------------------------------------------------------------
// Variables
// ----------------------------------------------------------------------
//! Buffer data for Container 1
U8 container1Data[DpTest::CONTAINER_1_PACKET_SIZE];
//! Buffer for Container 1
const Fw::Buffer container1Buffer;
//! Buffer data for Container 2
U8 container2Data[DpTest::CONTAINER_2_PACKET_SIZE];
//! Buffer for Container 2
const Fw::Buffer container2Buffer;
//! Buffer data for Container 3
U8 container3Data[DpTest::CONTAINER_3_PACKET_SIZE];
//! Buffer for Container 3
const Fw::Buffer container3Buffer;
//! Buffer data for Container 4
U8 container4Data[DpTest::CONTAINER_4_PACKET_SIZE];
//! Buffer for Container 4
const Fw::Buffer container4Buffer;
//! Buffer data for Container 5
U8 container5Data[DpTest::CONTAINER_5_PACKET_SIZE];
//! Buffer for Container 5
const Fw::Buffer container5Buffer;
//! Data for U8 array record
DpTest::U8ArrayRecordData u8ArrayRecordData;
//! Data for U32 array record
DpTest::U32ArrayRecordData u32ArrayRecordData;
//! Data for Data array record
DpTest::DataArrayRecordData dataArrayRecordData;
//! The component under test
DpTest component;
};
} // end namespace FppTest
#endif
| hpp |
fprime | data/projects/fprime/FppTest/dp/test/ut/TestMain.cpp | // ----------------------------------------------------------------------
// TestMain.cpp
// ----------------------------------------------------------------------
#include "FppTest/dp/test/ut/Tester.hpp"
#include "Fw/Test/UnitTest.hpp"
#include "STest/Random/Random.hpp"
using namespace FppTest;
TEST(schedIn, OK) {
COMMENT("schedIn OK");
Tester tester;
tester.schedIn_OK();
}
TEST(productRecvIn, Container1_SUCCESS) {
COMMENT("Receive Container1 SUCCESS");
Tester tester;
tester.productRecvIn_Container1_SUCCESS();
}
TEST(productRecvIn, Container1_FAILURE) {
COMMENT("Receive Container1 FAILURE");
Tester tester;
tester.productRecvIn_Container1_FAILURE();
}
TEST(productRecvIn, Container2_SUCCESS) {
COMMENT("Receive Container2 SUCCESS");
Tester tester;
tester.productRecvIn_Container2_SUCCESS();
}
TEST(productRecvIn, Container2_FAILURE) {
COMMENT("Receive Container2 FAILURE");
Tester tester;
tester.productRecvIn_Container2_FAILURE();
}
TEST(productRecvIn, Container3_SUCCESS) {
COMMENT("Receive Container3 SUCCESS");
Tester tester;
tester.productRecvIn_Container3_SUCCESS();
}
TEST(productRecvIn, Container3_FAILURE) {
COMMENT("Receive Container3 FAILURE");
Tester tester;
tester.productRecvIn_Container3_FAILURE();
}
TEST(productRecvIn, Container4_SUCCESS) {
COMMENT("Receive Container4 SUCCESS");
Tester tester;
tester.productRecvIn_Container4_SUCCESS();
}
TEST(productRecvIn, Container4_FAILURE) {
COMMENT("Receive Container4 FAILURE");
Tester tester;
tester.productRecvIn_Container4_FAILURE();
}
TEST(productRecvIn, Container5_SUCCESS) {
COMMENT("Receive Container5 SUCCESS");
Tester tester;
tester.productRecvIn_Container5_SUCCESS();
}
TEST(productRecvIn, Container5_FAILURE) {
COMMENT("Receive Container5 FAILURE");
Tester tester;
tester.productRecvIn_Container5_FAILURE();
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
STest::Random::seed();
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/FppTest/struct/main.cpp | // ======================================================================
// \title main.cpp
// \author T. Chieu
// \brief main cpp file for FPP struct tests
//
// \copyright
// Copyright (C) 2009-2022 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FppTest/struct/NonPrimitiveSerializableAc.hpp"
#include "FppTest/struct/MultiStringSerializableAc.hpp"
#include "FppTest/typed_tests/StringTest.hpp"
#include "STest/Random/Random.hpp"
#include "gtest/gtest.h"
// Instantiate string tests for structs
using StringTestImplementations = ::testing::Types<
NonPrimitive::StringSize80,
MultiString::StringSize50,
MultiString::StringSize60,
MultiString::StringSize80
>;
INSTANTIATE_TYPED_TEST_SUITE_P(Struct, StringTest, StringTestImplementations);
template<>
U32 FppTest::String::getSize<MultiString::StringSize50>() {
return 50;
}
template<>
U32 FppTest::String::getSize<MultiString::StringSize60>() {
return 60;
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
STest::Random::seed();
return RUN_ALL_TESTS();
}
| cpp |
fprime | data/projects/fprime/FppTest/struct/PrimitiveStructTest.cpp | // ======================================================================
// \title PrimitiveStructTest.cpp
// \author T. Chieu
// \brief cpp file for PrimitiveStructTest class
//
// \copyright
// Copyright (C) 2009-2022 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FppTest/struct/PrimitiveSerializableAc.hpp"
#include "FppTest/utils/Utils.hpp"
#include "Fw/Types/SerialBuffer.hpp"
#include "Fw/Types/StringUtils.hpp"
#include "STest/Pick/Pick.hpp"
#include "gtest/gtest.h"
#include <sstream>
// Test Primitive struct class
class PrimitiveStructTest : public ::testing::Test {
protected:
void SetUp() override {
testBool = true;
testU32 = FppTest::Utils::getNonzeroU32();
testI16 = static_cast<I16>(FppTest::Utils::getNonzeroU32());
testF64 = static_cast<F64>(FppTest::Utils::getNonzeroU32());
}
void assertStructMembers(const Primitive& s) {
ASSERT_EQ(s.getmBool(), testBool);
ASSERT_EQ(s.getmU32(), testU32);
ASSERT_EQ(s.getmI16(), testI16);
ASSERT_EQ(s.getmF64(), testF64);
}
void assertUnsuccessfulSerialization(Primitive& s, U32 bufSize) {
// Avoid creating an array of size zero
U8 data[bufSize + 1];
Fw::SerialBuffer buf(data, bufSize);
Fw::SerializeStatus status;
// Serialize
status = buf.serialize(s);
ASSERT_NE(status, Fw::FW_SERIALIZE_OK);
// Deserialize
status = buf.deserialize(s);
ASSERT_NE(status, Fw::FW_SERIALIZE_OK);
}
bool testBool;
U32 testU32;
I16 testI16;
F64 testF64;
};
// Test struct constants and default constructor
TEST_F(PrimitiveStructTest, Default) {
Primitive s;
// Constants
ASSERT_EQ(
Primitive::SERIALIZED_SIZE,
sizeof(U8)
+ sizeof(U32)
+ sizeof(I16)
+ sizeof(F64)
);
// Default constructor
ASSERT_EQ(s.getmBool(), false);
ASSERT_EQ(s.getmU32(), 0);
ASSERT_EQ(s.getmI16(), 0);
ASSERT_EQ(s.getmF64(), 0.0);
}
// Test struct constructors
TEST_F(PrimitiveStructTest, Constructors) {
// Member constructor
Primitive s1(testBool, testU32, testI16, testF64);
assertStructMembers(s1);
// Copy constructor
Primitive s2(s1);
assertStructMembers(s2);
}
// Test struct assignment operator
TEST_F(PrimitiveStructTest, AssignmentOp) {
Primitive s1;
Primitive s2(testBool, testU32, testI16, testF64);
// Copy assignment
s1 = s2;
assertStructMembers(s1);
Primitive& s1Ref = s1;
s1 = s1Ref;
ASSERT_EQ(&s1, &s1Ref);
}
// Test struct equality and inequality operators
TEST_F(PrimitiveStructTest, EqualityOp) {
Primitive s1, s2;
ASSERT_TRUE(s1 == s2);
ASSERT_FALSE(s1 != s2);
s1.setmBool(testBool);
ASSERT_FALSE(s1 == s2);
ASSERT_TRUE(s1 != s2);
s2.setmBool(testBool);
s1.setmU32(testU32);
ASSERT_FALSE(s1 == s2);
ASSERT_TRUE(s1 != s2);
s2.setmU32(testU32);
s1.setmI16(testI16);
ASSERT_FALSE(s1 == s2);
ASSERT_TRUE(s1 != s2);
s2.setmI16(testI16);
s1.setmF64(testF64);
ASSERT_FALSE(s1 == s2);
ASSERT_TRUE(s1 != s2);
s2.setmF64(testF64);
ASSERT_TRUE(s1 == s2);
ASSERT_FALSE(s1 != s2);
}
// Test struct getter and setter functions
TEST_F(PrimitiveStructTest, GetterSetterFunctions) {
Primitive s1, s2;
// Set all members
s1.set(testBool, testU32, testI16, testF64);
assertStructMembers(s1);
// Set individual members
s2.setmBool(testBool);
ASSERT_EQ(s2.getmBool(), testBool);
s2.setmU32(testU32);
ASSERT_EQ(s2.getmU32(), testU32);
s2.setmI16(testI16);
ASSERT_EQ(s2.getmI16(), testI16);
s2.setmF64(testF64);
ASSERT_EQ(s2.getmF64(), testF64);
}
// Test struct serialization and deserialization
TEST_F(PrimitiveStructTest, Serialization) {
Primitive s(testBool, testU32, testI16, testF64);
Primitive sCopy;
Fw::SerializeStatus status;
// Test successful serialization
U8 data[Primitive::SERIALIZED_SIZE];
Fw::SerialBuffer buf(data, sizeof(data));
// Serialize
status = buf.serialize(s);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
ASSERT_EQ(buf.getBuffLength(), Primitive::SERIALIZED_SIZE);
// Deserialize
status = buf.deserialize(sCopy);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
ASSERT_EQ(s, sCopy);
// Test unsuccessful serialization
assertUnsuccessfulSerialization(s, sizeof(U8) - 1);
assertUnsuccessfulSerialization(s, sizeof(U8) + sizeof(U32) - 1);
assertUnsuccessfulSerialization(s, sizeof(U8) + sizeof(U32)
+ sizeof(I16) - 1);
assertUnsuccessfulSerialization(s, Primitive::SERIALIZED_SIZE - 1);
}
// Test struct toString() and ostream operator functions
TEST_F(PrimitiveStructTest, ToString) {
Primitive s(testBool, testU32, testI16, testF64);
std::stringstream buf1, buf2;
buf1 << s;
buf2 << "( "
<< "mBool = " << testBool << ", "
<< "mU32 = " << testU32 << ", "
<< "mI16 = " << testI16 << ", "
<< "mF64 = " << std::fixed << testF64
<< " )";
// Truncate string output
char buf2Str[FW_SERIALIZABLE_TO_STRING_BUFFER_SIZE];
Fw::StringUtils::string_copy(buf2Str, buf2.str().c_str(),
FW_SERIALIZABLE_TO_STRING_BUFFER_SIZE);
ASSERT_STREQ(buf1.str().c_str(), buf2Str);
}
| cpp |
fprime | data/projects/fprime/FppTest/struct/NonPrimitiveStructTest.cpp | // ======================================================================
// \title NonPrimitiveStructTest.cpp
// \author T. Chieu
// \brief cpp file for NonPrimitiveStructTest class
//
// \copyright
// Copyright (C) 2009-2022 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FppTest/struct/NonPrimitiveSerializableAc.hpp"
#include "FppTest/utils/Utils.hpp"
#include "Fw/Types/SerialBuffer.hpp"
#include "Fw/Types/StringUtils.hpp"
#include "STest/Pick/Pick.hpp"
#include "gtest/gtest.h"
#include <sstream>
// Test NonPrimitive struct class
class NonPrimitiveStructTest : public ::testing::Test {
protected:
void SetUp() override {
char buf[testString.getCapacity()];
// Test string must be non-empty
FppTest::Utils::setString(buf, sizeof(buf), 1);
testString = buf;
testEnum = static_cast<StructEnum::T>(STest::Pick::startLength(
StructEnum::A,
StructEnum::B
));
for (U32 i = 0; i < StructArray::SIZE; i++) {
testArray[i] = FppTest::Utils::getNonzeroU32();
}
testStruct.set(
true,
FppTest::Utils::getNonzeroU32(),
static_cast<I16>(FppTest::Utils::getNonzeroU32()),
static_cast<F64>(FppTest::Utils::getNonzeroU32())
);
for (U32 i = 0; i < 3; i++) {
testU32Arr[0] = FppTest::Utils::getNonzeroU32();
}
for (U32 i = 0; i < 3; i++) {
testStructArr[i].set(
true,
FppTest::Utils::getNonzeroU32(),
static_cast<I16>(FppTest::Utils::getNonzeroU32()),
static_cast<F64>(FppTest::Utils::getNonzeroU32())
);
}
}
void assertStructMembers(const NonPrimitive& s) {
ASSERT_EQ(s.getmString(), testString);
ASSERT_EQ(s.getmEnum(), testEnum);
ASSERT_EQ(s.getmArray(), testArray);
ASSERT_EQ(s.getmStruct(), testStruct);
for (U32 i = 0; i < 3; i++) {
ASSERT_EQ(s.getmU32Arr()[i], testU32Arr[i]);
}
for (U32 i = 0; i < 3; i++) {
ASSERT_EQ(s.getmStructArr()[i], testStructArr[i]);
}
}
void assertUnsuccessfulSerialization(NonPrimitive& s, U32 bufSize) {
U8 data[bufSize];
Fw::SerialBuffer buf(data, sizeof(data));
Fw::SerializeStatus status;
// Serialize
status = buf.serialize(s);
ASSERT_NE(status, Fw::FW_SERIALIZE_OK);
// Deserialize
status = buf.deserialize(s);
ASSERT_NE(status, Fw::FW_SERIALIZE_OK);
}
NonPrimitive::StringSize80 testString;
StructEnum testEnum;
StructArray testArray;
Primitive testStruct;
U32 testU32Arr[3];
Primitive testStructArr[3];
};
// Test struct constants and default constructor
TEST_F(NonPrimitiveStructTest, Default) {
NonPrimitive s;
StructArray defaultArray;
Primitive defaultStruct1(true, 0, 0, 3.14);
Primitive defaultStruct2(true, 0, 0, 1.16);
// Constants
ASSERT_EQ(
NonPrimitive::SERIALIZED_SIZE,
NonPrimitive::StringSize80::SERIALIZED_SIZE
+ StructEnum::SERIALIZED_SIZE
+ StructArray::SERIALIZED_SIZE
+ Primitive::SERIALIZED_SIZE
+ (3 * sizeof(U32))
+ (3 * Primitive::SERIALIZED_SIZE)
);
// Default constructor
ASSERT_EQ(s.getmString(), "");
ASSERT_EQ(s.getmEnum(), StructEnum::C);
ASSERT_EQ(s.getmArray(), defaultArray);
ASSERT_EQ(s.getmStruct(), defaultStruct1);
for (U32 i = 0; i < 3; i++) {
ASSERT_EQ(s.getmU32Arr()[i], 0);
}
for (U32 i = 0; i < 3; i++) {
ASSERT_EQ(s.getmStructArr()[i], defaultStruct2);
}
}
// Test struct constructors
TEST_F(NonPrimitiveStructTest, Constructors) {
// Member constructor
NonPrimitive s1(testString, testEnum, testArray,
testStruct, testU32Arr, testStructArr);
assertStructMembers(s1);
// Scalar member constructor
NonPrimitive s2(testString, testEnum, testArray,
testStruct, testU32Arr[0], testStructArr[0]);
ASSERT_EQ(s2.getmString(), testString);
ASSERT_EQ(s2.getmEnum(), testEnum);
ASSERT_EQ(s2.getmArray(), testArray);
ASSERT_EQ(s2.getmStruct(), testStruct);
for (U32 i = 0; i < 3; i++) {
ASSERT_EQ(s2.getmU32Arr()[i], testU32Arr[0]);
}
for (U32 i = 0; i < 3; i++) {
ASSERT_EQ(s2.getmStructArr()[i], testStructArr[0]);
}
// Copy constructor
NonPrimitive s3(s1);
assertStructMembers(s3);
}
// Test struct assignment operator
TEST_F(NonPrimitiveStructTest, AssignmentOp) {
NonPrimitive s1;
NonPrimitive s2(testString, testEnum, testArray,
testStruct, testU32Arr, testStructArr);
// Copy assignment
s1 = s2;
assertStructMembers(s1);
NonPrimitive& s1Ref = s1;
s1 = s1Ref;
ASSERT_EQ(&s1, &s1Ref);
}
// Test struct equality and inequality operators
TEST_F(NonPrimitiveStructTest, EqualityOp) {
NonPrimitive s1, s2;
ASSERT_TRUE(s1 == s2);
ASSERT_FALSE(s1 != s2);
s1.setmString(testString);
ASSERT_FALSE(s1 == s2);
ASSERT_TRUE(s1 != s2);
s2.setmString(testString);
s1.setmEnum(testEnum);
ASSERT_NE(s1, s2);
ASSERT_FALSE(s1 == s2);
ASSERT_TRUE(s1 != s2);
s2.setmEnum(testEnum);
s1.setmArray(testArray);
ASSERT_FALSE(s1 == s2);
ASSERT_TRUE(s1 != s2);
s2.setmArray(testArray);
s1.setmStruct(testStruct);
ASSERT_FALSE(s1 == s2);
ASSERT_TRUE(s1 != s2);
s2.setmStruct(testStruct);
s1.setmU32Arr(testU32Arr);
ASSERT_FALSE(s1 == s2);
ASSERT_TRUE(s1 != s2);
s2.setmU32Arr(testU32Arr);
s1.setmStructArr(testStructArr);
ASSERT_FALSE(s1 == s2);
ASSERT_TRUE(s1 != s2);
s2.setmStructArr(testStructArr);
ASSERT_TRUE(s1 == s2);
ASSERT_FALSE(s1 != s2);
}
// Test struct getter and setter functions
TEST_F(NonPrimitiveStructTest, GetterSetterFunctions) {
NonPrimitive s1, s2;
// Set all members
s1.set(testString, testEnum, testArray,
testStruct, testU32Arr, testStructArr);
assertStructMembers(s1);
// Set individual members
s2.setmString(testString);
ASSERT_EQ(s2.getmString(), testString);
s2.setmEnum(testEnum);
ASSERT_EQ(s2.getmEnum(), testEnum);
s2.setmArray(testArray);
ASSERT_EQ(s2.getmArray(), testArray);
s2.setmStruct(testStruct);
ASSERT_EQ(s2.getmStruct(), testStruct);
s2.setmU32Arr(testU32Arr);
for (U32 i = 0; i < 3; i++) {
ASSERT_EQ(s2.getmU32Arr()[i], testU32Arr[i]);
}
s2.setmStructArr(testStructArr);
for (U32 i = 0; i < 3; i++) {
ASSERT_EQ(s2.getmStructArr()[i], testStructArr[i]);
}
// Check non-const getter
s2.getmStruct().setmU32(testU32Arr[0]);
ASSERT_EQ(s2.getmStruct().getmU32(), testU32Arr[0]);
}
// Test struct serialization and deserialization
TEST_F(NonPrimitiveStructTest, Serialization) {
NonPrimitive s(testString, testEnum, testArray,
testStruct, testU32Arr, testStructArr);
NonPrimitive sCopy;
U32 stringSerializedSize = testString.length() + sizeof(FwBuffSizeType);
U32 serializedSize = NonPrimitive::SERIALIZED_SIZE
- NonPrimitive::StringSize80::SERIALIZED_SIZE
+ stringSerializedSize;
Fw::SerializeStatus status;
// Test successful serialization
U8 data[NonPrimitive::SERIALIZED_SIZE];
Fw::SerialBuffer buf(data, sizeof(data));
// Serialize
status = buf.serialize(s);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
ASSERT_EQ(buf.getBuffLength(), serializedSize);
// Deserialize
status = buf.deserialize(sCopy);
ASSERT_EQ(status, Fw::FW_SERIALIZE_OK);
ASSERT_EQ(s, sCopy);
// Test unsuccessful serialization
assertUnsuccessfulSerialization(s, stringSerializedSize - 1);
assertUnsuccessfulSerialization(s, stringSerializedSize
+ StructEnum::SERIALIZED_SIZE - 1);
assertUnsuccessfulSerialization(s, stringSerializedSize
+ StructEnum::SERIALIZED_SIZE + StructArray::SERIALIZED_SIZE - 1);
assertUnsuccessfulSerialization(s, stringSerializedSize
+ StructEnum::SERIALIZED_SIZE + StructArray::SERIALIZED_SIZE
+ Primitive::SERIALIZED_SIZE - 1);
assertUnsuccessfulSerialization(s, stringSerializedSize
+ StructEnum::SERIALIZED_SIZE + StructArray::SERIALIZED_SIZE
+ Primitive::SERIALIZED_SIZE + (3 * sizeof(U32)) - 1);
assertUnsuccessfulSerialization(s, serializedSize - 1);
}
// Test struct toString() and ostream operator functions
TEST_F(NonPrimitiveStructTest, ToString) {
NonPrimitive s(testString, testEnum, testArray,
testStruct, testU32Arr, testStructArr);
std::stringstream buf1, buf2;
buf1 << s;
buf2 << "( "
<< "mString = " << testString << ", "
<< "mEnum = " << testEnum << ", "
<< "mArray = " << testArray << ", "
<< "mStruct = " << testStruct << ", "
<< "mU32Arr = [ "
<< testU32Arr[0] << ", "
<< testU32Arr[1] << ", "
<< testU32Arr[2] << " ], "
<< "mStructArr = [ "
<< testStructArr[0] << ", "
<< testStructArr[1] << ", "
<< testStructArr[2] << " ] "
<< " )";
// Truncate string output
char buf2Str[FW_SERIALIZABLE_TO_STRING_BUFFER_SIZE];
Fw::StringUtils::string_copy(buf2Str, buf2.str().c_str(),
FW_SERIALIZABLE_TO_STRING_BUFFER_SIZE);
ASSERT_STREQ(buf1.str().c_str(), buf2Str);
}
| cpp |
fprime | data/projects/fprime/FppTest/enum/main.cpp | // ======================================================================
// \title main.cpp
// \author T. Chieu
// \brief main cpp file for FPP enum tests
//
// \copyright
// Copyright (C) 2009-2022 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "FppTest/enum/ImplicitEnumAc.hpp"
#include "FppTest/enum/ExplicitEnumAc.hpp"
#include "FppTest/enum/DefaultEnumAc.hpp"
#include "FppTest/enum/IntervalEnumAc.hpp"
#include "FppTest/enum/SerializeTypeU8EnumAc.hpp"
#include "FppTest/enum/SerializeTypeU64EnumAc.hpp"
#include "FppTest/typed_tests/EnumTest.hpp"
#include "STest/Random/Random.hpp"
#include "gtest/gtest.h"
// Instantiate enum tests
using EnumTestImplementations = ::testing::Types<
Implicit,
Explicit,
Default,
Interval,
SerializeTypeU8,
SerializeTypeU64
>;
INSTANTIATE_TYPED_TEST_SUITE_P(FppTest,
EnumTest,
EnumTestImplementations);
// Specializations for default value
template<>
Explicit::T FppTest::Enum::getDefaultValue<Explicit>() {
return Explicit::A;
}
template<>
Default::T FppTest::Enum::getDefaultValue<Default>() {
return Default::C;
}
// Specializations for valid value
template<>
Explicit::T FppTest::Enum::getValidValue<Explicit>() {
U32 val = STest::Pick::startLength(0, Explicit::NUM_CONSTANTS);
switch (val) {
case 0: return Explicit::A;
case 1: return Explicit::B;
default: return Explicit::C;
}
}
template<>
Interval::T FppTest::Enum::getValidValue<Interval>() {
U32 val = STest::Pick::startLength(0, Interval::NUM_CONSTANTS);
switch (val) {
case 0: return Interval::A;
case 1: return Interval::B;
case 2: return Interval::C;
case 3: return Interval::D;
case 4: return Interval::E;
case 5: return Interval::F;
default: return Interval::G;
}
}
// Specializations for invalid value
template <>
Explicit::T FppTest::Enum::getInvalidValue<Explicit>() {
U32 sign = STest::Pick::lowerUpper(0, 1);
switch (sign) {
case 0:
return static_cast<Explicit::T>(STest::Pick::lowerUpper(
Explicit::C + 1,
std::numeric_limits<Explicit::SerialType>::max()
));
default:
return static_cast<Explicit::T>(STest::Pick::lowerUpper(
(Explicit::A - 1) * (-1),
std::numeric_limits<Explicit::SerialType>::max()
) * (-1));
}
}
template<>
Interval::T FppTest::Enum::getInvalidValue<Interval>() {
return static_cast<Interval::T>(STest::Pick::lowerUpper(
Interval::G + 1,
std::numeric_limits<Interval::SerialType>::max()
));
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
STest::Random::seed();
return RUN_ALL_TESTS();
}
| cpp |