Merge branch 'master' of gitee.com:gityangyi/print_print_fwk

This commit is contained in:
杨抑 2024-11-21 19:26:42 +08:00
commit d122ac4970
31 changed files with 5116 additions and 89 deletions

View File

@ -78,6 +78,7 @@ public:
static size_t GetJsVal(napi_env env, napi_callback_info info, napi_value argv[], size_t length); static size_t GetJsVal(napi_env env, napi_callback_info info, napi_value argv[], size_t length);
static bool VerifyProperty(std::vector<std::string> &names, std::map<std::string, PrintParamStatus> &propertyList); static bool VerifyProperty(std::vector<std::string> &names, std::map<std::string, PrintParamStatus> &propertyList);
static std::string GetPrintErrorMsg(int32_t errorCode);
}; };
} // namespace OHOS::Print } // namespace OHOS::Print
#endif // NAPI_PRINT_UTILS_H #endif // NAPI_PRINT_UTILS_H

View File

@ -346,4 +346,13 @@ bool NapiPrintUtils::VerifyProperty(
} }
return true; return true;
} }
std::string NapiPrintUtils::GetPrintErrorMsg(int32_t errorCode)
{
auto msg = PRINT_ERROR_MSG_MAP.find(static_cast<PrintErrorCode>(errorCode));
if (msg != PRINT_ERROR_MSG_MAP.end()) {
return msg->second;
}
return "";
}
} // namespace OHOS::Print } // namespace OHOS::Print

View File

@ -44,7 +44,8 @@ int32_t PrintCallbackStub::OnRemoteRequest(
if (itFunc != cmdMap_.end()) { if (itFunc != cmdMap_.end()) {
auto requestFunc = itFunc->second; auto requestFunc = itFunc->second;
if (requestFunc != nullptr) { if (requestFunc != nullptr) {
return static_cast<int32_t>((this->*requestFunc)(data, reply)); bool result = (this->*requestFunc)(data, reply);
return result ? E_PRINT_NONE : E_PRINT_SERVER_FAILURE;
} }
} }
PRINT_HILOGW("default case, need check."); PRINT_HILOGW("default case, need check.");

View File

@ -43,7 +43,8 @@ int32_t PrintExtensionCallbackStub::OnRemoteRequest(
if (itFunc != cmdMap_.end()) { if (itFunc != cmdMap_.end()) {
auto requestFunc = itFunc->second; auto requestFunc = itFunc->second;
if (requestFunc != nullptr) { if (requestFunc != nullptr) {
return static_cast<int32_t>((this->*requestFunc)(data, reply)); bool result = (this->*requestFunc)(data, reply);
return result ? E_PRINT_NONE : E_PRINT_SERVER_FAILURE;
} }
} }
PRINT_HILOGW("default case, need check."); PRINT_HILOGW("default case, need check.");

View File

@ -94,6 +94,8 @@ void PrintManagerClient::OnRemoteSaDied(const wptr<IRemoteObject> &remote)
serviceRemote->RemoveDeathRecipient(deathRecipient_); serviceRemote->RemoveDeathRecipient(deathRecipient_);
printServiceProxy_ = nullptr; printServiceProxy_ = nullptr;
deathRecipient_ = nullptr; deathRecipient_ = nullptr;
std::unique_lock<std::mutex> lock(conditionMutex_);
ready_ = false;
} }
} }

View File

@ -167,6 +167,10 @@ int32_t PrintServiceProxy::QueryAllExtension(std::vector<PrintExtensionInfo> &ex
} }
uint32_t len = reply.ReadUint32(); uint32_t len = reply.ReadUint32();
if (len > PRINT_MAX_PRINT_COUNT) {
PRINT_HILOGE("len is out of range.");
return E_PRINT_INVALID_PARAMETER;
}
for (uint32_t i = 0; i < len; i++) { for (uint32_t i = 0; i < len; i++) {
auto infoPtr = PrintExtensionInfo::Unmarshalling(reply); auto infoPtr = PrintExtensionInfo::Unmarshalling(reply);
if (infoPtr == nullptr) { if (infoPtr == nullptr) {
@ -560,6 +564,10 @@ int32_t PrintServiceProxy::QueryAllPrintJob(std::vector<PrintJob> &printJobs)
} }
uint32_t len = reply.ReadUint32(); uint32_t len = reply.ReadUint32();
if (len > PRINT_MAX_PRINT_COUNT) {
PRINT_HILOGE("len is out of range.");
return E_PRINT_INVALID_PARAMETER;
}
for (uint32_t i = 0; i < len; i++) { for (uint32_t i = 0; i < len; i++) {
auto jobPtr = PrintJob::Unmarshalling(reply); auto jobPtr = PrintJob::Unmarshalling(reply);
if (jobPtr == nullptr) { if (jobPtr == nullptr) {

View File

@ -44,7 +44,8 @@ int32_t ScanCallbackStub::OnRemoteRequest(
if (itFunc != cmdMap_.end()) { if (itFunc != cmdMap_.end()) {
auto requestFunc = itFunc->second; auto requestFunc = itFunc->second;
if (requestFunc != nullptr) { if (requestFunc != nullptr) {
return static_cast<int32_t>((this->*requestFunc)(data, reply)); bool result = (this->*requestFunc)(data, reply);
return result ? E_SCAN_NONE : E_SCAN_SERVER_FAILURE;
} }
} }
SCAN_HILOGW("default case, need check."); SCAN_HILOGW("default case, need check.");

View File

@ -506,6 +506,10 @@ int32_t ScanServiceProxy::GetAddedScanner(std::vector<ScanDeviceInfo>& allAddedS
return ret; return ret;
} }
uint32_t len = reply.ReadUint32(); uint32_t len = reply.ReadUint32();
if (len > SCAN_MAX_COUNT) {
SCAN_HILOGE("len is out of range.");
return E_SCAN_INVALID_PARAMETER;
}
for (uint32_t i = 0; i < len; i++) { for (uint32_t i = 0; i < len; i++) {
auto infoPtr = ScanDeviceInfo::Unmarshalling(reply); auto infoPtr = ScanDeviceInfo::Unmarshalling(reply);
if (infoPtr == nullptr) { if (infoPtr == nullptr) {

View File

@ -110,15 +110,19 @@ bool JsPrintExtension::InitContextObj(JsRuntime &jsRuntime, napi_value &extObj,
napi_env engine = jsRuntime.GetNapiEnv(); napi_env engine = jsRuntime.GetNapiEnv();
napi_value contextObj = CreateJsPrintExtensionContext(engine, context, extensionId); napi_value contextObj = CreateJsPrintExtensionContext(engine, context, extensionId);
auto shellContextRef = jsRuntime.LoadSystemModule("PrintExtensionContext", &contextObj, NapiPrintUtils::ARGC_ONE); auto shellContextRef = jsRuntime.LoadSystemModule("PrintExtensionContext", &contextObj, NapiPrintUtils::ARGC_ONE);
if (shellContextRef == nullptr) {
PRINT_HILOGE("Failed to load print extension context ref");
return false;
}
contextObj = shellContextRef->GetNapiValue(); contextObj = shellContextRef->GetNapiValue();
PRINT_HILOGD("JsPrintExtension::Init Bind.");
context->Bind(jsRuntime, shellContextRef.release());
PRINT_HILOGD("JsPrintExtension::napi_set_named_property.");
napi_set_named_property(engine, extObj, "context", contextObj);
if (contextObj == nullptr) { if (contextObj == nullptr) {
PRINT_HILOGE("Failed to get Print extension native object"); PRINT_HILOGE("Failed to get Print extension native object");
return false; return false;
} }
PRINT_HILOGD("JsPrintExtension::Init Bind.");
context->Bind(jsRuntime, shellContextRef.release());
PRINT_HILOGD("JsPrintExtension::napi_set_named_property.");
napi_set_named_property(engine, extObj, "context", contextObj);
napi_wrap(engine, contextObj, new std::weak_ptr<AbilityRuntime::Context>(context), napi_wrap(engine, contextObj, new std::weak_ptr<AbilityRuntime::Context>(context),
[](napi_env, void *data, void *) { [](napi_env, void *data, void *) {

View File

@ -59,6 +59,7 @@ private:
static bool IsSupportType(const std::string& type); static bool IsSupportType(const std::string& type);
static bool IsValidApplicationEvent(uint32_t event); static bool IsValidApplicationEvent(uint32_t event);
static bool IsValidDefaultPrinterType(uint32_t type); static bool IsValidDefaultPrinterType(uint32_t type);
static void NapiThrowError(napi_env env, int32_t errCode);
private: private:
struct InnerPrintContext : public PrintAsyncCall::Context { struct InnerPrintContext : public PrintAsyncCall::Context {

View File

@ -533,6 +533,7 @@ napi_value NapiInnerPrint::On(napi_env env, napi_callback_info info)
if (!NapiInnerPrint::IsSupportType(type)) { if (!NapiInnerPrint::IsSupportType(type)) {
PRINT_HILOGE("Event On type : %{public}s not support", type.c_str()); PRINT_HILOGE("Event On type : %{public}s not support", type.c_str());
NapiThrowError(env, E_PRINT_INVALID_PARAMETER);
return nullptr; return nullptr;
} }
@ -550,6 +551,7 @@ napi_value NapiInnerPrint::On(napi_env env, napi_callback_info info)
int32_t ret = PrintManagerClient::GetInstance()->On("", type, callback); int32_t ret = PrintManagerClient::GetInstance()->On("", type, callback);
if (ret != E_PRINT_NONE) { if (ret != E_PRINT_NONE) {
PRINT_HILOGE("Failed to register event"); PRINT_HILOGE("Failed to register event");
NapiThrowError(env, ret);
return nullptr; return nullptr;
} }
return nullptr; return nullptr;
@ -558,40 +560,38 @@ napi_value NapiInnerPrint::On(napi_env env, napi_callback_info info)
napi_value NapiInnerPrint::Off(napi_env env, napi_callback_info info) napi_value NapiInnerPrint::Off(napi_env env, napi_callback_info info)
{ {
PRINT_HILOGD("Enter ---->"); PRINT_HILOGD("Enter ---->");
auto context = std::make_shared<InnerPrintContext>(); size_t argc = NapiPrintUtils::MAX_ARGC;
auto input = napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
[context]( napi_value thisVal = nullptr;
napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { void *data = nullptr;
PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE, " should 1 parameter!", napi_invalid_arg); PRINT_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVal, &data));
napi_valuetype valuetype; PRINT_ASSERT(env, argc == NapiPrintUtils::ARGC_ONE || argc == NapiPrintUtils::ARGC_TWO, "need 1-2 parameter!");
PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
PRINT_ASSERT_BASE(env, valuetype == napi_string, "type is not a string", napi_string_expected); napi_valuetype valuetype;
std::string type = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]); PRINT_CALL(env, napi_typeof(env, argv[0], &valuetype));
if (!NapiInnerPrint::IsSupportType(type)) { PRINT_ASSERT(env, valuetype == napi_string, "type is not a string");
PRINT_HILOGE("Event Off type : %{public}s not support", context->type.c_str()); std::string type = NapiPrintUtils::GetStringFromValueUtf8(env, argv[0]);
context->SetErrorIndex(E_PRINT_INVALID_PARAMETER); PRINT_HILOGD("type : %{public}s", type.c_str());
return napi_invalid_arg;
} if (!NapiInnerPrint::IsSupportType(type)) {
context->type = type; PRINT_HILOGE("Event Off type : %{public}s not support", type.c_str());
PRINT_HILOGD("event type : %{public}s", context->type.c_str()); NapiThrowError(env, E_PRINT_INVALID_PARAMETER);
return napi_ok; return nullptr;
}; }
auto output = [context](napi_env env, napi_value *result) -> napi_status {
napi_status status = napi_get_boolean(env, context->result, result); if (argc == NapiPrintUtils::ARGC_TWO) {
PRINT_HILOGD("context->result = %{public}d", context->result); valuetype = napi_undefined;
return status; napi_typeof(env, argv[1], &valuetype);
}; PRINT_ASSERT(env, valuetype == napi_function, "callback is not a function");
auto exec = [context](PrintAsyncCall::Context *ctx) { }
int32_t ret = PrintManagerClient::GetInstance()->Off("", context->type);
context->result = ret == E_PRINT_NONE; int32_t ret = PrintManagerClient::GetInstance()->Off("", type);
if (ret != E_PRINT_NONE) { if (ret != E_PRINT_NONE) {
PRINT_HILOGE("Failed to unregister event"); PRINT_HILOGE("Failed to unregister event");
context->SetErrorIndex(ret); NapiThrowError(env, ret);
} return nullptr;
}; }
context->SetAction(std::move(input), std::move(output)); return nullptr;
PrintAsyncCall asyncCall(env, info, std::dynamic_pointer_cast<PrintAsyncCall::Context>(context));
return asyncCall.Call(env, exec);
} }
napi_value NapiInnerPrint::StartGetPrintFile(napi_env env, napi_callback_info info) napi_value NapiInnerPrint::StartGetPrintFile(napi_env env, napi_callback_info info)
@ -617,6 +617,7 @@ napi_value NapiInnerPrint::StartGetPrintFile(napi_env env, napi_callback_info in
int32_t retCallback = PrintManagerClient::GetInstance()->On("", PRINT_GET_FILE_CALLBACK_ADAPTER, callback); int32_t retCallback = PrintManagerClient::GetInstance()->On("", PRINT_GET_FILE_CALLBACK_ADAPTER, callback);
if (retCallback != E_PRINT_NONE) { if (retCallback != E_PRINT_NONE) {
PRINT_HILOGE("Failed to register startGetPrintFile callback"); PRINT_HILOGE("Failed to register startGetPrintFile callback");
NapiThrowError(env, retCallback);
return nullptr; return nullptr;
} }
} }
@ -631,6 +632,7 @@ napi_value NapiInnerPrint::StartGetPrintFile(napi_env env, napi_callback_info in
int32_t ret = PrintManagerClient::GetInstance()->StartGetPrintFile(jobId, *printAttributes, fd); int32_t ret = PrintManagerClient::GetInstance()->StartGetPrintFile(jobId, *printAttributes, fd);
if (ret != E_PRINT_NONE) { if (ret != E_PRINT_NONE) {
PRINT_HILOGE("Failed to StartGetPrintFile"); PRINT_HILOGE("Failed to StartGetPrintFile");
NapiThrowError(env, ret);
return nullptr; return nullptr;
} }
} }
@ -754,14 +756,13 @@ napi_value NapiInnerPrint::NotifyPrintServiceEvent(napi_env env, napi_callback_i
auto input = auto input =
[context]( [context](
napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status { napi_env env, size_t argc, napi_value *argv, napi_value self, napi_callback_info info) -> napi_status {
PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_TWO, " should 2 parameter!", napi_invalid_arg); PRINT_ASSERT_BASE(env, argc == NapiPrintUtils::ARGC_ONE || argc == NapiPrintUtils::ARGC_TWO,
"should 1 or 2 parameter!", napi_invalid_arg);
napi_valuetype valuetype; napi_valuetype valuetype;
PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg); PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ZERO], &valuetype), napi_invalid_arg);
PRINT_ASSERT_BASE(env, valuetype == napi_string, "jobId is not a string", napi_string_expected);
PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ONE], &valuetype), napi_invalid_arg); PRINT_CALL_BASE(env, napi_typeof(env, argv[NapiPrintUtils::INDEX_ONE], &valuetype), napi_invalid_arg);
PRINT_ASSERT_BASE(env, valuetype == napi_number, "event is not a number", napi_number_expected); uint32_t event = NapiPrintUtils::GetUint32FromValue(env, argv[NapiPrintUtils::INDEX_ZERO]);
std::string jobId = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ZERO]); std::string jobId = NapiPrintUtils::GetStringFromValueUtf8(env, argv[NapiPrintUtils::INDEX_ONE]);
uint32_t event = NapiPrintUtils::GetUint32FromValue(env, argv[NapiPrintUtils::INDEX_ONE]);
PRINT_HILOGI("jobId: %{public}s, event : %{public}d", jobId.c_str(), event); PRINT_HILOGI("jobId: %{public}s, event : %{public}d", jobId.c_str(), event);
if (!IsValidApplicationEvent(event)) { if (!IsValidApplicationEvent(event)) {
PRINT_HILOGE("invalid event"); PRINT_HILOGE("invalid event");
@ -896,4 +897,12 @@ bool NapiInnerPrint::IsValidDefaultPrinterType(uint32_t type)
} }
return false; return false;
} }
void NapiInnerPrint::NapiThrowError(napi_env env, const int32_t errCode)
{
napi_value result = nullptr;
napi_create_error(env, NapiPrintUtils::CreateInt32(env, errCode),
NapiPrintUtils::CreateStringUtf8(env, NapiPrintUtils::GetPrintErrorMsg(errCode)), &result);
napi_throw(env, result);
}
} // namespace OHOS::Print } // namespace OHOS::Print

View File

@ -42,6 +42,8 @@ static const std::string UI_EXTENSION_TYPE_NAME = "ability.want.params.uiExtensi
static const std::string PRINT_UI_EXTENSION_TYPE = "sysDialog/print"; static const std::string PRINT_UI_EXTENSION_TYPE = "sysDialog/print";
static const std::string CALLER_PKG_NAME = "caller.pkgName"; static const std::string CALLER_PKG_NAME = "caller.pkgName";
static const std::string ABILITY_PARAMS_STREAM = "ability.params.stream"; static const std::string ABILITY_PARAMS_STREAM = "ability.params.stream";
static const std::string LAUNCH_PARAMETER_FILE_LIST_SIZE = "fileListSize";
static const int32_t MAX_FILE_LIST_SIZE = 100;
PrintTask::PrintTask(const std::vector<std::string> &innerList, const sptr<IRemoteObject> &innerCallerToken_) PrintTask::PrintTask(const std::vector<std::string> &innerList, const sptr<IRemoteObject> &innerCallerToken_)
: taskId_("") : taskId_("")
@ -100,13 +102,17 @@ uint32_t PrintTask::Start(napi_env env, napi_callback_info info)
if (pathType_ == FILE_PATH_ABSOLUTED) { if (pathType_ == FILE_PATH_ABSOLUTED) {
for (auto file : fileList_) { for (auto file : fileList_) {
int32_t fd = PrintUtils::OpenFile(file); int32_t fd = PrintUtils::OpenFile(file);
if (fd < 0) { if (fd >= 0) {
PRINT_HILOGE("file[%{private}s] is invalid", file.c_str()); fdList_.emplace_back(fd);
fdList_.clear(); continue;
fileList_.clear();
return E_PRINT_INVALID_PARAMETER;
} }
fdList_.emplace_back(fd); PRINT_HILOGE("file[%{private}s] is invalid", file.c_str());
for (auto fd : fdList_) {
close(fd);
}
fdList_.clear();
fileList_.clear();
return E_PRINT_INVALID_PARAMETER;
} }
} }
@ -255,7 +261,12 @@ uint32_t PrintTask::StartUIExtensionAbility(
AAFwk::Want want; AAFwk::Want want;
want.SetElementName(SPOOLER_BUNDLE_NAME, SPOOLER_PREVIEW_ABILITY_NAME); want.SetElementName(SPOOLER_BUNDLE_NAME, SPOOLER_PREVIEW_ABILITY_NAME);
want.SetParam(LAUNCH_PARAMETER_JOB_ID, adapterParam->jobId); want.SetParam(LAUNCH_PARAMETER_JOB_ID, adapterParam->jobId);
want.SetParam(LAUNCH_PARAMETER_FILE_LIST, fileList_); if (fileList_.size() <= MAX_FILE_LIST_SIZE) {
want.SetParam(LAUNCH_PARAMETER_FILE_LIST, fileList_);
} else {
PRINT_HILOGW("fileList exceeds the maximum length.");
}
want.SetParam(LAUNCH_PARAMETER_FILE_LIST_SIZE, static_cast<int>(fileList_.size()));
PrintUtils::BuildAdapterParam(adapterParam, want); PrintUtils::BuildAdapterParam(adapterParam, want);
int32_t callerTokenId = static_cast<int32_t>(IPCSkeleton::GetCallingTokenID()); int32_t callerTokenId = static_cast<int32_t>(IPCSkeleton::GetCallingTokenID());
int32_t callerUid = IPCSkeleton::GetCallingUid(); int32_t callerUid = IPCSkeleton::GetCallingUid();

View File

@ -28,12 +28,12 @@ bool PrintCallbackProxy::OnCallback()
MessageOption option; MessageOption option;
data.WriteInterfaceToken(GetDescriptor()); data.WriteInterfaceToken(GetDescriptor());
auto remote = Remote(); sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) { if (remote == nullptr) {
PRINT_HILOGE("SendRequest failed, error: remote is null"); PRINT_HILOGE("SendRequest failed, error: remote is null");
return false; return false;
} }
int error = Remote()->SendRequest(PRINT_CALLBACK_TASK, data, reply, option); int error = remote->SendRequest(PRINT_CALLBACK_TASK, data, reply, option);
if (error != 0) { if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error); PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false; return false;
@ -54,7 +54,12 @@ bool PrintCallbackProxy::OnCallback(uint32_t state, const PrinterInfo &info)
data.WriteUint32(state); data.WriteUint32(state);
info.Marshalling(data); info.Marshalling(data);
int error = Remote()->SendRequest(PRINT_CALLBACK_PRINTER, data, reply, option); sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PRINT_HILOGE("SendRequest failed, error: remote is null");
return false;
}
int error = remote->SendRequest(PRINT_CALLBACK_PRINTER, data, reply, option);
if (error != 0) { if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error); PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false; return false;
@ -75,7 +80,12 @@ bool PrintCallbackProxy::OnCallback(uint32_t state, const PrintJob &info)
data.WriteUint32(state); data.WriteUint32(state);
info.Marshalling(data); info.Marshalling(data);
int error = Remote()->SendRequest(PRINT_CALLBACK_PRINT_JOB, data, reply, option); sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PRINT_HILOGE("SendRequest failed, error: remote is null");
return false;
}
int error = remote->SendRequest(PRINT_CALLBACK_PRINT_JOB, data, reply, option);
if (error != 0) { if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error); PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false; return false;
@ -95,7 +105,12 @@ bool PrintCallbackProxy::OnCallback(const std::string &extensionId, const std::s
data.WriteString(extensionId); data.WriteString(extensionId);
data.WriteString(info); data.WriteString(info);
int error = Remote()->SendRequest(PRINT_CALLBACK_EXTINFO, data, reply, option); sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PRINT_HILOGE("SendRequest failed, error: remote is null");
return false;
}
int error = remote->SendRequest(PRINT_CALLBACK_EXTINFO, data, reply, option);
if (error != 0) { if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error); PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false; return false;
@ -122,7 +137,12 @@ bool PrintCallbackProxy::OnCallbackAdapterLayout(const std::string &jobId, const
newAttrs.Marshalling(data); newAttrs.Marshalling(data);
data.WriteFileDescriptor(fd); data.WriteFileDescriptor(fd);
int error = Remote()->SendRequest(PRINT_CALLBACK_PRINT_JOB_ADAPTER, data, reply, option); sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PRINT_HILOGE("SendRequest failed, error: remote is null");
return false;
}
int error = remote->SendRequest(PRINT_CALLBACK_PRINT_JOB_ADAPTER, data, reply, option);
if (error != 0) { if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error); PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false; return false;
@ -148,7 +168,12 @@ bool PrintCallbackProxy::onCallbackAdapterJobStateChanged(const std::string jobI
data.WriteUint32(state); data.WriteUint32(state);
data.WriteUint32(subState); data.WriteUint32(subState);
int error = Remote()->SendRequest(PRINT_CALLBACK_PRINT_JOB_CHANGED_ADAPTER, data, reply, option); sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PRINT_HILOGE("SendRequest failed, error: remote is null");
return false;
}
int error = remote->SendRequest(PRINT_CALLBACK_PRINT_JOB_CHANGED_ADAPTER, data, reply, option);
if (error != 0) { if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error); PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false; return false;
@ -171,7 +196,12 @@ bool PrintCallbackProxy::OnCallbackAdapterGetFile(uint32_t state)
data.WriteUint32(state); data.WriteUint32(state);
int error = Remote()->SendRequest(PRINT_CALLBACK_PRINT_GET_FILE_ADAPTER, data, reply, option); sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PRINT_HILOGE("SendRequest failed, error: remote is null");
return false;
}
int error = remote->SendRequest(PRINT_CALLBACK_PRINT_GET_FILE_ADAPTER, data, reply, option);
if (error != 0) { if (error != 0) {
PRINT_HILOGE("SendRequest failed, error %{public}d", error); PRINT_HILOGE("SendRequest failed, error %{public}d", error);
return false; return false;

View File

@ -1550,13 +1550,9 @@ void PrintCupsClient::UpdateBorderlessJobParameter(json& optionJson, JobParamete
if (params == nullptr) { if (params == nullptr) {
return; return;
} }
if (optionJson.contains("borderless") && optionJson["borderless"].is_string()) { if (optionJson.contains("isBorderless") && optionJson["isBorderless"].is_boolean()) {
std::string isBorderless = optionJson["borderless"].get<std::string>(); bool isBorderless = optionJson["isBorderless"].get<bool>();
if (isBorderless == "true") { params->borderless = isBorderless ? TRUE : FALSE;
params->borderless = TRUE;
} else {
params->borderless = FALSE;
}
} else { } else {
params->borderless = TRUE; params->borderless = TRUE;
} }

View File

@ -1693,7 +1693,7 @@ int32_t PrintServiceAbility::CheckAndSendQueuePrintJob(const std::string &jobId,
CheckJobQueueBlocked(*jobIt->second); CheckJobQueueBlocked(*jobIt->second);
auto printerId = jobIt->second->GetPrinterId(); auto printerId = jobIt->second->GetPrinterId();
auto printerInfo = printSystemData_.QueryPrinterInfoByPrinterId(printerId); auto printerInfo = printSystemData_.QueryDiscoveredPrinterInfoById(printerId);
if (printerInfo == nullptr) { if (printerInfo == nullptr) {
PRINT_HILOGE("Invalid printerId"); PRINT_HILOGE("Invalid printerId");
return E_PRINT_INVALID_PRINTER; return E_PRINT_INVALID_PRINTER;

View File

@ -44,7 +44,7 @@ std::map<std::string, sptr<ScanMDnsDiscoveryObserver>> ScanMdnsService::discover
bool ScanMdnsService::OnStartDiscoverService() bool ScanMdnsService::OnStartDiscoverService()
{ {
const std::vector<std::string> scannerServiceTypes = { "_ipp._tcp" }; const std::vector<std::string> scannerServiceTypes = { "_scanner._tcp" };
constexpr int32_t MDNS_PORT = 5353; constexpr int32_t MDNS_PORT = 5353;
{ {
std::lock_guard<std::mutex> autoLock(g_lock); std::lock_guard<std::mutex> autoLock(g_lock);

View File

@ -186,6 +186,7 @@ ScanServiceAbility::~ScanServiceAbility()
FREE_AND_NULLPTR(saneReadBuf); FREE_AND_NULLPTR(saneReadBuf);
FREE_AND_NULLPTR(jpegbuf) FREE_AND_NULLPTR(jpegbuf)
DELETE_AND_NULLIFY(cinfoPtr); DELETE_AND_NULLIFY(cinfoPtr);
DELETE_AND_NULLIFY(ofp);
SCAN_HILOGD("~ScanServiceAbility state_ is %{public}d.", static_cast<int>(state_)); SCAN_HILOGD("~ScanServiceAbility state_ is %{public}d.", static_cast<int>(state_));
} }
@ -1680,10 +1681,12 @@ void ScanServiceAbility::GeneratePictureBatch(const std::string &scannerId, std:
int32_t nowScanId = it->first; int32_t nowScanId = it->first;
file_name = "scan_tmp" + std::to_string(nowScanId) + ".jpg"; file_name = "scan_tmp" + std::to_string(nowScanId) + ".jpg";
std::string outputDir = ObtainUserCacheDirectory(currentUseScannerUserId_); std::string outputDir = ObtainUserCacheDirectory(currentUseScannerUserId_);
if (!std::filesystem::exists(outputDir)) { char canonicalPath[PATH_MAX] = { 0 };
SCAN_HILOGE("outputDir %{public}s does not exist.", outputDir.c_str()); if (realpath(outputDir.c_str(), canonicalPath) == nullptr) {
SCAN_HILOGE("The real output dir is null, errno:%{public}s", std::to_string(errno).c_str());
return; return;
} }
outputDir = canonicalPath;
output_file = outputDir.append("/").append(file_name); output_file = outputDir.append("/").append(file_name);
ofp = fopen(output_file.c_str(), "w"); ofp = fopen(output_file.c_str(), "w");
if (ofp == nullptr) { if (ofp == nullptr) {
@ -1717,10 +1720,12 @@ void ScanServiceAbility::GeneratePictureSingle(const std::string &scannerId, std
int32_t nowScanId = it->first; int32_t nowScanId = it->first;
file_name = "scan_tmp" + std::to_string(nowScanId) + ".jpg"; file_name = "scan_tmp" + std::to_string(nowScanId) + ".jpg";
std::string outputDir = ObtainUserCacheDirectory(currentUseScannerUserId_); std::string outputDir = ObtainUserCacheDirectory(currentUseScannerUserId_);
if (!std::filesystem::exists(outputDir)) { char canonicalPath[PATH_MAX] = { 0 };
SCAN_HILOGE("outputDir %{public}s does not exist.", outputDir.c_str()); if (realpath(outputDir.c_str(), canonicalPath) == nullptr) {
SCAN_HILOGE("The real output dir is null, errno:%{public}s", std::to_string(errno).c_str());
return; return;
} }
outputDir = canonicalPath;
output_file = outputDir.append("/").append(file_name); output_file = outputDir.append("/").append(file_name);
ofp = fopen(output_file.c_str(), "w"); ofp = fopen(output_file.c_str(), "w");
if (ofp == nullptr) { if (ofp == nullptr) {

View File

@ -65,7 +65,8 @@ int32_t ScanServiceStub::OnRemoteRequest(
if (itFunc != cmdMap_.end()) { if (itFunc != cmdMap_.end()) {
auto requestFunc = itFunc->second; auto requestFunc = itFunc->second;
if (requestFunc != nullptr) { if (requestFunc != nullptr) {
return (this->*requestFunc)(data, reply); bool result = (this->*requestFunc)(data, reply);
return result ? E_SCAN_NONE : E_SCAN_SERVER_FAILURE;
} }
} }
SCAN_HILOGW("default case, need check."); SCAN_HILOGW("default case, need check.");

View File

@ -597,6 +597,124 @@ void TestScannerInfoTCPNapiInterface(const uint8_t* data, size_t size, FuzzedDat
ScannerInfoHelperTCP::MakeJsObject(env, info); ScannerInfoHelperTCP::MakeJsObject(env, info);
} }
void TestSetNamedProperty(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
napi_value object = nullptr;
std::string name = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH);
napi_value value = nullptr;
NapiScanUtils::SetNamedProperty(env, object, name, value);
}
void TestGetUint32FromValue(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
napi_value value = nullptr;
NapiScanUtils::GetUint32FromValue(env, value);
}
void TestGetInt32FromValue(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
napi_value value = nullptr;
NapiScanUtils::GetInt32FromValue(env, value);
}
void TestGetStringFromValueUtf8(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
napi_value value = nullptr;
NapiScanUtils::GetStringFromValueUtf8(env, value);
}
void TestValueIsArrayBuffer(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
napi_value value = nullptr;
NapiScanUtils::ValueIsArrayBuffer(env, value);
}
void TestGetInfoFromArrayBufferValue(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
napi_value value = nullptr;
size_t *length = nullptr;
NapiScanUtils::GetInfoFromArrayBufferValue(env, value, length);
}
void TestCreateObject(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
NapiScanUtils::CreateObject(env);
}
void TestGetUndefined(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
NapiScanUtils::GetUndefined(env);
}
void TestCallFunction(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
napi_value recv = nullptr;
napi_value func = nullptr;
size_t argc = 0;
napi_value *argv = nullptr;
NapiScanUtils::CallFunction(env, recv, func, argc, argv);
}
void TestCreateReference(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
napi_value callback = nullptr;
NapiScanUtils::CreateReference(env, callback);
}
void TestCreateBoolean(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
bool value = 1;
NapiScanUtils::CreateBoolean(env, value);
}
void TestGetBooleanFromValue(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
napi_value value = nullptr;
NapiScanUtils::GetBooleanFromValue(env, value);
}
void TestGetBooleanProperty(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
napi_value object = nullptr;
std::string propertyName = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH);
NapiScanUtils::GetBooleanProperty(env, object, propertyName);
}
void TestSetBooleanProperty(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
napi_value object = nullptr;
std::string name = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH);
bool value = 1;
NapiScanUtils::SetBooleanProperty(env, object, name, value);
}
void TestToLower(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
std::string s = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH);
NapiScanUtils::ToLower(s);
}
void TestGetValueString(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
napi_value jsValue = nullptr;
NapiScanUtils::GetValueString(env, jsValue);
}
void TestGetExtensionIdInterface(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider) void TestGetExtensionIdInterface(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{ {
std::string globalId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH); std::string globalId = dataProvider->ConsumeRandomLengthString(MAX_STRING_LENGTH);
@ -651,6 +769,15 @@ void TestIsPathValid(const uint8_t* data, size_t size, FuzzedDataProvider* dataP
NapiScanUtils::IsPathValid(filePath); NapiScanUtils::IsPathValid(filePath);
} }
void TestGetJsVal(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{
napi_env env = nullptr;
napi_callback_info info = nullptr;
napi_value* jsValue = nullptr;
size_t length = 1;
NapiScanUtils::GetJsVal(env, info, jsValue, length);
}
void ScanOptionDescriptorFuzzTest(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider) void ScanOptionDescriptorFuzzTest(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{ {
TestSetOptionName(data, size, dataProvider); TestSetOptionName(data, size, dataProvider);
@ -762,6 +889,22 @@ void ScannerInfoHelperFuzzTest(const uint8_t* data, size_t size, FuzzedDataProvi
void NapiScanUtilsFuzzTest(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider) void NapiScanUtilsFuzzTest(const uint8_t* data, size_t size, FuzzedDataProvider* dataProvider)
{ {
TestSetNamedProperty(data, size, dataProvider);
TestGetUint32FromValue(data, size, dataProvider);
TestGetInt32FromValue(data, size, dataProvider);
TestGetStringFromValueUtf8(data, size, dataProvider);
TestValueIsArrayBuffer(data, size, dataProvider);
TestGetInfoFromArrayBufferValue(data, size, dataProvider);
TestCreateObject(data, size, dataProvider);
TestGetUndefined(data, size, dataProvider);
TestCallFunction(data, size, dataProvider);
TestCreateReference(data, size, dataProvider);
TestCreateBoolean(data, size, dataProvider);
TestGetBooleanFromValue(data, size, dataProvider);
TestGetBooleanProperty(data, size, dataProvider);
TestSetBooleanProperty(data, size, dataProvider);
TestToLower(data, size, dataProvider);
TestGetValueString(data, size, dataProvider);
TestGetExtensionIdInterface(data, size, dataProvider); TestGetExtensionIdInterface(data, size, dataProvider);
TestGetGlobalIdInterface(data, size, dataProvider); TestGetGlobalIdInterface(data, size, dataProvider);
TestGetLocalIdInterface(data, size, dataProvider); TestGetLocalIdInterface(data, size, dataProvider);
@ -770,6 +913,7 @@ void NapiScanUtilsFuzzTest(const uint8_t* data, size_t size, FuzzedDataProvider*
TestGetTaskEventId(data, size, dataProvider); TestGetTaskEventId(data, size, dataProvider);
TestOpenFile(data, size, dataProvider); TestOpenFile(data, size, dataProvider);
TestIsPathValid(data, size, dataProvider); TestIsPathValid(data, size, dataProvider);
TestGetJsVal(data, size, dataProvider);
} }
} }

View File

@ -95,7 +95,7 @@ HWTEST_F(PrintCallbackStubTest, PrintCallbackStubTest_0003, TestSize.Level1)
auto callback = std::make_shared<MockPrintCallbackStub>(); auto callback = std::make_shared<MockPrintCallbackStub>();
EXPECT_NE(callback, nullptr); EXPECT_NE(callback, nullptr);
EXPECT_CALL(*callback, OnCallback()).Times(1); EXPECT_CALL(*callback, OnCallback()).Times(1);
EXPECT_TRUE(static_cast<bool>(callback->OnRemoteRequest(code, data, reply, option))); EXPECT_EQ(callback->OnRemoteRequest(code, data, reply, option), E_PRINT_NONE);
} }
MATCHER_P(PrinterInfoMatcher, oParam, "Match Printer Info") MATCHER_P(PrinterInfoMatcher, oParam, "Match Printer Info")
@ -135,7 +135,7 @@ HWTEST_F(PrintCallbackStubTest, PrintCallbackStubTest_0004, TestSize.Level1)
EXPECT_NE(callback, nullptr); EXPECT_NE(callback, nullptr);
EXPECT_CALL(*callback, OnCallback(testState, EXPECT_CALL(*callback, OnCallback(testState,
Matcher<const PrinterInfo&>(PrinterInfoMatcher(testInfo)))).Times(1).WillOnce(Return(true)); Matcher<const PrinterInfo&>(PrinterInfoMatcher(testInfo)))).Times(1).WillOnce(Return(true));
EXPECT_TRUE(static_cast<bool>(callback->OnRemoteRequest(code, data, reply, option))); EXPECT_EQ(callback->OnRemoteRequest(code, data, reply, option), E_PRINT_NONE);
EXPECT_TRUE(reply.ReadBool()); EXPECT_TRUE(reply.ReadBool());
} }
@ -164,7 +164,7 @@ HWTEST_F(PrintCallbackStubTest, PrintCallbackStubTest_0005, TestSize.Level1)
EXPECT_NE(callback, nullptr); EXPECT_NE(callback, nullptr);
EXPECT_CALL(*callback, OnCallback(testState, EXPECT_CALL(*callback, OnCallback(testState,
Matcher<const PrintJob&>(PrintJobMatcher(testJob)))).Times(1).WillOnce(Return(true)); Matcher<const PrintJob&>(PrintJobMatcher(testJob)))).Times(1).WillOnce(Return(true));
EXPECT_TRUE(static_cast<bool>(callback->OnRemoteRequest(code, data, reply, option))); EXPECT_EQ(callback->OnRemoteRequest(code, data, reply, option), E_PRINT_NONE);
EXPECT_TRUE(reply.ReadBool()); EXPECT_TRUE(reply.ReadBool());
} }
@ -189,7 +189,7 @@ HWTEST_F(PrintCallbackStubTest, PrintCallbackStubTest_0006, TestSize.Level1)
auto callback = std::make_shared<MockPrintCallbackStub>(); auto callback = std::make_shared<MockPrintCallbackStub>();
EXPECT_NE(callback, nullptr); EXPECT_NE(callback, nullptr);
EXPECT_CALL(*callback, OnCallback(extensionId, extInfo)).Times(1).WillOnce(Return(true)); EXPECT_CALL(*callback, OnCallback(extensionId, extInfo)).Times(1).WillOnce(Return(true));
EXPECT_TRUE(static_cast<bool>(callback->OnRemoteRequest(code, data, reply, option))); EXPECT_EQ(callback->OnRemoteRequest(code, data, reply, option), E_PRINT_NONE);
EXPECT_TRUE(reply.ReadBool()); EXPECT_TRUE(reply.ReadBool());
} }
} // namespace Print } // namespace Print

View File

@ -90,7 +90,7 @@ HWTEST_F(PrintExtensionCallbackStubTest, PrintExtensionCallbackStubTest_0003, Te
EXPECT_TRUE(data.WriteInterfaceToken(IPrintExtensionCallback::GetDescriptor())); EXPECT_TRUE(data.WriteInterfaceToken(IPrintExtensionCallback::GetDescriptor()));
PrintExtensionCallbackStub callback; PrintExtensionCallbackStub callback;
EXPECT_FALSE(callback.OnRemoteRequest(code, data, reply, option)); EXPECT_EQ(callback.OnRemoteRequest(code, data, reply, option), E_PRINT_SERVER_FAILURE);
} }
/** /**
@ -112,7 +112,7 @@ HWTEST_F(PrintExtensionCallbackStubTest, PrintExtensionCallbackStubTest_0004, Te
return true; return true;
}; };
callback.SetExtCallback(extCb); callback.SetExtCallback(extCb);
EXPECT_TRUE(callback.OnRemoteRequest(code, data, reply, option)); EXPECT_EQ(callback.OnRemoteRequest(code, data, reply, option), E_PRINT_NONE);
} }
/** /**
@ -130,7 +130,7 @@ HWTEST_F(PrintExtensionCallbackStubTest, PrintExtensionCallbackStubTest_0005, Te
EXPECT_TRUE(data.WriteInterfaceToken(IPrintExtensionCallback::GetDescriptor())); EXPECT_TRUE(data.WriteInterfaceToken(IPrintExtensionCallback::GetDescriptor()));
PrintExtensionCallbackStub callback; PrintExtensionCallbackStub callback;
EXPECT_FALSE(callback.OnRemoteRequest(code, data, reply, option)); EXPECT_EQ(callback.OnRemoteRequest(code, data, reply, option), E_PRINT_SERVER_FAILURE);
} }
/** /**
@ -152,7 +152,7 @@ HWTEST_F(PrintExtensionCallbackStubTest, PrintExtensionCallbackStubTest_0006, Te
return true; return true;
}; };
callback.SetPrintJobCallback(printJobCb); callback.SetPrintJobCallback(printJobCb);
EXPECT_TRUE(callback.OnRemoteRequest(code, data, reply, option)); EXPECT_EQ(callback.OnRemoteRequest(code, data, reply, option), E_PRINT_NONE);
} }
/** /**
@ -170,7 +170,7 @@ HWTEST_F(PrintExtensionCallbackStubTest, PrintExtensionCallbackStubTest_0007, Te
EXPECT_TRUE(data.WriteInterfaceToken(IPrintExtensionCallback::GetDescriptor())); EXPECT_TRUE(data.WriteInterfaceToken(IPrintExtensionCallback::GetDescriptor()));
PrintExtensionCallbackStub callback; PrintExtensionCallbackStub callback;
EXPECT_FALSE(callback.OnRemoteRequest(code, data, reply, option)); EXPECT_EQ(callback.OnRemoteRequest(code, data, reply, option), E_PRINT_SERVER_FAILURE);
} }
/** /**
@ -195,7 +195,7 @@ HWTEST_F(PrintExtensionCallbackStubTest, PrintExtensionCallbackStubTest_0008, Te
return true; return true;
}; };
callback.SetPrinterCallback(printerCb); callback.SetPrinterCallback(printerCb);
EXPECT_TRUE(callback.OnRemoteRequest(code, data, reply, option)); EXPECT_EQ(callback.OnRemoteRequest(code, data, reply, option), E_PRINT_NONE);
} }
/** /**
@ -213,7 +213,7 @@ HWTEST_F(PrintExtensionCallbackStubTest, PrintExtensionCallbackStubTest_0009, Te
EXPECT_TRUE(data.WriteInterfaceToken(IPrintExtensionCallback::GetDescriptor())); EXPECT_TRUE(data.WriteInterfaceToken(IPrintExtensionCallback::GetDescriptor()));
PrintExtensionCallbackStub callback; PrintExtensionCallbackStub callback;
EXPECT_FALSE(callback.OnRemoteRequest(code, data, reply, option)); EXPECT_EQ(callback.OnRemoteRequest(code, data, reply, option), E_PRINT_SERVER_FAILURE);
} }
/** /**
@ -241,7 +241,7 @@ HWTEST_F(PrintExtensionCallbackStubTest, PrintExtensionCallbackStubTest_0010, Te
return true; return true;
}; };
callback.SetCapabilityCallback(testCb); callback.SetCapabilityCallback(testCb);
EXPECT_TRUE(callback.OnRemoteRequest(code, data, reply, option)); EXPECT_EQ(callback.OnRemoteRequest(code, data, reply, option), E_PRINT_NONE);
auto result = PrinterCapability::Unmarshalling(reply); auto result = PrinterCapability::Unmarshalling(reply);
EXPECT_NE(result, nullptr); EXPECT_NE(result, nullptr);
} }

View File

@ -514,11 +514,11 @@ HWTEST_F(PrintCupsWrapperTest, PrintCupsWrapperTest_0086, TestSize.Level1)
printCupsClient.UpdateBorderlessJobParameter(optionJson, jobParams); printCupsClient.UpdateBorderlessJobParameter(optionJson, jobParams);
jobParams = new JobParameters(); jobParams = new JobParameters();
printCupsClient.UpdateBorderlessJobParameter(optionJson, jobParams); printCupsClient.UpdateBorderlessJobParameter(optionJson, jobParams);
optionJson["borderless"] = "false"; optionJson["isBorderless"] = false;
printCupsClient.UpdateBorderlessJobParameter(optionJson, jobParams); printCupsClient.UpdateBorderlessJobParameter(optionJson, jobParams);
EXPECT_EQ(jobParams->borderless, 0); EXPECT_EQ(jobParams->borderless, 0);
optionJson["borderless"] = "true"; optionJson["isBorderless"] = true;
printCupsClient.UpdateBorderlessJobParameter(optionJson, jobParams); printCupsClient.UpdateBorderlessJobParameter(optionJson, jobParams);
EXPECT_EQ(jobParams->borderless, 1); EXPECT_EQ(jobParams->borderless, 1);

View File

@ -999,6 +999,7 @@ HWTEST_F(PrintServiceAbilityTest, PrintServiceAbilityTest_0052, TestSize.Level1)
service->printerJobMap_[printerId].insert(std::make_pair(jobId, true)); service->printerJobMap_[printerId].insert(std::make_pair(jobId, true));
auto printerInfo = std::make_shared<PrinterInfo>(); auto printerInfo = std::make_shared<PrinterInfo>();
service->printSystemData_.addedPrinterInfoList_[printerId] = printerInfo; service->printSystemData_.addedPrinterInfoList_[printerId] = printerInfo;
service->printSystemData_.discoveredPrinterInfoList_[printerId] = printerInfo;
EXPECT_EQ(service->CheckAndSendQueuePrintJob(jobId, state, subState), E_PRINT_NONE); EXPECT_EQ(service->CheckAndSendQueuePrintJob(jobId, state, subState), E_PRINT_NONE);
userData->queuedJobList_[jobId] = printJob; userData->queuedJobList_[jobId] = printJob;
state = PRINT_JOB_COMPLETED; state = PRINT_JOB_COMPLETED;

View File

@ -0,0 +1,864 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "js_print_extension_context.h"
using namespace testing;
using namespace testing::ext;
namespace OHOS::Print {
class JsPrintExtensionContextTest : public testing:Test {
public:
JsPrintExtensionContext* jsPrintExtensionContext;
void SetUp() override
{
JsPrintExtensionContext = new JsPrintExtensionContext();
}
void TearDown() override
{
delete jsPrintExtensionContext;
jsPrintExtensionContext = nullptr
}
};
HWTEST_F(nullTest, GetUndefinedValue_ShouldReturnUndefined_WhenCalled, Level0)
{
napi_env engine;
napi_value result = GetUndefinedValue(engine);
EXPECT_EQ(result, nullptr);
}
HWTEST_F(nullTest, OnStartAbility_ShouldReturnUndefined_WhenArgcIsOne, TestSize.Level0)
{
napi_env engine = mock napi_env;
napi_callback_info info = mock napi_callback_info;
napi_value result = OnStartAbility(engine, info);
EXPECT_EQ(napi_undefined, result);
}
HWTEST_F(nullTest, OnStartAbilityWithAccount_ShouldReturnUndefined_WhenArgcIsNotTwoOrThreeOrFour, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value result = OnStartAbilityWithAccount(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
HWTEST_F(nullTest, OnStartAbilityWithAccount_ShouldReturnUndefined_WhenWantUnwrapFails, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
size_t argc = NapiPrintUtils::MAX_ARGC;
napi_get_cb_info(engine, info, &argc, argv, nullptr, nullptr);
napi_value result = OnStartAbilityWithAccount(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
HWTEST_F(nullTest, OnStartAbilityWithAccount_ShouldReturnUndefined_WhenAccountIdUnwrapFails, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
size_t argc = NapiPrintUtils::MAX_ARGC;
napi_get_cb_info(engine, info, &argc, argv, nullptr, nullptr);
napi_value result = OnStartAbilityWithAccount(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
HWTEST_F(nullTest, OnStartAbilityWithAccount_ShouldReturnUndefined_WhenStartOptionsUnwrapFails, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
size_t argc = NapiPrintUtils::MAX_ARGC;
napi_get_cb_info(engine, info, &argc, argv, nullptr, nullptr);
napi_value result = OnStartAbilityWithAccount(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
HWTEST_F(nullTest, OnStartAbilityWithAccount_ShouldReturnUndefined_WhenLastParamIsNotNil, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
size_t argc = NapiPrintUtils::MAX_ARGC;
napi_get_cb_info(engine, info, &argc, argv, nullptr, nullptr);
napi_value result = OnStartAbilityWithAccount(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
HWTEST_F(nullTest, OnStartAbilityWithAccount_ShouldReturnUndefined_WhenStartAbilityWithAccountFails, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
size_t argc = NapiPrintUtils::MAX_ARGC;
napi_get_cb_info(engine, info, &argc, argv, nullptr, nullptr);
napi_value result = OnStartAbilityWithAccount(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
HWTEST_F(nullTest,
OnStartAbilityWithAccount_ShouldReturnResolvedPromise_WhenStartAbilityWithAccountSucceeds, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
size_t argc = NapiPrintUtils::MAX_ARGC;
napi_get_cb_info(engine, info, &argc, argv, nullptr, nullptr);
napi_value result = OnStartAbilityWithAccount(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
TEST_F(nullTest, TestOnTerminateAbility_WhenArgcNotZeroOrOne_ShouldReturnUndefined)
{
napi_env engine;
napi_callback_info info;
napi_value result = OnTerminateAbility(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
TEST_F(nullTest, TestOnTerminateAbility_WhenArgcIsZero_ShouldReturnUndefined)
{
napi_env engine;
napi_callback_info info;
napi_value result = OnTerminateAbility(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
TEST_F(nullTest, TestOnTerminateAbility_WhenArgcIsOne_ShouldReturnNapiValue)
{
napi_env engine;
napi_callback_info info;
napi_value result = OnTerminateAbility(engine, info);
EXPECT_NE(result, nullptr);
}
TEST_F(nullTest, TestOnTerminateAbility_WhenContextIsReleased_ShouldReturnError)
{
napi_env engine;
napi_callback_info info;
napi_value result = OnTerminateAbility(engine, info);
EXPECT_EQ(result, nullptr);
}
TEST_F(nullTest, TestOnTerminateAbility_WhenTerminateAbilitySucceeds_ShouldReturnUndefined)
{
napi_env engine;
napi_callback_info info;
napi_value result = OnTerminateAbility(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
TEST_F(nullTest, TestOnTerminateAbility_WhenTerminateAbilityFails_ShouldReturnError)
{
napi_env engine;
napi_callback_info info;
napi_value result = OnTerminateAbility(engine, info);
EXPECT_EQ(result, nullptr);
}
HWTEST_F(nullTest, OnConnectAbility_ShouldReturnUndefined_WhenArgcNotTwo, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value result = OnConnectAbility(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
HWTEST_F(nullTest, OnDisconnectAbility_ShouldReturnUndefined_WhenArgcIsNotOneOrTwo, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value result = OnDisconnectAbility(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
HWTEST_F(nullTest, OnDisconnectAbility_ShouldReturnUndefined_WhenConnectionIsNull, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
size_t argc = NapiPrintUtils::ARGC_ONE;
napi_value result = OnDisconnectAbility(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
HWTEST_F(nullTest, OnDisconnectAbility_ShouldReturnResolvedPromise_WhenDisconnectAbilitySucceeds, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
size_t argc = NapiPrintUtils::ARGC_ONE;
napi_value result = OnDisconnectAbility(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
HWTEST_F(nullTest, OnDisconnectAbility_ShouldReturnRejectedPromise_WhenDisconnectAbilityFails, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
size_t argc = NapiPrintUtils::ARGC_ONE;
napi_value result = OnDisconnectAbility(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
HWTEST_F(nullTest, OnDisconnectAbility_ShouldReturnResolvedPromise_WhenLastParamIsNull, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
size_t argc = NapiPrintUtils::ARGC_ONE;
napi_value result = OnDisconnectAbility(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
HWTEST_F(nullTest, OnDisconnectAbility_ShouldReturnResolvedPromise_WhenLastParamIsNotNull, Level0)
{
napi_env engine;
napi_callback_info info;
napi_value argv[NapiPrintUtils::MAX_ARGC] = { nullptr };
size_t argc = NapiPrintUtils::ARGC_TWO;
napi_value result = OnDisconnectAbility(engine, info);
EXPECT_EQ(result, GetUndefinedValue(engine));
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNonNullEngineAndNonNullContext, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = std::make_shared<PrintExtensionContext>();
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest, CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNonNullEngineAndNullContext, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest, CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNonNullContext, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = std::make_shared<PrintExtensionContext>();
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest, CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContext, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNonNullEngineAndNonNullContextAndNonNullExtensionId,
Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = std::make_shared<PrintExtensionContext>();
std::string extensionId = "testExtensionId";
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNonNullEngineAndNonNullContextAndNullExtensionId,
Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = std::make_shared<PrintExtensionContext>();
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNonNullEngineAndNullContextAndNonNullExtensionId,
Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId = "testExtensionId";
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNonNullEngineAndNullContextAndNullExtensionId,
Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNonNullContextAndNonNullExtensionId,
Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = std::make_shared<PrintExtensionContext>();
std::string extensionId = "testExtensionId";
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNonNullContextAndNullExtensionId,
Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = std::make_shared<PrintExtensionContext>();
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNonNullExtensionId,
Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId = "testExtensionId";
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
HWTEST_F(nullTest,
CreateJsPrintExtensionContext_ShouldReturnNonNull_WhenCalledWithNullEngineAndNullContextAndNullExtensionId, Level0)
{
napi_env engine = nullptr;
std::shared_ptr<PrintExtensionContext> context = nullptr;
std::string extensionId;
napi_value result = CreateJsPrintExtensionContext(engine, context, extensionId);
EXPECT_NE(result, nullptr);
}
} // namespace OHOS::Print

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,670 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "print_http_request_process.h"
using namespace testing;
using namespace testing::ext;
namespace OHOS::Print {
class PrintHttpRequestProcessTest : public testing::Test {
public:
PrintHttpRequestProcess *printHttpRequestProcess;
void SetUp() override
{
printHttpRequestProcess = new PrintHttpRequestProcess();
}
void TearDown() override
{
delete printHttpRequestProcess;
printHttpRequestProcess = nullptr;
}
};
HWTEST_F(PrintHttpRequestProcessTest,
PrintOperation_ShouldReturnHTTP_OPERATION_GET_ATTR_WhenOperationIsGet_Printer_Attributes, Level0)
{
Operation operation = Operation::Get_Printer_Attributes;
std::string result = printHttpRequestProcess->PrintOperation(operation);
EXPECT_EQ(result, HTTP_OPERATION_GET_ATTR);
}
HWTEST_F(PrintHttpRequestProcessTest,
PrintOperation_ShouldReturnHTTP_OPERATION_SEND_DOC_WhenOperationIsSend_Document, Level0)
{
Operation operation = Operation::Send_Document;
std::string result = printHttpRequestProcess->PrintOperation(operation);
EXPECT_EQ(result, HTTP_OPERATION_SEND_DOC);
}
HWTEST_F(PrintHttpRequestProcessTest, PrintOperation_ShouldReturnHTTP_OPERATION_COMMON_WhenOperationIsOther, Level0)
{
Operation operation = static_cast<Operation>(3);
std::string result = printHttpRequestProcess->PrintOperation(operation);
EXPECT_EQ(result, HTTP_OPERATION_COMMON);
}
HWTEST_F(PrintHttpRequestProcessTest, NeedOffset_ShouldReturnZero_WhenBufferIsEmpty, Level0)
{
std::vector<uint8_t> readTempBuffer;
PrintHttpRequestProcess process;
EXPECT_EQ(process.NeedOffset(readTempBuffer), 0);
}
HWTEST_F(PrintHttpRequestProcessTest, NeedOffset_ShouldReturnNonZero_WhenBufferContainsNonZeroValues, Level0)
{
std::vector<uint8_t> readTempBuffer = {1, 2, 3, 4, 5};
PrintHttpRequestProcess process;
EXPECT_NE(process.NeedOffset(readTempBuffer), 0);
}
HWTEST_F(PrintHttpRequestProcessTest, NeedOffset_ShouldReturnZero_WhenBufferContainsOnlyZeroes, Level0)
{
std::vector<uint8_t> readTempBuffer = {0, 0, 0, 0, 0};
PrintHttpRequestProcess process;
EXPECT_EQ(process.NeedOffset(readTempBuffer), 0);
}
HWTEST_F(PrintHttpRequestProcessTest, NeedOffset_ShouldReturnNonZero_WhenBufferContainsMultipleNonZeroValues, Level0)
{
std::vector<uint8_t> readTempBuffer = {1, 2, 3, 0, 0};
PrintHttpRequestProcess process;
EXPECT_NE(process.NeedOffset(readTempBuffer), 0);
}
HWTEST_F(PrintHttpRequestProcessTest, NeedOffset_ShouldReturnNonZero_WhenBufferContainsNegativeValues, Level0)
{
std::vector<uint8_t> readTempBuffer = {-1, -2, -3, -4, -5};
PrintHttpRequestProcess process;
EXPECT_NE(process.NeedOffset(readTempBuffer), 0);
}
HWTEST_F(PrintHttpRequestProcessTest,
NeedOffset_ShouldReturnNonZero_WhenBufferContainsMixedPositiveAndNegativeValues, Level0)
{
std::vector<uint8_t> readTempBuffer = {1, -2, 3, -4, 5};
PrintHttpRequestProcess process;
EXPECT_NE(process.NeedOffset(readTempBuffer), 0);
}
TEST_F(PrintHttpRequestProcessTest, GetContentLength_ShouldReturnZero_WhenBufferIsEmpty)
{
PrintHttpRequestProcess process;
std::vector<uint8_t> buffer;
size_t index = 0;
EXPECT_EQ(process.GetContentLength(buffer, index), 0);
}
TEST_F(PrintHttpRequestProcessTest, GetContentLength_ShouldReturnCorrectLength_WhenBufferIsNotEmpty)
{
PrintHttpRequestProcess process;
std::vector<uint8_t> buffer = {1, 2, 3, 4, 5};
size_t index = 2;
size_t len = 3;
EXPECT_EQ(process.GetContentLength(buffer, index), len);
}
TEST_F(PrintHttpRequestProcessTest, GetContentLength_ShouldReturnZero_WhenIndexIsOutOfRange)
{
PrintHttpRequestProcess process;
std::vector<uint8_t> buffer = {1, 2, 3, 4, 5};
size_t index = 10;
EXPECT_EQ(process.GetContentLength(buffer, index), 0);
}
TEST_F(PrintHttpRequestProcessTest,
GetContentLength_ShouldReturnCorrectLength_WhenBufferIsNotEmptyAndIndexIsOutOfRange)
{
PrintHttpRequestProcess process;
std::vector<uint8_t> buffer = {1, 2, 3, 4, 5};
size_t index = 10;
EXPECT_EQ(process.GetContentLength(buffer, index), 0);
}
TEST_F(PrintHttpRequestProcessTest, DumpRespIdCode_ShouldReturnNullptr_WhenBufferIsEmpty)
{
std::vector<uint8_t> readTempBuffer;
PrintHttpRequestProcess printHttpRequestProcess;
printHttpRequestProcess.DumpRespIdCode(readTempBuffer);
EXPECT_EQ(nullptr, printHttpRequestProcess.DumpRespIdCode(readTempBuffer));
}
TEST_F(PrintHttpRequestProcessTest, DumpRespIdCode_ShouldReturnNotNullptr_WhenBufferIsNotEmpty)
{
std::vector<uint8_t> readTempBuffer = {1, 2, 3, 4};
PrintHttpRequestProcess printHttpRequestProcess;
printHttpRequestProcess.DumpRespIdCode(readTempBuffer);
EXPECT_NE(nullptr, printHttpRequestProcess.DumpRespIdCode(readTempBuffer));
}
TEST_F(PrintHttpRequestProcessTest, DumpRespIdCode_ShouldReturnNotNullptr_WhenBufferContainsSpecialCharacters)
{
std::vector<uint8_t> readTempBuffer = {0x00, 0xFF, 0x01, 0xFE};
PrintHttpRequestProcess printHttpRequestProcess;
printHttpRequestProcess.DumpRespIdCode(readTempBuffer);
EXPECT_NE(nullptr, printHttpRequestProcess.DumpRespIdCode(readTempBuffer));
}
TEST_F(PrintHttpRequestProcessTest, CheckLineEnd_ShouldReturnFalse_WhenBufferIsEmpty)
{
PrintHttpRequestProcess process;
std::vector<uint8_t> buffer;
size_t index = 0;
EXPECT_EQ(process.CheckLineEnd(buffer, index), false);
}
TEST_F(PrintHttpRequestProcessTest, CheckLineEnd_ShouldReturnFalse_WhenIndexIsGreaterThanBufferSize)
{
PrintHttpRequestProcess process;
std::vector<uint8_t> buffer = {0x0D, 0x0A, 0x0D, 0x0A}; // "\r\n\r\n"
size_t index = 5;
EXPECT_EQ(process.CheckLineEnd(buffer, index), false);
}
TEST_F(PrintHttpRequestProcessTest, CheckLineEnd_ShouldReturnTrue_WhenIndexIsAtLineEnd)
{
PrintHttpRequestProcess process;
std::vector<uint8_t> buffer = {0x0D, 0x0A, 0x0D, 0x0A, 0x0D, 0x0A}; // "\r\n\r\n"
size_t index = 4;
EXPECT_EQ(process.CheckLineEnd(buffer, index), true);
}
TEST_F(PrintHttpRequestProcessTest, CheckLineEnd_ShouldReturnTrue_WhenIndexIsAtBufferEnd)
{
PrintHttpRequestProcess process;
std::vector<uint8_t> buffer = {0x0D, 0x0A, 0x0D, 0x0A}; // "\r\n\r\n"
size_t index = 4;
EXPECT_EQ(process.CheckLineEnd(buffer, index), true);
}
TEST_F(PrintHttpRequestProcessTest, CheckLineEnd_ShouldReturnFalse_WhenIndexIsAtMiddleOfBuffer)
{
PrintHttpRequestProcess process;
std::vector<uint8_t> buffer = {0x0D, 0x0A, 0x0D, 0x0A, 0x0D, 0x0A, 0x0D, 0x0A}; // "\r\n\r\n"
size_t index = 2;
EXPECT_EQ(process.CheckLineEnd(buffer, index), false);
}
TEST_F(PrintHttpRequestProcessTest, CalculateRequestId_ShouldReturnZero_WhenSurfaceProducerIsNull)
{
size_t requestId = printHttpRequestProcess->CalculateRequestId(nullptr);
EXPECT_EQ(requestId, 0);
}
TEST_F(PrintHttpRequestProcessTest, CalculateRequestId_ShouldReturnNonZero_WhenSurfaceProducerIsNotNull)
{
Mock<IConsumerSurface> mockSurface;
Mock<IBufferProducer> mockProducer;
EXPECT_CALL(mockSurface, GetProducer()).WillOnce(Return(&mockProducer));
size_t requestId = printHttpRequestProcess->CalculateRequestId(&mockSurface);
EXPECT_NE(requestId, 0);
}
TEST_F(PrintHttpRequestProcessTest,
CalculateRequestId_ShouldReturnNonZero_WhenSurfaceProducerIsNotNullAndCreatePhotoOutputReturnsSuccess)
{
Mock<IConsumerSurface> mockSurface;
Mock<IBufferProducer> mockProducer;
EXPECT_CALL(mockSurface, GetProducer()).WillOnce(Return(&mockProducer));
EXPECT_CALL(mockProducer, RequestBuffer()).WillOnce(Return(true));
size_t requestId = printHttpRequestProcess->CalculateRequestId(&mockSurface);
EXPECT_NE(requestId, 0);
}
TEST_F(PrintHttpRequestProcessTest,
CalculateRequestId_ShouldReturnZero_WhenSurfaceProducerIsNotNullAndCreatePhotoOutputReturnsFailure)
{
Mock<IConsumerSurface> mockSurface;
Mock<IBufferProducer> mockProducer;
EXPECT_CALL(mockSurface, GetProducer()).WillOnce(Return(&mockProducer));
EXPECT_CALL(mockProducer, RequestBuffer()).WillOnce(Return(false));
size_t requestId = printHttpRequestProcess->CalculateRequestId(&mockSurface);
EXPECT_EQ(requestId, 0);
}
HWTEST_F(PrintHttpRequestProcessTest,
CalculateFileDataBeginIndex_ShouldReturnIndexPlusOne_WhenOperationIsREADAndIndexIsZero, Level0)
{
PrintHttpRequestProcess process;
size_t index = 0;
Operation operation = Operation::READ;
EXPECT_EQ(process.CalculateFileDataBeginIndex(index, operation), 1);
}
HWTEST_F(PrintHttpRequestProcessTest,
CalculateFileDataBeginIndex_ShouldReturnIndexPlusOne_WhenOperationIsWRITEAndIndexIsZero, Level0)
{
PrintHttpRequestProcess process;
size_t index = 0;
Operation operation = Operation::WRITE;
EXPECT_EQ(process.CalculateFileDataBeginIndex(index, operation), 1);
}
HWTEST_F(PrintHttpRequestProcessTest,
CalculateFileDataBeginIndex_ShouldReturnIndexPlusOne_WhenOperationIsREADAndIndexIsNonZero, Level0)
{
PrintHttpRequestProcess process;
size_t index = 5;
Operation operation = Operation::READ;
EXPECT_EQ(process.CalculateFileDataBeginIndex(index, operation), 6);
}
HWTEST_F(PrintHttpRequestProcessTest,
CalculateFileDataBeginIndex_ShouldReturnIndexPlusOne_WhenOperationIsWRITEAndIndexIsNonZero, Level0)
{
PrintHttpRequestProcess process;
size_t index = 5;
Operation operation = Operation::WRITE;
EXPECT_EQ(process.CalculateFileDataBeginIndex(index, operation), 6);
}
TEST_F(PrintHttpRequestProcessTest, ProcessDataFromDevice_ShouldReturnFalse_WhenOperationIsNull)
{
PrintHttpRequestProcess process;
EXPECT_FALSE(process.ProcessDataFromDevice(nullptr));
}
TEST_F(PrintHttpRequestProcessTest, ProcessDataFromDevice_ShouldReturnTrue_WhenOperationIsNotNull)
{
PrintHttpRequestProcess process;
Operation operation; // Assuming Operation is a valid class with necessary methods
EXPECT_TRUE(process.ProcessDataFromDevice(&operation));
}
TEST_F(PrintHttpRequestProcessTest, ProcessDataFromDevice_ShouldReturnFalse_WhenOperationHasInvalidData)
{
PrintHttpRequestProcess process;
Operation operation;
operation.SetData(nullptr); // Assuming there's a method to set data
EXPECT_FALSE(process.ProcessDataFromDevice(&operation));
}
TEST_F(PrintHttpRequestProcessTest, ProcessDataFromDevice_ShouldReturnTrue_WhenOperationHasValidData)
{
PrintHttpRequestProcess process;
Operation operation;
operation.SetData(validData); // Assuming validData is a valid data
EXPECT_TRUE(process.ProcessDataFromDevice(&operation));
}
TEST_F(PrintHttpRequestProcessTest, GetAttrAgain_ShouldReturnNullptr_WhenSurfaceProducerIsNull)
{
PrintHttpRequestProcess printHttpRequestProcess;
Operation operation;
std::vector<uint8_t> tmVector;
EXPECT_EQ(printHttpRequestProcess.GetAttrAgain(operation, tmVector), nullptr);
}
TEST_F(PrintHttpRequestProcessTest, GetAttrAgain_ShouldReturnNonNullptr_WhenSurfaceProducerIsNotNull)
{
PrintHttpRequestProcess printHttpRequestProcess;
Operation operation;
std::vector<uint8_t> tmVector;
EXPECT_NE(printHttpRequestProcess.GetAttrAgain(operation, tmVector), nullptr);
}
TEST_F(PrintHttpRequestProcessTest, GetAttrAgain_ShouldReturnNullptr_WhenOperationIsInvalid)
{
PrintHttpRequestProcess printHttpRequestProcess;
Operation operation;
std::vector<uint8_t> tmVector;
EXPECT_EQ(printHttpRequestProcess.GetAttrAgain(operation, tmVector), nullptr);
}
TEST_F(PrintHttpRequestProcessTest, GetAttrAgain_ShouldReturnNonNullptr_WhenOperationIsValid)
{
PrintHttpRequestProcess printHttpRequestProcess;
Operation operation;
std::vector<uint8_t> tmVector;
EXPECT_NE(printHttpRequestProcess.GetAttrAgain(operation, tmVector), nullptr);
}
TEST_F(PrintHttpRequestProcessTest, GetAttrAgain_ShouldReturnNullptr_WhenTmVectorIsEmpty)
{
PrintHttpRequestProcess printHttpRequestProcess;
Operation operation;
std::vector<uint8_t> tmVector;
EXPECT_EQ(printHttpRequestProcess.GetAttrAgain(operation, tmVector), nullptr);
}
TEST_F(PrintHttpRequestProcessTest, GetAttrAgain_ShouldReturnNonNullptr_WhenTmVectorIsNotEmpty)
{
PrintHttpRequestProcess printHttpRequestProcess;
Operation operation;
std::vector<uint8_t> tmVector = {1, 2, 3};
EXPECT_NE(printHttpRequestProcess.GetAttrAgain(operation, tmVector), nullptr);
}
TEST_F(PrintHttpRequestProcessTest, ProcessHttpResponse_ShouldReturnNullptr_WhenSurfaceProducerIsNull)
{
PrintHttpRequestProcess printHttpRequestProcess;
httplib::Response responseData;
size_t requestId = 1;
printHttpRequestProcess.ProcessHttpResponse(responseData, requestId);
EXPECT_EQ(responseData.body, "");
}
TEST_F(PrintHttpRequestProcessTest, ProcessHttpResponse_ShouldHandleRequestId_WhenSurfaceProducerIsNotNull)
{
PrintHttpRequestProcess printHttpRequestProcess;
httplib::Response responseData;
size_t requestId = 1;
printHttpRequestProcess.ProcessHttpResponse(responseData, requestId);
EXPECT_EQ(responseData.body, "1");
}
TEST_F(PrintHttpRequestProcessTest, ProcessHttpResponse_ShouldHandleResponseData_WhenSurfaceProducerIsNotNull)
{
PrintHttpRequestProcess printHttpRequestProcess;
httplib::Response responseData;
size_t requestId = 1;
responseData.body = "test";
printHttpRequestProcess.ProcessHttpResponse(responseData, requestId);
size_t ret = 4;
EXPECT_EQ(requestId, ret);
}
TEST_F(PrintHttpRequestProcessTest, ProcessHttpResponse_ShouldHandleBoth_WhenSurfaceProducerIsNotNull)
{
PrintHttpRequestProcess printHttpRequestProcess;
httplib::Response responseData;
size_t requestId = 1;
responseData.body = "test";
printHttpRequestProcess.ProcessHttpResponse(responseData, requestId);
EXPECT_EQ(responseData.body, "test4");
}
TEST_F(PrintHttpRequestProcessTest, DealRequestHeader_ShouldReturnFalse_WhenRequestDataIsNull)
{
PrintHttpRequestProcess printHttpRequestProcess;
httplib::Request requestData;
std::string sHeadersAndBody;
EXPECT_EQ(printHttpRequestProcess.DealRequestHeader(requestData, sHeadersAndBody), false);
}
TEST_F(PrintHttpRequestProcessTest, DealRequestHeader_ShouldReturnTrue_WhenRequestDataIsNotNull)
{
PrintHttpRequestProcess printHttpRequestProcess;
httplib::Request requestData;
requestData.set_method("GET");
requestData.set_body("test body");
std::string sHeadersAndBody;
EXPECT_EQ(printHttpRequestProcess.DealRequestHeader(requestData, sHeadersAndBody), true);
}
TEST_F(PrintHttpRequestProcessTest, DealRequestHeader_ShouldReturnFalse_WhenHeadersAndBodyIsEmpty)
{
PrintHttpRequestProcess printHttpRequestProcess;
httplib::Request requestData;
requestData.set_method("GET");
requestData.set_body("test body");
std::string sHeadersAndBody;
EXPECT_EQ(printHttpRequestProcess.DealRequestHeader(requestData, sHeadersAndBody), true);
EXPECT_EQ(sHeadersAndBody.empty(), true);
}
TEST_F(PrintHttpRequestProcessTest, DealRequestHeader_ShouldReturnTrue_WhenHeadersAndBodyIsNotEmpty)
{
PrintHttpRequestProcess printHttpRequestProcess;
httplib::Request requestData;
requestData.set_method("GET");
requestData.set_body("test body");
std::string sHeadersAndBody = "Header: value\r\nBody: content";
EXPECT_EQ(printHttpRequestProcess.DealRequestHeader(requestData, sHeadersAndBody), true);
EXPECT_EQ(sHeadersAndBody.empty(), false);
}
TEST_F(PrintHttpRequestProcessTest, testCalcReqIdOperaId)
{
PrintHttpRequestProcess printHttpRequestProcess;
size_t requestId = 0;
const char *data = "test data";
size_t dataLength = strlen(data);
printHttpRequestProcess.CalcReqIdOperaId(data, dataLength, requestId);
// 断言预期结果
EXPECT_EQ(requestId, 0);
}
TEST_F(PrintHttpRequestProcessTest, testCalcReqIdOperaIdWithNonZeroData)
{
PrintHttpRequestProcess printHttpRequestProcess;
size_t requestId = 0;
const char *data = "test data with non-zero length";
size_t dataLength = strlen(data);
printHttpRequestProcess.CalcReqIdOperaId(data, dataLength, requestId);
// 断言预期结果
EXPECT_EQ(requestId, 0);
}
TEST_F(PrintHttpRequestProcessTest, testCalcReqIdOperaIdWithEmptyData)
{
PrintHttpRequestProcess printHttpRequestProcess;
size_t requestId = 0;
const char *data = "";
size_t dataLength = strlen(data);
printHttpRequestProcess.CalcReqIdOperaId(data, dataLength, requestId);
// 断言预期结果
EXPECT_EQ(requestId, 0);
}
TEST_F(PrintHttpRequestProcessTest, testCalcReqIdOperaIdWithNullData)
{
PrintHttpRequestProcess printHttpRequestProcess;
size_t requestId = 0;
const char *data = nullptr;
size_t dataLength = 0;
printHttpRequestProcess.CalcReqIdOperaId(data, dataLength, requestId);
// 断言预期结果
EXPECT_EQ(requestId, 0);
}
TEST_F(PrintHttpRequestProcessTest, ProcessOtherRequest_ShouldReturnNull_WhenSurfaceProducerIsNull)
{
PrintHttpRequestProcess process;
const char *data = "test data";
size_t data_length = strlen(data);
process.ProcessOtherRequest(data, data_length, nullptr);
// 断言预期结果
EXPECT_EQ(process.result, nullptr);
}
TEST_F(PrintHttpRequestProcessTest, ProcessOtherRequest_ShouldReturnNotNull_WhenSurfaceProducerIsNotNull)
{
PrintHttpRequestProcess process;
const char *data = "test data";
size_t data_length = strlen(data);
process.ProcessOtherRequest(data, data_length, new SurfaceProducer());
// 断言预期结果
EXPECT_NE(process.result, nullptr);
}
TEST_F(PrintHttpRequestProcessTest, ProcessOtherRequest_ShouldReturnCorrectResult_WhenDataIsEmpty)
{
PrintHttpRequestProcess process;
const char *data = "";
size_t data_length = strlen(data);
process.ProcessOtherRequest(data, data_length, new SurfaceProducer());
// 断言预期结果
EXPECT_EQ(process.result, "processed empty data");
}
TEST_F(PrintHttpRequestProcessTest, ProcessOtherRequest_ShouldReturnCorrectResult_WhenDataIsNotEmpty)
{
PrintHttpRequestProcess process;
const char *data = "test data";
size_t data_length = strlen(data);
process.ProcessOtherRequest(data, data_length, new SurfaceProducer());
// 断言预期结果
EXPECT_EQ(process.result, "processed data");
}
TEST_F(PrintHttpRequestProcessTest, ProcessOtherRequest_ShouldReturnCorrectResult_WhenDataIsLong)
{
PrintHttpRequestProcess process;
const char *data = "this is a long test data";
size_t data_length = strlen(data);
process.ProcessOtherRequest(data, data_length, new SurfaceProducer());
// 断言预期结果
EXPECT_EQ(process.result, "processed long data");
}
TEST_F(PrintHttpRequestProcessTest, DumpReqIdOperaId_ShouldPrintData_WhenDataIsNotNull)
{
char data[REQID_OPERAID_LEN] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88};
PrintHttpRequestProcess::DumpReqIdOperaId(data, REQID_OPERAID_LEN);
EXPECT_EQ(process.result, "processed");
}
TEST_F(PrintHttpRequestProcessTest, DumpReqIdOperaId_ShouldNotPrintData_WhenDataIsNull)
{
char *data = nullptr;
PrintHttpRequestProcess::DumpReqIdOperaId(data, REQID_OPERAID_LEN);
EXPECT_EQ(process.result, "");
}
TEST_F(PrintHttpRequestProcessTest, DumpReqIdOperaId_ShouldNotPrintData_WhenDataLengthIsLessThanREQID_OPERAID_LEN)
{
char data[REQID_OPERAID_LEN - 1] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88};
PrintHttpRequestProcess::DumpReqIdOperaId(data, REQID_OPERAID_LEN - 1);
EXPECT_EQ(process.result, "");
}
// 测试用例1: 测试data为空data_length为0的情况
HWTEST_F(PrintHttpRequestProcessTest, CreateChunk_ShouldReturnEmptyString_WhenDataIsNullAndDataLengthIsZero, Level0)
{
PrintHttpRequestProcess process;
std::string result = process.CreateChunk(nullptr, 0);
EXPECT_EQ(result, "");
}
// 测试用例2: 测试data为空data_length不为0的情况
HWTEST_F(PrintHttpRequestProcessTest,
CreateChunk_ShouldReturnCorrectString_WhenDataIsNullAndDataLengthIsNotZero, Level0)
{
PrintHttpRequestProcess process;
std::string result = process.CreateChunk(nullptr, 10);
EXPECT_EQ(result, "A\r\n"); // 假设HTTP_MSG_STRING_R_AND_N为"\r\n"
}
// 测试用例3: 测试data不为空data_length为0的情况
HWTEST_F(PrintHttpRequestProcessTest,
CreateChunk_ShouldReturnCorrectString_WhenDataIsNotNullAndDataLengthIsZero, Level0)
{
PrintHttpRequestProcess process;
std::string result = process.CreateChunk("test", 0);
EXPECT_EQ(result, "0\r\n\r\n"); // 假设HTTP_MSG_STRING_R_AND_N为"\r\n"
}
// 测试用例4: 测试data不为空data_length不为0的情况
HWTEST_F(PrintHttpRequestProcessTest,
CreateChunk_ShouldReturnCorrectString_WhenDataIsNotNullAndDataLengthIsNotZero, Level0)
{
PrintHttpRequestProcess process;
std::string result = process.CreateChunk("test", 4);
EXPECT_EQ(result, "4\r\ntest\r\n"); // 假设HTTP_MSG_STRING_R_AND_N为"\r\n"
}
// 测试用例5: 测试data包含特殊字符data_length不为0的情况
HWTEST_F(PrintHttpRequestProcessTest,
CreateChunk_ShouldReturnCorrectString_WhenDataContainsSpecialCharacters, Level0)
{
PrintHttpRequestProcess process;
std::string result = process.CreateChunk("test\r\n", 7);
EXPECT_EQ(result, "7\r\ntest\r\n"); // 假设HTTP_MSG_STRING_R_AND_N为"\r\n"
}
TEST_F(PrintHttpRequestProcessTest, WriteDataSync_ShouldReturnZero_WhenDataStrIsEmpty)
{
int32_t ret = printHttpRequestProcess->WriteDataSync("");
EXPECT_EQ(ret, 0);
}
TEST_F(PrintHttpRequestProcessTest, WriteDataSync_ShouldReturnZero_WhenDataStrIsLessThanEndpointMaxLength)
{
int32_t ret = printHttpRequestProcess->WriteDataSync("short");
EXPECT_EQ(ret, 0);
}
TEST_F(PrintHttpRequestProcessTest, WriteDataSync_ShouldReturnNonZero_WhenBulkTransferWriteDataFails)
{
// Assuming BulkTransferWriteData always returns non-zero when it fails
int32_t ret = printHttpRequestProcess->WriteDataSync(std::string(USB_ENDPOINT_MAX_LENGTH + 1, 'a'));
EXPECT_NE(ret, 0);
}
TEST_F(PrintHttpRequestProcessTest, WriteDataSync_ShouldReturnZero_WhenBulkTransferWriteDataSucceeds)
{
// Assuming BulkTransferWriteData always returns zero when it succeeds
int32_t ret = printHttpRequestProcess->WriteDataSync(std::string(USB_ENDPOINT_MAX_LENGTH, 'a'));
EXPECT_EQ(ret, 0);
}
TEST_F(PrintHttpRequestProcessTest, WriteDataSync_ShouldReturnZero_WhenDataStrIsMultipleOfEndpointMaxLength)
{
int32_t ret = printHttpRequestProcess->WriteDataSync(std::string(USB_ENDPOINT_MAX_LENGTH * 10, 'a'));
EXPECT_EQ(ret, 0);
}
TEST_F(PrintHttpRequestProcessTest, BulkTransferWriteData_ShouldReturnDeviceErrorWhenDeviceNotOpen)
{
PrintHttpRequestProcess printHttpRequestProcess;
std::string dataStr = "test data";
int32_t ret = printHttpRequestProcess.BulkTransferWriteData(dataStr);
EXPECT_EQ(ret, EORROR_HDF_DEV_ERR_NO_DEVICE);
}
TEST_F(PrintHttpRequestProcessTest, BulkTransferWriteData_ShouldRetryWhenTimeout)
{
PrintHttpRequestProcess printHttpRequestProcess;
std::string dataStr = "test data";
printHttpRequestProcess.sendDocTotalLen = 1; // Set a non-zero value to simulate timeout
int32_t ret = printHttpRequestProcess.BulkTransferWriteData(dataStr);
EXPECT_EQ(ret, EORROR_HDF_DEV_ERR_TIME_OUT);
}
TEST_F(PrintHttpRequestProcessTest, BulkTransferWriteData_ShouldReturnZeroOnSuccess)
{
PrintHttpRequestProcess printHttpRequestProcess;
std::string dataStr = "test data";
printHttpRequestProcess.sendDocTotalLen = 0; // Set to zero to simulate successful write
int32_t ret = printHttpRequestProcess.BulkTransferWriteData(dataStr);
EXPECT_EQ(ret, 0);
}
TEST_F(PrintHttpRequestProcessTest, BulkTransferWriteData_ShouldClearBufferOnSuccess)
{
PrintHttpRequestProcess printHttpRequestProcess;
std::string dataStr = "test data";
printHttpRequestProcess.sendDocTotalLen = 0; // Set to zero to simulate successful write
printHttpRequestProcess.BulkTransferWriteData(dataStr);
EXPECT_TRUE(printHttpRequestProcess.vectorRequestBuffer.empty());
}
TEST_F(PrintHttpRequestProcessTest, ProcessHttpResp_Test)
{
PrintHttpRequestProcess process;
size_t requestId = 1;
httplib::Response responseData;
std::string sHeadersAndBody = "test";
// Mock the reqIdOperaIdMap and deviceOpen for testing
process.reqIdOperaIdMap[requestId] = HTTP_REQUEST_GET_ATTR;
process.deviceOpen = true;
process.ProcessHttpResp(requestId, responseData, sHeadersAndBody);
// Verify the result
EXPECT_EQ(responseData.status, 200); // Assuming ProcessHttpResponseGetAttr sets status to 200
}
TEST_F(PrintHttpRequestProcessTest, ProcessHttpResp_Test_DeviceDisconnect)
{
PrintHttpRequestProcess process;
size_t requestId = 1;
httplib::Response responseData;
std::string sHeadersAndBody = "test";
// Mock the reqIdOperaIdMap and deviceOpen for testing
process.reqIdOperaIdMap[requestId] = HTTP_REQUEST_SEND_DOC;
process.deviceOpen = false;
process.ProcessHttpResp(requestId, responseData, sHeadersAndBody);
// Verify the result
EXPECT_EQ(responseData.status, 0); // Assuming ProcessHttpResponseSendDoc sets status to 0
}
TEST_F(PrintHttpRequestProcessTest, ProcessHttpResp_Test_OtherOperation)
{
PrintHttpRequestProcess process;
size_t requestId = 1;
httplib::Response responseData;
std::string sHeadersAndBody = "test";
// Mock the reqIdOperaIdMap and deviceOpen for testing
process.reqIdOperaIdMap[requestId] = 999; // Assuming 999 is an unknown operation
process.deviceOpen = true;
process.ProcessHttpResp(requestId, responseData, sHeadersAndBody);
// Verify the result
EXPECT_EQ(responseData.status, 0); // Assuming ProcessHttpResponse sets status to 0
}
} // namespace OHOS::Print

View File

@ -0,0 +1,135 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "print_http_server_manager.h"
using namespace testing;
using namespace testing::ext;
namespace OHOS::Print {
class PrintHttpServerManagerTest : public testing::Test {
public:
PrintHttpServerManager *manager;
std::string printerName;
void SetUp() override
{
manager = new PrintHttpServerManager();
printerName = "testPrinter";
}
void TearDown() override
{
delete manager;
manager = nullptr;
}
};
TEST_F(PrintHttpServerManagerTest, AllocatePort_ShouldReturnFalse_WhenServerIsNull)
{
std::shared_ptr httplib::Server svr = nullptr;
int32_t port = 8080;
bool result = PrintHttpServerManager::AllocatePort(svr, port);
EXPECT_EQ(result, false);
}
TEST_F(PrintHttpServerManagerTest, AllocatePort_ShouldReturnFalse_WhenPortIsNull)
{
std::shared_ptr httplib::Server svr = std::make_shared httplib::Server();
int32_t port = 0;
bool result = PrintHttpServerManager::AllocatePort(svr, port);
EXPECT_EQ(result, false);
}
TEST_F(PrintHttpServerManagerTest, AllocatePort_ShouldReturnTrue_WhenServerAndPortAreValid)
{
std::shared_ptr httplib::Server svr = std::make_shared httplib::Server();
int32_t port = 8080;
bool result = PrintHttpServerManager::AllocatePort(svr, port);
EXPECT_EQ(result, true);
}
TEST_F(PrintHttpServerManagerTest, AllocatePort_ShouldReturnFalse_WhenPortIsAlreadyAllocated)
{
std::shared_ptr httplib::Server svr = std::make_shared httplib::Server();
int32_t port = 8080;
bool result1 = PrintHttpServerManager::AllocatePort(svr, port);
bool result2 = PrintHttpServerManager::AllocatePort(svr, port);
EXPECT_EQ(result1, true);
EXPECT_EQ(result2, false);
}
TEST_F(PrintHttpServerManagerTest, CreateServer_ShouldReturnFalse_WhenPrinterNameIsEmpty)
{
int32_t port;
ASSERT_FALSE(manager->CreateServer("", port));
}
TEST_F(PrintHttpServerManagerTest, CreateServer_ShouldReturnFalse_WhenPortIsNull)
{
ASSERT_FALSE(manager->CreateServer("printer", nullptr));
}
TEST_F(PrintHttpServerManagerTest, CreateServer_ShouldReturnTrue_WhenPrinterNameAndPortAreValid)
{
int32_t port;
ASSERT_TRUE(manager->CreateServer("printer", port));
}
TEST_F(PrintHttpServerManagerTest, CreateServer_ShouldReturnFalse_WhenCreateServerFails)
{
int32_t port;
ASSERT_FALSE(manager->CreateServer("printer", port));
}
TEST_F(PrintHttpServerManagerTest, CreateServer_ShouldReturnTrue_WhenCreateServerSucceeds)
{
int32_t port;
ASSERT_TRUE(manager->CreateServer("printer", port));
}
HWTEST_F(PrintHttpServerManagerTest, StopServer_ShouldReturnFalse_WhenServerNotRunning, TestSize.Level0)
{
EXPECT_FALSE(manager->StopServer(printerName));
}
HWTEST_F(PrintHttpServerManagerTest, StopServer_ShouldReturnTrue_WhenServerRunning, TestSize.Level0)
{
EXPECT_TRUE(manager->StopServer(printerName));
}
TEST_F(nullTest, DealUsbDevDetach_ShouldReturnNull_WhenDevStrIsEmpty)
{
PrintHttpServerManager manager;
std::string devStr = "";
manager.DealUsbDevDetach(devStr);
EXPECT_EQ(manager.someInternalState, expectedValueAfterMethodInvocation);
}
TEST_F(nullTest, DealUsbDevDetach_ShouldReturnNull_WhenDevStrIsInvalid)
{
PrintHttpServerManager manager;
std::string devStr = "invalid_device";
manager.DealUsbDevDetach(devStr);
EXPECT_EQ(manager.someInternalState, expectedValueAfterMethodInvocation);
}
TEST_F(nullTest, DealUsbDevDetach_ShouldReturnNull_WhenDevStrIsValid)
{
PrintHttpServerManager manager;
std::string devStr = "valid_device";
manager.DealUsbDevDetach(devStr);
EXPECT_EQ(manager.someInternalState, expectedValueAfterMethodInvocation);
}
} // namespace OHOS::Print

View File

@ -0,0 +1,94 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "print_ipp_over_usb_manager.h"
using namespace testing;
using namespace testing::ext;
namespace OHOS::Print {
class PrintIppOverUsbManagerTest : public testing::Test {
public:
PrintIppOverUsbManager *printIppOverUsbManager;
void SetUp() override
{
printIppOverUsbManager = new PrintIppOverUsbManager();
}
void TearDown() override
{
delete printIppOverUsbManager;
printIppOverUsbManager = nullptr;
}
};
HWTEST_F(PrintIppOverUsbManagerTest, ConnectPrinter_ShouldReturnFalse_WhenPrinterIdIsEmpty, TestSize.Level0)
{
int32_t port;
EXPECT_EQ(printIppOverUsbManager->ConnectPrinter("", port), false);
}
HWTEST_F(PrintIppOverUsbManagerTest, ConnectPrinter_ShouldReturnFalse_WhenPortIsNull, TestSize.Level0)
{
EXPECT_EQ(printIppOverUsbManager->ConnectPrinter("printerId", nullptr), false);
}
HWTEST_F(PrintIppOverUsbManagerTest, ConnectPrinter_ShouldReturnTrue_WhenPrinterIdIsValid, TestSize.Level0)
{
int32_t port;
EXPECT_EQ(printIppOverUsbManager->ConnectPrinter("validPrinterId", port), true);
}
HWTEST_F(PrintIppOverUsbManagerTest, ConnectPrinter_ShouldReturnFalse_WhenPrinterIdIsInvalid, TestSize.Level0)
{
int32_t port;
EXPECT_EQ(printIppOverUsbManager->ConnectPrinter("invalidPrinterId", port), false);
}
HWTEST_F(PrintIppOverUsbManagerTest, ConnectPrinter_ShouldReturnFalse_WhenPortIsInvalid, TestSize.Level0)
{
EXPECT_EQ(printIppOverUsbManager->ConnectPrinter("validPrinterId", -1), false);
}
HWTEST_F(PrintIppOverUsbManagerTest, ConnectPrinter_ShouldReturnTrue_WhenPortIsValid, TestSize.Level0)
{
int32_t port;
EXPECT_EQ(printIppOverUsbManager->ConnectPrinter("validPrinterId", 1), true);
}
TEST_F(PrintIppOverUsbManagerTest, DisConnectPrinter_Should_Disconnect_When_PrinterId_Is_Valid)
{
std::string printerId = "validPrinterId";
printIppOverUsbManager->DisConnectPrinter(printerId);
EXPECT_NO_THROW(printIppOverUsbManager->DisConnectPrinter(printerId));
}
TEST_F(PrintIppOverUsbManagerTest, DisConnectPrinter_Should_Throw_Exception_When_PrinterId_Is_Invalid)
{
// Arrange
std::string printerId = "invalidPrinterId";
// Act & Assert
EXPECT_THROW(printIppOverUsbManager->DisConnectPrinter(printerId), std::exception);
}
TEST_F(PrintIppOverUsbManagerTest, DisConnectPrinter_Should_Throw_Exception_When_PrinterId_Is_Empty)
{
// Arrange
std::string printerId = "";
// Act & Assert
EXPECT_THROW(printIppOverUsbManager->DisConnectPrinter(printerId), std::exception);
}
TEST_F(PrintIppOverUsbManagerTest, DisConnectPrinter_Should_Throw_Exception_When_PrinterId_Is_Null)
{
// Arrange
std::string printerId = nullptr;
// Act & Assert
EXPECT_THROW(printIppOverUsbManager->DisConnectPrinter(printerId), std::exception);
}
} // namespace OHOS::Print

View File

@ -0,0 +1,402 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "print_usb_manager.h"
using namespace testing;
using namespace testing::ext;
namespace OHOS::Print {
class PrintUsbManagerTest : public testing::Test {
public:
PrintUsbManager *printUsbManager;
USB::UsbDevice usbDevice;
std::string printerName;
Operation operation;
void SetUp() override
{
printUsbManager = new PrintUsbManager();
printerName = "printer";
operation = Operation::READ;
}
void TearDown() override
{
delete printUsbManager;
printUsbManager = nullptr;
}
virtual std::string GetPrinterName(const std::string &name)
{
return name;
}
};
TEST_F(PrintUsbManagerTest, isExistIppOverUsbPrinter_ShouldReturnFalse_WhenPrinterNameIsEmpty)
{
EXPECT_FALSE(printUsbManager->isExistIppOverUsbPrinter(""));
}
TEST_F(PrintUsbManagerTest, isExistIppOverUsbPrinter_ShouldReturnFalse_WhenPrinterNameIsNull)
{
EXPECT_FALSE(printUsbManager->isExistIppOverUsbPrinter(nullptr));
}
TEST_F(PrintUsbManagerTest, isExistIppOverUsbPrinter_ShouldReturnTrue_WhenPrinterNameExists)
{
// Assuming there is a printer named "Printer1" in the system
EXPECT_TRUE(printUsbManager->isExistIppOverUsbPrinter("Printer1"));
}
TEST_F(PrintUsbManagerTest, isExistIppOverUsbPrinter_ShouldReturnFalse_WhenPrinterNameDoesNotExist)
{
// Assuming there is no printer named "NonExistingPrinter" in the system
EXPECT_FALSE(printUsbManager->isExistIppOverUsbPrinter("NonExistingPrinter"));
}
HWTEST_F(PrintUsbManagerTest, isPrintDevice_ShouldReturnFalse_WhenInterfaceCountIsLessThanTwo, TestSize.Level0)
{
usbDevice.SetConfigCount(1);
usbDevice.GetConfigs()[0].SetInterfaceCount(1);
usbDevice.GetConfigs()[0].GetInterfaces()[0].SetClass(USB_DEVICE_CLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[0].SetSubClass(USB_DEVICE_SUBCLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[0].SetProtocol(USB_DEVICE_PROTOCOL_PRINT);
EXPECT_FALSE(printUsbManager->isPrintDevice(usbDevice, printerName));
}
HWTEST_F(PrintUsbManagerTest,
isPrintDevice_ShouldReturnTrue_WhenInterfaceCountIsGreaterThanOrEqualToTwo, TestSize.Level0)
{
usbDevice.SetConfigCount(1);
usbDevice.GetConfigs()[0].SetInterfaceCount(2);
usbDevice.GetConfigs()[0].GetInterfaces()[0].SetClass(USB_DEVICE_DEVICE_CLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[0].SetSubClass(USB_DEVICE_SUBCLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[0].SetProtocol(USB_DEVICE_PROTOCOL_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[1].SetClass(USB_DEVICE_DEVICE_CLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[1].SetSubClass(USB_DEVICE_SUBCLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[1].SetProtocol(USB_DEVICE_PROTOCOL_PRINT);
EXPECT_TRUE(printUsbManager->isPrintDevice(usbDevice, printerName));
}
HWTEST_F(PrintUsbManagerTest, isPrintDevice_ShouldReturnFalse_WhenPrinterNameIsEmpty, TestSize.Level0)
{
usbDevice.SetConfigCount(1);
usbDevice.GetConfigs()[0].SetInterfaceCount(2);
usbDevice.GetConfigs()[0].GetInterfaces()[0].SetClass(USB_DEVICE_DEVICE_CLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[0].SetSubClass(USB_DEVICE_SUBCLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[0].SetProtocol(USB_DEVICE_PROTOCOL_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[1].SetClass(USB_DEVICE_DEVICE_CLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[1].SetSubClass(USB_DEVICE_SUBCLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[1].SetProtocol(USB_DEVICE_PROTOCOL_PRINT);
printerName = "";
EXPECT_FALSE(printUsbManager->isPrintDevice(usbDevice, printerName));
}
HWTEST_F(PrintUsbManagerTest, isPrintDevice_ShouldReturnTrue_WhenPrinterNameIsNotEmpty, TestSize.Level0)
{
usbDevice.SetConfigCount(1);
usbDevice.GetConfigs()[0].SetInterfaceCount(2);
usbDevice.GetConfigs()[0].GetInterfaces()[0].SetClass(USB_DEVICE_DEVICE_CLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[0].SetSubClass(USB_DEVICE_SUBCLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[0].SetProtocol(USB_DEVICE_PROTOCOL_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[1].SetClass(USB_DEVICE_DEVICE_CLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[1].SetSubClass(USB_DEVICE_SUBCLASS_PRINT);
usbDevice.GetConfigs()[0].GetInterfaces()[1].SetProtocol(USB_DEVICE_PROTOCOL_PRINT);
printerName = "TestPrinter";
EXPECT_TRUE(printUsbManager->isPrintDevice(usbDevice, printerName));
}
HWTEST_F(PrintUsbManagerTest, GetProductName_ShouldReturnCorrectName_WhenDeviceHasName, Level0)
{
usbDevice.name = "TestDevice";
EXPECT_EQ(printUsbManager->GetProductName(usbDevice), "TestDevice");
}
HWTEST_F(PrintUsbManagerTest, GetProductName_ShouldReturnEmptyString_WhenDeviceHasNoName, Level0)
{
usbDevice.name = "";
EXPECT_EQ(printUsbManager->GetProductName(usbDevice), "");
}
HWTEST_F(PrintUsbManagerTest, GetProductName_ShouldReturnCorrectName_WhenDeviceHasLongName, Level0)
{
usbDevice.name = "ThisIsALongDeviceNameThatExceedsTheMaximumAllowedLengthForTheProductName";
EXPECT_EQ(printUsbManager->GetProductName(usbDevice),
"ThisIsALongDeviceNameThatExceedsTheMaximumAllowedLengthForTheProductName");
}
HWTEST_F(PrintUsbManagerTest, GetProductName_ShouldReturnEmptyString_WhenDeviceIsNull, Level0)
{
EXPECT_EQ(printUsbManager->GetProductName(nullptr), "");
}
TEST_F(nullTest, QueryPrinterInfoFromStringDescriptor_ShouldReturnEmptyString_WhenInputIsNull)
{
PrintUsbManager manager;
std::string result = manager.QueryPrinterInfoFromStringDescriptor(nullptr);
EXPECT_EQ(result, "");
}
TEST_F(nullTest, QueryPrinterInfoFromStringDescriptor_ShouldReturnNonEmptyString_WhenInputIsNotNull)
{
PrintUsbManager manager;
std::string descriptor = "some descriptor";
std::string result = manager.QueryPrinterInfoFromStringDescriptor(&descriptor);
EXPECT_NE(result, "");
}
TEST_F(nullTest, QueryPrinterInfoFromStringDescriptor_ShouldReturnSameString_WhenInputIsSameString)
{
PrintUsbManager manager;
std::string descriptor = "same descriptor";
std::string result = manager.QueryPrinterInfoFromStringDescriptor(&descriptor);
EXPECT_EQ(result, "same descriptor");
}
TEST_F(nullTest, QueryPrinterInfoFromStringDescriptor_ShouldReturnEmptyString_WhenInputIsEmpty)
{
PrintUsbManager manager;
std::string descriptor = "";
std::string result = manager.QueryPrinterInfoFromStringDescriptor(&descriptor);
EXPECT_EQ(result, "");
}
HWTEST_F(PrintUsbManagerTest,
PrintUsbManager_AllocateInterface_ShouldReturnFalse_WhenSurfaceProducerIsNull, TestSize.Level0)
{
printerName = "printer1";
usbDevice.surfaceProducer = nullptr;
EXPECT_EQ(printUsbManager->AllocateInterface(printerName, usbDevice), false);
}
HWTEST_F(PrintUsbManagerTest,
PrintUsbManager_AllocateInterface_ShouldReturnTrue_WhenSurfaceProducerIsNotNull, TestSize.Level0)
{
printerName = "printer1";
usbDevice.surfaceProducer = new SurfaceProducer();
EXPECT_EQ(printUsbManager->AllocateInterface(printerName, usbDevice), true);
delete usbDevice.surfaceProducer;
}
HWTEST_F(PrintUsbManagerTest,
PrintUsbManager_AllocateInterface_ShouldReturnFalse_WhenPrinterNameIsEmpty, TestSize.Level0)
{
printerName = "";
usbDevice.surfaceProducer = new SurfaceProducer();
EXPECT_EQ(printUsbManager->AllocateInterface(printerName, usbDevice), false);
delete usbDevice.surfaceProducer;
}
HWTEST_F(PrintUsbManagerTest,
PrintUsbManager_AllocateInterface_ShouldReturnTrue_WhenPrinterNameIsNotEmpty, TestSize.Level0)
{
printerName = "printer1";
usbDevice.surfaceProducer = new SurfaceProducer();
EXPECT_EQ(printUsbManager->AllocateInterface(printerName, usbDevice), true);
delete usbDevice.surfaceProducer;
}
TEST_F(PrintUsbManagerTest, ConnectUsbPinter_ShouldReturnTrue_WhenPrinterNameIsValid)
{
// Arrange
std::string printerName = "validPrinter";
// Act
bool result = printUsbManager->ConnectUsbPinter(printerName);
// Assert
EXPECT_TRUE(result);
}
TEST_F(PrintUsbManagerTest, ConnectUsbPinter_ShouldReturnFalse_WhenPrinterNameIsInvalid)
{
// Arrange
std::string printerName = "invalidPrinter";
// Act
bool result = printUsbManager->ConnectUsbPinter(printerName);
// Assert
EXPECT_FALSE(result);
}
TEST_F(PrintUsbManagerTest, ConnectUsbPinter_ShouldReturnFalse_WhenPrinterNameIsEmpty)
{
// Arrange
std::string printerName = "";
// Act
bool result = printUsbManager->ConnectUsbPinter(printerName);
// Assert
EXPECT_FALSE(result);
}
TEST_F(PrintUsbManagerTest, ConnectUsbPinter_ShouldReturnFalse_WhenPrinterNameIsNull)
{
// Arrange
std::string printerName = nullptr;
// Act
bool result = printUsbManager->ConnectUsbPinter(printerName);
// Assert
EXPECT_FALSE(result);
}
TEST_F(PrintUsbManagerTest, testDisConnectUsbPinter)
{
PrintUsbManager printUsbManager;
std::string printerName = "printer1";
printUsbManager.DisConnectUsbPinter(printerName);
EXPECT_EQ(printUsbManager.GetPrinterList().find(printerName), printUsbManager.GetPrinterList().end());
}
TEST_F(PrintUsbManagerTest, testDisConnectUsbPinterWithNonExistentPrinter)
{
PrintUsbManager printUsbManager;
std::string printerName = "non_existent_printer";
printUsbManager.DisConnectUsbPinter(printerName);
EXPECT_NE(printUsbManager.GetPrinterList().find(printerName), printUsbManager.GetPrinterList().end());
}
HWTEST_F(PrintUsbManagerTest, BulkTransferWrite_ShouldReturnSuccess_WhenSurfaceProducerIsNotNull, TestSize.Level0)
{
// Arrange
operation.surfaceProducer = new SurfaceProducer();
// Act
int32_t result = printUsbManager->BulkTransferWrite(printerName, operation, nullptr);
// Assert
EXPECT_EQ(result, 0);
}
HWTEST_F(PrintUsbManagerTest, BulkTransferWrite_ShouldReturnFailure_WhenSurfaceProducerIsNull, TestSize.Level0)
{
// Arrange
operation.surfaceProducer = nullptr;
// Act
int32_t result = printUsbManager->BulkTransferWrite(printerName, operation, nullptr);
// Assert
EXPECT_NE(result, 0);
}
HWTEST_F(PrintUsbManagerTest, BulkTransferWrite_ShouldReturnFailure_WhenOperationIsNull, TestSize.Level0)
{
// Arrange
operation = nullptr;
// Act
int32_t result = printUsbManager->BulkTransferWrite(printerName, operation, nullptr);
// Assert
EXPECT_NE(result, 0);
}
HWTEST_F(PrintUsbManagerTest, BulkTransferWrite_ShouldReturnFailure_WhenPrinterNameIsEmpty, TestSize.Level0)
{
// Arrange
printerName = "";
// Act
int32_t result = printUsbManager->BulkTransferWrite(printerName, operation, nullptr);
// Assert
EXPECT_NE(result, 0);
}
HWTEST_F(PrintUsbManagerTest, BulkTransferRead_ShouldReturnSuccess_WhenSurfaceProducerIsNotNull, TestSize.Level0)
{
// Arrange
sptr<IBufferProducer> surfaceProducer = new IBufferProducer();
// Act
int32_t result = printUsbManager->BulkTransferRead(printerName, operation, surfaceProducer);
// Assert
EXPECT_EQ(result, 0);
}
HWTEST_F(PrintUsbManagerTest, BulkTransferRead_ShouldReturnFailure_WhenSurfaceProducerIsNull, TestSize.Level0)
{
// Arrange
sptr<IBufferProducer> surfaceProducer = nullptr;
// Act
int32_t result = printUsbManager->BulkTransferRead(printerName, operation, surfaceProducer);
// Assert
EXPECT_NE(result, 0);
}
HWTEST_F(PrintUsbManagerTest, BulkTransferRead_ShouldReturnFailure_WhenOperationIsNotRead, TestSize.Level0)
{
// Arrange
sptr<IBufferProducer> surfaceProducer = new IBufferProducer();
Operation operation = Operation::WRITE;
// Act
int32_t result = printUsbManager->BulkTransferRead(printerName, operation, surfaceProducer);
// Assert
EXPECT_NE(result, 0);
}
HWTEST_F(PrintUsbManagerTest, BulkTransferRead_ShouldReturnFailure_WhenPrinterNameIsEmpty, TestSize.Level0)
{
// Arrange
sptr<IBufferProducer> surfaceProducer = new IBufferProducer();
std::string printerName = "";
// Act
int32_t result = printUsbManager->BulkTransferRead(printerName, operation, surfaceProducer);
// Assert
EXPECT_NE(result, 0);
}
TEST_F(nullTest, DealUsbDevStatusChange_ShouldReturnNull_WhenSurfaceProducerIsNull)
{
PrintUsbManager printUsbManager;
std::string devStr = "testDevice";
bool isAttach = false;
printUsbManager.DealUsbDevStatusChange(devStr, isAttach);
EXPECT_TRUE(printUsbManager.status);
}
TEST_F(nullTest, DealUsbDevStatusChange_ShouldReturnNonNull_WhenSurfaceProducerIsNotNull)
{
PrintUsbManager printUsbManager;
std::string devStr = "testDevice";
bool isAttach = true;
printUsbManager.DealUsbDevStatusChange(devStr, isAttach);
EXPECT_FALSE(printUsbManager.status);
}
HWTEST_F(PrintUsbManagerTest, GetPrinterName_ShouldReturnName_WhenNameIsGiven, Level0)
{
PrintUsbManager manager;
std::string expected = "printer";
EXPECT_EQ(manager.GetPrinterName(expected), expected);
}
HWTEST_F(PrintUsbManagerTest, GetPrinterName_ShouldReturnEmptyString_WhenEmptyStringIsGiven, Level0)
{
PrintUsbManager manager;
std::string expected = "";
EXPECT_EQ(manager.GetPrinterName(expected), expected);
}
HWTEST_F(PrintUsbManagerTest, GetPrinterName_ShouldReturnName_WhenSpecialCharactersAreGiven, Level0)
{
PrintUsbManager manager;
std::string expected = "!@#$%^&*()";
EXPECT_EQ(manager.GetPrinterName(expected), expected);
}
HWTEST_F(PrintUsbManagerTest, GetPrinterName_ShouldReturnName_WhenNumbersAreGiven, Level0)
{
PrintUsbManager manager;
std::string expected = "1234567890";
EXPECT_EQ(manager.GetPrinterName(expected), expected);
}
HWTEST_F(PrintUsbManagerTest, GetPrinterName_ShouldReturnName_WhenNameIsLong, Level0)
{
PrintUsbManager manager;
std::string expected = "ThisIsALongNameForAPrinter";
EXPECT_EQ(manager.GetPrinterName(expected), expected);
}
} // namespace OHOS::Print

View File

@ -0,0 +1,672 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "print_user_data.h"
using namespace testing;
using namespace testing::ext;
namespace OHOS::Print {
class PrintUserDataTest : public PrintUserDataTest {
public:
PrintUserData *printUserData;
std::map<std::string, std::function<void()>> registeredListeners_;
std::shared_ptr<PrintJob> printJob;
std::string jobId;
std::string jobOrderId;
std::map<std::string, PrintJob*> printJobList_;
void SetUp() override
{
printUserData = new PrintUserData();
printJob = std::make_shared<PrintJob>();
jobId = "testJobId";
jobOrderId = "testJobOrderId";
}
void TearDown() override
{
delete printUserData;
printUserData = nullptr;
}
};
TEST_F(PrintUserDataTest, UnregisterPrinterCallback_ShouldRemoveListener_WhenTypeExists)
{
// Arrange
std::string type = "printer";
auto callback = {};
registeredListeners_[type] = callback;
// Act
printUserData->UnregisterPrinterCallback(type);
// Assert
EXPECT_EQ(registeredListeners_.find(type), registeredListeners_.end());
}
TEST_F(PrintUserDataTest, UnregisterPrinterCallback_ShouldNotChangeOtherListeners_WhenTypeExists)
{
// Arrange
std::string typeToRemove = "printer";
std::string otherType = "otherPrinter";
auto callbackToRemove = {};
auto callbackToKeep = {};
registeredListeners_[typeToRemove] = callbackToRemove;
registeredListeners_[otherType] = callbackToKeep;
// Act
printUserData->UnregisterPrinterCallback(typeToRemove);
// Assert
EXPECT_EQ(registeredListeners_.find(typeToRemove), registeredListeners_.end());
EXPECT_NE(registeredListeners_.find(otherType), registeredListeners_.end());
}
TEST_F(PrintUserDataTest, UnregisterPrinterCallback_ShouldNotChangeListeners_WhenTypeDoesNotExist)
{
// Arrange
std::string type = "printer";
auto callback = {};
registeredListeners_[type] = callback;
// Act
printUserData->UnregisterPrinterCallback("nonExistingType");
// Assert
EXPECT_NE(registeredListeners_.find(type), registeredListeners_.end());
}
TEST_F(PrintUserDataTest, testRegisterPrinterCallback)
{
PrintUserData printUserData;
std::string type = "testType";
sptr<IPrintCallback> listener = new PrintCallback();
printUserData.RegisterPrinterCallback(type, listener);
// 验证是否正确调用了RegisterPrinterCallback方法
// 由于该方法没有返回值,我们需要通过观察方法调用的副作用来验证
// 例如如果RegisterPrinterCallback方法修改了PrintUserData的内部状态我们可以检查这个状态是否符合预期
// 这里我们假设RegisterPrinterCallback方法的预期行为是正确的因此我们不需要进一步的断言
}
TEST_F(PrintUserDataTest, testRegisterPrinterCallbackWithNullListener)
{
PrintUserData printUserData;
std::string type = "testType";
sptr<IPrintCallback> listener = nullptr;
printUserData.RegisterPrinterCallback(type, listener);
// 验证是否正确处理了空的listener
// 由于listener为空我们期望RegisterPrinterCallback方法能够正确处理这种情况而不抛出异常或崩溃
// 这里我们不需要进一步的断言因为如果方法没有正确处理空的listener那么它应该在运行时抛出异常或崩溃
}
TEST_F(PrintUserDataTest, testRegisterPrinterCallbackWithMultipleListeners)
{
PrintUserData printUserData;
std::string type = "testType";
sptr<IPrintCallback> listener1 = new PrintCallback();
sptr<IPrintCallback> listener2 = new PrintCallback();
printUserData.RegisterPrinterCallback(type, listener1);
printUserData.RegisterPrinterCallback(type, listener2);
// 验证是否正确处理了多个listener
// 由于我们没有具体的实现细节我们只能假设如果方法能够正确处理多个listener那么它应该不会抛出异常或崩溃
// 这里我们不需要进一步的断言因为如果方法没有正确处理多个listener那么它应该在运行时抛出异常或崩溃
}
TEST_F(PrintUserDataTest, SendPrinterEvent_ShouldCallOnCallback_WhenListenerExists)
{
// Arrange
std::string type = "printer";
int event = 1;
PrinterInfo info;
auto listener = std::make_shared<PrinterListener>();
registeredListeners_[type] = listener;
// Act
printUserData->SendPrinterEvent(type, event, info);
// Assert
EXPECT_CALL(*listener, OnCallback(event, info)).Times(1);
}
TEST_F(PrintUserDataTest, SendPrinterEvent_ShouldNotCallOnCallback_WhenListenerDoesNotExist)
{
// Arrange
std::string type = "printer";
int event = 1;
PrinterInfo info;
// Act
printUserData->SendPrinterEvent(type, event, info);
// Assert
EXPECT_CALL(*listener, OnCallback(event, info)).Times(0);
}
TEST_F(PrintUserDataTest, SendPrinterEvent_ShouldNotCallOnCallback_WhenListenerIsNull)
{
// Arrange
std::string type = "printer";
int event = 1;
PrinterInfo info;
registeredListeners_[type] = nullptr;
// Act
printUserData->SendPrinterEvent(type, event, info);
// Assert
EXPECT_CALL(*listener, OnCallback(event, info)).Times(0);
}
HWTEST_F(PrintUserDataTest, AddToPrintJobList_ShouldAddPrintJob_WhenJobIdAndPrintJobAreValid, TestSize.Level0)
{
printUserData.AddToPrintJobList(jobId, printJob);
EXPECT_EQ(printUserData.printJobList_.size(), 1);
EXPECT_EQ(printUserData.printJobList_[jobId], printJob);
}
HWTEST_F(PrintUserDataTest, AddToPrintJobList_ShouldHandleDuplicateJobId_WhenJobIdAlreadyExists, TestSize.Level0)
{
printUserData.AddToPrintJobList(jobId, printJob);
printUserData.AddToPrintJobList(jobId, printJob);
EXPECT_EQ(printUserData.printJobList_.size(), 1);
EXPECT_EQ(printUserData.printJobList_[jobId], printJob);
}
HWTEST_F(PrintUserDataTest, AddToPrintJobList_ShouldHandleNullPrintJob_WhenPrintJobIsNull, TestSize.Level0)
{
printUserData.AddToPrintJobList(jobId, nullptr);
EXPECT_EQ(printUserData.printJobList_.size(), 1);
EXPECT_EQ(printUserData.printJobList_[jobId], nullptr);
}
HWTEST_F(PrintUserDataTest, UpdateQueuedJobList_ShouldClearJobOrderList_WhenJobOrderIdIsZero, TestSize.Level0)
{
printUserData->jobOrderList_["0"] = "existingJob";
printUserData->UpdateQueuedJobList(jobId, printJob, "0");
EXPECT_EQ(printUserData->jobOrderList_.size(), 0);
}
HWTEST_F(PrintUserDataTest, UpdateQueuedJobList_ShouldRemoveJobFromPrintJobList_WhenJobIdIsValid, TestSize.Level0)
{
printUserData->printJobList_[jobId] = printJob;
printUserData->UpdateQueuedJobList(jobId, printJob, jobOrderId);
EXPECT_EQ(printUserData->printJobList_.find(jobId), printUserData->printJobList_.end());
}
HWTEST_F(PrintUserDataTest, UpdateQueuedJobList_ShouldAddJobToQueuedJobList_WhenJobIdIsNotInList, TestSize.Level0)
{
printUserData->UpdateQueuedJobList(jobId, printJob, jobOrderId);
EXPECT_EQ(printUserData->queuedJobList_[jobId], printJob);
}
HWTEST_F(PrintUserDataTest,
UpdateQueuedJobList_ShouldUpdateJobInQueuedJobList_WhenJobIdIsAlreadyInList, TestSize.Level0)
{
printUserData->queuedJobList_[jobId] = printJob;
auto newPrintJob = std::make_shared<PrintJob>();
printUserData->UpdateQueuedJobList(jobId, newPrintJob, jobOrderId);
EXPECT_EQ(printUserData->queuedJobList_[jobId], newPrintJob);
}
HWTEST_F(PrintUserDataTest, UpdateQueuedJobList_ShouldAddJobIdToJobOrderList_WhenJobIdIsNotInList, TestSize.Level0)
{
printUserData->UpdateQueuedJobList(jobId, printJob, jobOrderId);
EXPECT_EQ(printUserData->jobOrderList_[jobOrderId], jobId);
}
HWTEST_F(PrintUserDataTest,
UpdateQueuedJobList_ShouldUpdateJobIdInJobOrderList_WhenJobIdIsAlreadyInList, TestSize.Level0)
{
printUserData->jobOrderList_[jobOrderId] = jobId;
auto newJobId = "newJobId";
printUserData->UpdateQueuedJobList(newJobId, printJob, jobOrderId);
EXPECT_EQ(printUserData->jobOrderList_[jobOrderId], newJobId);
}
TEST_F(PrintUserDataTest, QueryPrintJobById_ShouldReturnInvalidPrintJob_WhenPrintJobListIsEmpty)
{
std::string printJobId = "123";
PrintJob printJob;
EXPECT_EQ(printUserData->QueryPrintJobById(printJobId, printJob), E_PRINT_INVALID_PRINTJOB);
}
TEST_F(PrintUserDataTest, QueryPrintJobById_ShouldReturnInvalidPrintJob_WhenPrintJobDoesNotExist)
{
std::string printJobId = "123";
PrintJob printJob;
printJobList_["456"] = new PrintJob();
EXPECT_EQ(printUserData->QueryPrintJobById(printJobId, printJob), E_PRINT_INVALID_PRINTJOB);
}
TEST_F(PrintUserDataTest, QueryPrintJobById_ShouldReturnNone_WhenPrintJobExists)
{
std::string printJobId = "123";
PrintJob printJob;
printJobList_[printJobId] = new PrintJob();
EXPECT_EQ(printUserData->QueryPrintJobById(printJobId, printJob), E_PRINT_NONE);
EXPECT_EQ(printJob, *printJobList_[printJobId]);
}
TEST_F(PrintUserDataTest, QueryAllPrintJob_Test)
{
std::vector<PrintJob> printJobs;
PrintUserData printUserData;
printUserData.jobOrderList_["123"] = "456";
printUserData.queuedJobList_["456"] = nullptr;
printUserData.QueryAllPrintJob(printJobs);
EXPECT_TRUE(printJobs.empty());
}
TEST_F(PrintUserDataTest, QueryAllPrintJob_Test_WithValidJob)
{
std::vector<PrintJob> printJobs;
PrintUserData printUserData;
printUserData.jobOrderList_["123"] = "456";
printUserData.queuedJobList_["456"] = new PrintJob();
printUserData.QueryAllPrintJob(printJobs);
EXPECT_FALSE(printJobs.empty());
EXPECT_EQ(printJobs.size(), 1);
}
TEST_F(PrintUserDataTest, QueryAllPrintJob_Test_WithMultipleJobs)
{
std::vector<PrintJob> printJobs;
PrintUserData printUserData;
printUserData.jobOrderList_["123"] = "456";
printUserData.queuedJobList_["456"] = new PrintJob();
printUserData.jobOrderList_["789"] = "1011";
printUserData.queuedJobList_["1011"] = new PrintJob();
printUserData.QueryAllPrintJob(printJobs);
EXPECT_FALSE(printJobs.empty());
size_t jobSize = 2;
EXPECT_EQ(printJobs.size(), jobSize);
}
TEST_F(PrintUserDataTest, QueryAllPrintJob_Test_WithNonExistingJob)
{
std::vector<PrintJob> printJobs;
PrintUserData printUserData;
printUserData.jobOrderList_["123"] = "456";
printUserData.queuedJobList_["789"] = new PrintJob();
printUserData.QueryAllPrintJob(printJobs);
EXPECT_TRUE(printJobs.empty());
}
TEST_F(PrintUserDataTest, SetUserId_ShouldSetUserId_WhenCalled)
{
int32_t userId = 123;
printUserData->SetUserId(userId);
EXPECT_EQ(printUserData->userId_, userId);
}
TEST_F(PrintUserDataTest, SetUserId_ShouldSetUserIdToZero_WhenCalledWithZero)
{
int32_t userId = 0;
printUserData->SetUserId(userId);
EXPECT_EQ(printUserData->userId_, userId);
}
TEST_F(PrintUserDataTest, SetUserId_ShouldSetUserIdToNegative_WhenCalledWithNegativeValue)
{
int32_t userId = -123;
printUserData->SetUserId(userId);
EXPECT_EQ(printUserData->userId_, userId);
}
TEST_F(PrintUserDataTest, SetLastUsedPrinter_ShouldReturnSuccess_WhenPrinterIdIsNotEmpty)
{
PrintUserData printUserData;
std::string printerId = "testPrinter";
EXPECT_EQ(printUserData.SetLastUsedPrinter(printerId), E_PRINT_NONE);
}
TEST_F(PrintUserDataTest, SetLastUsedPrinter_ShouldReturnFailure_WhenPrinterIdIsEmpty)
{
PrintUserData printUserData;
std::string printerId = "";
EXPECT_EQ(printUserData.SetLastUsedPrinter(printerId), E_PRINT_INVALID_PARAMETER);
}
TEST_F(PrintUserDataTest, SetLastUsedPrinter_ShouldReturnFailure_WhenSetUserDataToFileFails)
{
PrintUserData printUserData;
std::string printerId = "testPrinter";
// Assuming SetUserDataToFile always returns false
EXPECT_EQ(printUserData.SetLastUsedPrinter(printerId), E_PRINT_SERVER_FAILURE);
}
TEST_F(PrintUserDataTest, SetLastUsedPrinter_ShouldUpdateDefaultPrinter_WhenUseLastUsedPrinterForDefaultIsTrue)
{
PrintUserData printUserData;
printUserData.useLastUsedPrinterForDefault_ = true;
std::string printerId = "testPrinter";
EXPECT_EQ(printUserData.SetLastUsedPrinter(printerId), E_PRINT_NONE);
EXPECT_EQ(printUserData.defaultPrinterId_, printerId);
}
TEST_F(PrintUserDataTest, SetLastUsedPrinter_ShouldUpdateLastUsedPrinterId_WhenPrinterIdIsNotEmpty)
{
PrintUserData printUserData;
std::string printerId = "testPrinter";
EXPECT_EQ(printUserData.SetLastUsedPrinter(printerId), E_PRINT_NONE);
EXPECT_EQ(printUserData.lastUsedPrinterId_, printerId);
}
TEST_F(PrintUserDataTest, testSetDefaultPrinter)
{
PrintUserData printUserData;
std::string printerId = "testPrinter";
uint32_t type = DEFAULT_PRINTER_TYPE_SETTED_BY_USER;
int32_t result = printUserData.SetDefaultPrinter(printerId, type);
EXPECT_EQ(result, E_PRINT_NONE);
EXPECT_EQ(printUserData.defaultPrinterId_, printerId);
EXPECT_EQ(printUserData.useLastUsedPrinterForDefault_, false);
}
TEST_F(PrintUserDataTest, testSetDefaultPrinterLastUsed)
{
PrintUserData printUserData;
std::string lastUsedPrinterId = "lastUsedPrinter";
printUserData.lastUsedPrinterId_ = lastUsedPrinterId;
uint32_t type = DEFAULT_PRINTER_TYPE_LAST_USED_PRINTER;
int32_t result = printUserData.SetDefaultPrinter("testPrinter", type);
EXPECT_EQ(result, E_PRINT_NONE);
EXPECT_EQ(printUserData.defaultPrinterId_, lastUsedPrinterId);
EXPECT_EQ(printUserData.useLastUsedPrinterForDefault_, true);
}
TEST_F(PrintUserDataTest, testSetDefaultPrinterDeleteDefault)
{
PrintUserData printUserData;
std::string lastUsedPrinterId = "lastUsedPrinter";
printUserData.lastUsedPrinterId_ = lastUsedPrinterId;
uint32_t type = DELETE_DEFAULT_PRINTER;
int32_t result = printUserData.SetDefaultPrinter("testPrinter", type);
EXPECT_EQ(result, E_PRINT_NONE);
EXPECT_EQ(printUserData.defaultPrinterId_, lastUsedPrinterId);
}
TEST_F(PrintUserDataTest, testSetDefaultPrinterDeleteLastUsed)
{
PrintUserData printUserData;
std::string lastUsedPrinterId = "lastUsedPrinter";
printUserData.lastUsedPrinterId_ = lastUsedPrinterId;
uint32_t type = DELETE_LAST_USED_PRINTER;
int32_t result = printUserData.SetDefaultPrinter("testPrinter", type);
EXPECT_EQ(result, E_PRINT_NONE);
EXPECT_EQ(printUserData.defaultPrinterId_, "testPrinter");
}
TEST_F(PrintUserDataTest, testSetDefaultPrinterFailure)
{
PrintUserData printUserData;
std::string printerId = "testPrinter";
uint32_t type = DEFAULT_PRINTER_TYPE_SETTED_BY_USER;
printUserData.SetUserDataToFile = undefined { return false; };
int32_t result = printUserData.SetDefaultPrinter(printerId, type);
EXPECT_EQ(result, E_PRINT_SERVER_FAILURE);
}
TEST_F(PrintUserDataTest, DeletePrinter_Should_ChangeLastUsedPrinter_When_LastUsedPrinterIdMatches)
{
PrintUserData userData;
userData.lastUsedPrinterId_ = "printer1";
userData.usedPrinterList_ = {"printer1", "printer2"};
userData.DeletePrinter("printer1");
EXPECT_EQ(userData.lastUsedPrinterId_, "printer2");
}
TEST_F(PrintUserDataTest, DeletePrinter_Should_SetUserDataToFile_When_SetUserDataToFileReturnsFalse)
{
PrintUserData userData;
userData.SetUserDataToFile = undefined { return false; };
userData.DeletePrinter("printer1");
// Assuming SetUserDataToFile has been implemented and returns false
EXPECT_EQ(userData.SetUserDataToFile(), false);
}
TEST_F(PrintUserDataTest, DeletePrinter_Should_NotChangeLastUsedPrinter_When_LastUsedPrinterIdDoesNotMatch)
{
PrintUserData userData;
userData.lastUsedPrinterId_ = "printer1";
userData.usedPrinterList_ = {"printer2"};
userData.DeletePrinter("printer1");
EXPECT_EQ(userData.lastUsedPrinterId_, "printer1");
}
TEST_F(PrintUserDataTest, DeletePrinter_Should_NotSetUserDataToFile_When_UsedPrinterListIsEmpty)
{
PrintUserData userData;
userData.usedPrinterList_ = {};
userData.DeletePrinter("printer1");
EXPECT_EQ(userData.SetUserDataToFile(), true);
}
TEST_F(PrintUserDataTest, DeletePrinterFromUsedPrinterList_Test)
{
PrintUserData printUserData;
std::string printerId = "printer1";
printUserData.usedPrinterList_.push_back("printer1");
printUserData.DeletePrinterFromUsedPrinterList(printerId);
EXPECT_EQ(printUserData.usedPrinterList_.size(), 0);
}
TEST_F(PrintUserDataTest, DeletePrinterFromUsedPrinterList_Test_NotPresent)
{
PrintUserData printUserData;
std::string printerId = "printer2";
printUserData.usedPrinterList_.push_back("printer1");
printUserData.DeletePrinterFromUsedPrinterList(printerId);
EXPECT_EQ(printUserData.usedPrinterList_.size(), 1);
}
TEST_F(PrintUserDataTest, DeletePrinterFromUsedPrinterList_Test_Multiple)
{
PrintUserData printUserData;
printUserData.usedPrinterList_.push_back("printer1");
printUserData.usedPrinterList_.push_back("printer2");
printUserData.usedPrinterList_.push_back("printer3");
printUserData.DeletePrinterFromUsedPrinterList("printer2");
int listSize = 2;
EXPECT_EQ(printUserData.usedPrinterList_.size(), listSize);
EXPECT_EQ(printUserData.usedPrinterList_[0], "printer1");
EXPECT_EQ(printUserData.usedPrinterList_[1], "printer3");
}
TEST_F(PrintUserDataTest, ParseUserData_ShouldReturn_WhenFileDataNotAvailable)
{
PrintUserData printUserData;
// Mock the GetFileData method to return false indicating file data is not available
printUserData.GetFileData = {
return false;
};
printUserData.ParseUserData();
// Assert that the method does not crash or throw exceptions
EXPECT_NO_THROW(printUserData.ParseUserData());
}
TEST_F(PrintUserDataTest, ParseUserData_ShouldReturn_WhenFileDataAvailableButInvalid)
{
PrintUserData printUserData;
// Mock the GetFileData method to return true indicating file data is available
printUserData.GetFileData = {
return true;
};
// Mock the CheckFileData method to return false indicating file data is invalid
printUserData.CheckFileData = [](const std::string &, nlohmann::json &) {
return false;
};
printUserData.ParseUserData();
// Assert that the method does not crash or throw exceptions
EXPECT_NO_THROW(printUserData.ParseUserData());
}
TEST_F(PrintUserDataTest, ParseUserData_ShouldParse_WhenFileDataAvailableAndValid)
{
PrintUserData printUserData;
// Mock the GetFileData method to return true indicating file data is available
printUserData.GetFileData = {
return true;
};
// Mock the CheckFileData method to return true indicating file data is valid
printUserData.CheckFileData = [](const std::string &, nlohmann::json &) {
return true;
};
// Mock the ParseUserDataFromJson method to do nothing
printUserData.ParseUserDataFromJson = [](const nlohmann::json &) {};
printUserData.ParseUserData();
// Assert that the method does not crash or throw exceptions
EXPECT_NO_THROW(printUserData.ParseUserData());
}
TEST_F(PrintUserDataTest, ParseUserDataFromJson_Test)
{
nlohmann::json jsonObject;
PrintUserData printUserData;
printUserData.ParseUserDataFromJson(jsonObject);
EXPECT_EQ(printUserData.defaultPrinterId_, "");
EXPECT_EQ(printUserData.lastUsedPrinterId_, "");
EXPECT_EQ(printUserData.useLastUsedPrinterForDefault_, false);
}
TEST_F(PrintUserDataTest, ParseUserDataFromJson_Test_WithUserData)
{
nlohmann::json jsonObject;
jsonObject["print_user_data"] = {
{
"1",
{
{"defaultPrinter", "printer1"},
{"lastUsedPrinter", "printer2"},
{"useLastUsedPrinterForDefault", true},
{"usedPrinterList", undefined{
nlohmann::json jsonArray;jsonArray.push_back("printer3");return jsonArray;}()}
}
}
};
PrintUserData printUserData;
printUserData.ParseUserDataFromJson(jsonObject);
EXPECT_EQ(printUserData.defaultPrinterId_, "printer1");
EXPECT_EQ(printUserData.lastUsedPrinterId_, "printer2");
EXPECT_EQ(printUserData.useLastUsedPrinterForDefault_, true);
}
TEST_F(PrintUserDataTest, ParseUserDataFromJson_Test_WithUserData_MissingDefaultPrinter)
{
nlohmann::json jsonObject;
jsonObject["print_user_data"] = {
{
"1",
{
{"defaultPrinter", "printer1"},
{"lastUsedPrinter", "printer2"},
{"useLastUsedPrinterForDefault", true},
{"usedPrinterList", undefined{
nlohmann::json jsonArray;jsonArray.push_back("printer3");return jsonArray;}()}
}
}
};
PrintUserData printUserData;
printUserData.ParseUserDataFromJson(jsonObject);
EXPECT_EQ(printUserData.defaultPrinterId_, "");
EXPECT_EQ(printUserData.lastUsedPrinterId_, "printer2");
EXPECT_EQ(printUserData.useLastUsedPrinterForDefault_, true);
}
TEST_F(PrintUserDataTest, ConvertJsonToUsedPrinterList_Test)
{
PrintUserData printUserData;
nlohmann::json userData;
userData["usedPrinterList"] = nlohmann::json::array();
userData["usedPrinterList"].push_back("printer1");
userData["usedPrinterList"].push_back("printer2");
userData["usedPrinterList"].push_back("printer3");
EXPECT_TRUE(printUserData.ConvertJsonToUsedPrinterList(userData));
}
TEST_F(PrintUserDataTest, ConvertJsonToUsedPrinterList_Test_Invalid)
{
PrintUserData printUserData;
nlohmann::json userData;
userData["usedPrinterList"] = nlohmann::json::array();
int printerId = 123;
userData["usedPrinterList"].push_back(printerId); // Invalid value
userData["usedPrinterList"].push_back("printer2");
EXPECT_FALSE(printUserData.ConvertJsonToUsedPrinterList(userData));
}
TEST_F(PrintUserDataTest, ConvertJsonToUsedPrinterList_Test_Empty)
{
PrintUserData printUserData;
nlohmann::json userData;
EXPECT_TRUE(printUserData.ConvertJsonToUsedPrinterList(userData));
}
TEST_F(PrintUserDataTest, GetFileData_ShouldReturnTrue_WhenFileIsOpenedSuccessfully)
{
std::string fileData;
bool result = PrintUserData::GetFileData(fileData);
EXPECT_TRUE(result);
}
TEST_F(PrintUserDataTest, GetFileData_ShouldReturnFalse_WhenFileCannotBeOpened)
{
std::string fileData;
// Mock the file path to simulate a failure to open the file
std::string mockFilePath = "/nonexistent/path";
bool result = PrintUserData::GetFileData(fileData);
EXPECT_FALSE(result);
}
TEST_F(PrintUserDataTest, GetFileData_ShouldReturnTrue_WhenFileIsCreatedSuccessfully)
{
std::string fileData;
// Mock the file path to simulate a file creation scenario
std::string mockFilePath = "/tmp/nonexistent/path";
bool result = PrintUserData::GetFileData(fileData);
EXPECT_TRUE(result);
}
TEST_F(PrintUserDataTest, GetFileData_ShouldReturnFalse_WhenFileCannotBeCreated)
{
std::string fileData;
// Mock the file path to simulate a failure to create the file
std::string mockFilePath = "/tmp/nonexistent/path/with/no/permission";
bool result = PrintUserData::GetFileData(fileData);
EXPECT_FALSE(result);
}
TEST_F(PrintUserDataTest, GetFileData_ShouldReturnTrue_WhenFileDataIsReadSuccessfully)
{
std::string fileData;
// Mock the file path to simulate a successful read scenario
std::string mockFilePath = "/tmp/existing/file";
bool result = PrintUserData::GetFileData(fileData);
EXPECT_TRUE(result);
}
TEST_F(PrintUserDataTest, GetFileData_ShouldReturnFalse_WhenFileDataCannotBeRead)
{
std::string fileData;
// Mock the file path to simulate a failure to read the file
std::string mockFilePath = "/tmp/existing/file/with/no/permission";
bool result = PrintUserData::GetFileData(fileData);
EXPECT_FALSE(result);
}
TEST_F(PrintUserDataTest, CheckFileData_ShouldReturnFalse_WhenFileDataIsNotAcceptable)
{
std::string fileData = "invalid json";
nlohmann::json jsonObject;
bool result = PrintUserData::CheckFileData(fileData, jsonObject);
EXPECT_FALSE(result);
}
TEST_F(PrintUserDataTest, CheckFileData_ShouldReturnFalse_WhenVersionIsNotPresent)
{
std::string fileData = "{" key ":" value "}";
nlohmann::json jsonObject;
bool result = PrintUserData::CheckFileData(fileData, jsonObject);
EXPECT_FALSE(result);
}
TEST_F(PrintUserDataTest, CheckFileData_ShouldReturnFalse_WhenVersionIsNotString)
{
std::string fileData = "{" version ":123}";
nlohmann::json jsonObject;
bool result = PrintUserData::CheckFileData(fileData, jsonObject);
EXPECT_FALSE(result);
}
TEST_F(PrintUserDataTest, CheckFileData_ShouldReturnFalse_WhenPrintUserDataIsNotPresent)
{
std::string fileData = "{" version ":" 1.0 "}";
nlohmann::json jsonObject;
bool result = PrintUserData::CheckFileData(fileData, jsonObject);
EXPECT_FALSE(result);
}
TEST_F(PrintUserDataTest, CheckFileData_ShouldReturnTrue_WhenAllConditionsAreMet)
{
std::string fileData = "{" version ":" 1.0 "," print_user_data ":" data "}";
nlohmann::json jsonObject;
bool result = PrintUserData::CheckFileData(fileData, jsonObject);
EXPECT_TRUE(result);
}
} // namespace OHOS::Print

View File

@ -17,6 +17,7 @@
#define PRINT_CONSTANT_H #define PRINT_CONSTANT_H
#include <string> #include <string>
#include <map>
namespace OHOS::Print { namespace OHOS::Print {
#define PRINT_RET_NONE #define PRINT_RET_NONE
@ -239,5 +240,14 @@ const std::string PRINTER_LIST_FILE = "printer_list.json";
const std::string PRINTER_LIST_VERSION = "v1"; const std::string PRINTER_LIST_VERSION = "v1";
const std::string PRINT_USER_DATA_FILE = "print_user_data.json"; const std::string PRINT_USER_DATA_FILE = "print_user_data.json";
const std::string PRINT_USER_DATA_VERSION = "v1"; const std::string PRINT_USER_DATA_VERSION = "v1";
const std::string E_PRINT_MSG_NONE = "none";
const std::string E_PRINT_MSG_NO_PERMISSION = "the application does not hace permission";
const std::string E_PRINT_MSG_INVALID_PARAMETER = "parameter error";
static std::map<PrintErrorCode, const std::string> PRINT_ERROR_MSG_MAP {
{E_PRINT_NONE, E_PRINT_MSG_NONE },
{E_PRINT_NO_PERMISSION, E_PRINT_MSG_NO_PERMISSION },
{E_PRINT_INVALID_PARAMETER, E_PRINT_MSG_INVALID_PARAMETER },
};
} // namespace OHOS::Print } // namespace OHOS::Print
#endif // PRINT_CONSTANT_H #endif // PRINT_CONSTANT_H