diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 2cf9531cc937758c692bf980ce93f782e45661f3..8883eeb3e78dcceec849b895725ad8acc9854b8b 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -73,6 +73,7 @@ enum { DM_IPC_SEND_REQUEST_FAILED, DM_IPC_NOT_REGISTER_FUNC, DM_IPC_RESPOND_ERROR, + DM_IPC_WRITE_TOKEN_ERROR, DM_DISCOVERY_REPEATED, DM_AUTH_NOT_SUPPORT, DM_AUTH_BUSINESS_BUSY, @@ -144,6 +145,9 @@ const std::string AUTH_TYPE = "authType"; const std::string TOKEN = "token"; const std::string PIN_TOKEN = "pinToken"; const std::string PIN_CODE_KEY = "pinCode"; +const std::string NFC_CODE_KEY = "nfcCode"; +const std::string QR_CODE_KEY = "qrCode"; +const std::string TAG_AUTH_TOKEN = "authToken"; const int32_t AUTH_TYPE_PIN = 1; const int32_t AUTH_TYPE_SCAN = 2; const int32_t AUTH_TYPE_TOUCH = 3; diff --git a/common/include/ipc/ipc_def.h b/common/include/ipc/ipc_def.h index ec3a93d3ed6518238ae44a76ae77333986ef9723..cc2aa67d66b8ba23ea5ecadc70c0edc5be53a43e 100644 --- a/common/include/ipc/ipc_def.h +++ b/common/include/ipc/ipc_def.h @@ -54,6 +54,8 @@ enum IpcCmdID { SERVER_GET_DMFA_INFO, SERVER_USER_AUTH_OPERATION, SERVER_DEVICE_FA_NOTIFY, + REGISTER_DEV_STATE_CALLBACK, + UNREGISTER_DEV_STATE_CALLBACK, }; } // namespace DistributedHardware } // namespace OHOS diff --git a/common/include/ipc/model/ipc_register_dev_state_callback_req.h b/common/include/ipc/model/ipc_register_dev_state_callback_req.h new file mode 100644 index 0000000000000000000000000000000000000000..4ab4bc253ea6fb7da6be61cc5812262380f51c40 --- /dev/null +++ b/common/include/ipc/model/ipc_register_dev_state_callback_req.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 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. + */ + +#ifndef OHOS_DM_IPC_REGISTER_DEV_STATE_CALLBACK_REQ_H +#define OHOS_DM_IPC_REGISTER_DEV_STATE_CALLBACK_REQ_H + +#include + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcRegisterDevStateCallbackReq : public IpcReq { + DECLARE_IPC_MODEL(IpcRegisterDevStateCallbackReq); + +public: + const std::string &GetExtra() const + { + return extra_; + } + + void SetExtra(const std::string &extra) + { + extra_ = extra; + } + +private: + std::string extra_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_REGISTER_DEV_STATE_CALLBACK_REQ_H diff --git a/ext/pin_auth/include/pin_auth.h b/ext/pin_auth/include/pin_auth.h index dca2e7e7f9e12b4679d778c7d4a9b893f46c129d..ac02b101789ce4aad956095c5acf6fd32cbedb56 100644 --- a/ext/pin_auth/include/pin_auth.h +++ b/ext/pin_auth/include/pin_auth.h @@ -30,10 +30,9 @@ class PinAuth : public IAuthentication { public: PinAuth(); ~PinAuth(); - int32_t ShowAuthInfo(int32_t code, std::shared_ptr authManager) override; - int32_t StartAuth(int32_t code, std::shared_ptr authManager) override; - int32_t VerifyAuthentication(std::string pinToken, int32_t code, const std::string &authParam) override; - + int32_t ShowAuthInfo(std::string &authToken, std::shared_ptr authManager) override; + int32_t StartAuth(std::string &authToken, std::shared_ptr authManager) override; + int32_t VerifyAuthentication(std::string &authToken, const std::string &authParam) override; private: int32_t times_ = 0; std::shared_ptr pinAuthUi_; diff --git a/ext/pin_auth/src/pin_auth.cpp b/ext/pin_auth/src/pin_auth.cpp index 0bbadd15f7aa503e771432a132e9512f1834eec8..377cb8fdb1691fe835222a9052333acccf339cc9 100644 --- a/ext/pin_auth/src/pin_auth.cpp +++ b/ext/pin_auth/src/pin_auth.cpp @@ -16,6 +16,7 @@ #include "pin_auth.h" #include +#include #include "dm_constants.h" #include "dm_log.h" @@ -26,6 +27,7 @@ namespace DistributedHardware { const int32_t MAX_VERIFY_TIMES = 3; PinAuth::PinAuth() { + pinAuthUi_ = std::make_shared(); LOGI("PinAuth constructor"); } @@ -33,31 +35,64 @@ PinAuth::~PinAuth() { } -int32_t PinAuth::ShowAuthInfo(int32_t code, std::shared_ptr authManager) +int32_t PinAuth::ShowAuthInfo(std::string &authToken, std::shared_ptr authManager) { - return pinAuthUi_->ShowPinDialog(code, authManager); + nlohmann::json jsonObject = nlohmann::json::parse(authToken, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + if (!jsonObject.contains(PIN_CODE_KEY)) { + LOGE("err json string, first time"); + return DM_FAILED; + } + return pinAuthUi_->ShowPinDialog(jsonObject[PIN_CODE_KEY], authManager); } -int32_t PinAuth::StartAuth(int32_t code, std::shared_ptr authManager) +int32_t PinAuth::StartAuth(std::string &authToken, std::shared_ptr authManager) { - return pinAuthUi_->InputPinDialog(code, authManager); + nlohmann::json jsonObject = nlohmann::json::parse(authToken, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + if (!jsonObject.contains(PIN_CODE_KEY)) { + LOGE("err json string, first time"); + return DM_FAILED; + } + return pinAuthUi_->InputPinDialog(jsonObject[PIN_CODE_KEY], authManager); } -int32_t PinAuth::VerifyAuthentication(std::string pinToken, int32_t code, const std::string &authParam) +int32_t PinAuth::VerifyAuthentication(std::string &authToken, const std::string &authParam) { times_ += 1; - nlohmann::json jsonObject = nlohmann::json::parse(authParam, nullptr, false); - if (jsonObject.is_discarded()) { + if (strlen(authParam.c_str()) == 1) { + if (authParam == "0") { + return DM_OK; + } + LOGE("Peer rejection"); + return DM_FAILED; + } + nlohmann::json authParamJson = nlohmann::json::parse(authParam, nullptr, false); + if (authParamJson.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + nlohmann::json authTokenJson = nlohmann::json::parse(authToken, nullptr, false); + if (authTokenJson.is_discarded()) { LOGE("DecodeRequestAuth jsonStr error"); return DM_FAILED; } - if (!jsonObject.contains(PIN_CODE_KEY) && !jsonObject.contains(PIN_TOKEN)) { + if (!authParamJson.contains(PIN_CODE_KEY) || !authParamJson.contains(PIN_TOKEN) + || !authTokenJson.contains(PIN_CODE_KEY) || !authTokenJson.contains(PIN_TOKEN)) { LOGE("err json string, first time"); return DM_FAILED; } - int32_t inputPinCode = jsonObject[PIN_CODE_KEY]; - int32_t inputPinToken = jsonObject[PIN_TOKEN]; - if (code == inputPinCode && stoi(pinToken) == inputPinToken) { + int32_t code = authTokenJson[PIN_CODE_KEY]; + int32_t pinToken = authTokenJson[PIN_TOKEN]; + int32_t inputPinCode = authParamJson[PIN_CODE_KEY]; + int32_t inputPinToken = authParamJson[PIN_TOKEN]; + if (code == inputPinCode && pinToken == inputPinToken) { return DM_OK; } else if (code != inputPinCode && times_ < MAX_VERIFY_TIMES) { return DM_AUTH_INPUT_FAILED; diff --git a/ext/pin_auth/src/pin_auth_ui.cpp b/ext/pin_auth/src/pin_auth_ui.cpp index 9fc3459cda10a015720e9c8184833825b398c14f..eb976a67898c97ed963f8228bf400323baa920f8 100644 --- a/ext/pin_auth/src/pin_auth_ui.cpp +++ b/ext/pin_auth/src/pin_auth_ui.cpp @@ -43,7 +43,7 @@ int32_t PinAuthUi::ShowPinDialog(int32_t code, std::shared_ptr au ACE_X, ACE_Y, ACE_WIDTH, ACE_HEIGHT, [authManager](int32_t id, const std::string& event, const std::string& params) { if (strcmp(params.c_str(), "0") == 0) { - authManager->ClosePage(id); + authManager->SetPageId(id); } if (strcmp(params.c_str(), "1") == 0) { LOGI("CancelDialog start id:%d,event:%s,parms:%s", id, event.c_str(), params.c_str()); @@ -69,12 +69,12 @@ int32_t PinAuthUi::InputPinDialog(int32_t code, std::shared_ptr a ACE_X, ACE_Y, ACE_WIDTH, ACE_HEIGHT, [authManager](int32_t id, const std::string& event, const std::string& params) { if (strcmp(params.c_str(), "2") == 0) { - authManager->ClosePage(id); + authManager->SetPageId(id); } if (strcmp(params.c_str(), "0") == 0 || strcmp(params.c_str(), "1") == 0) { Ace::UIServiceMgrClient::GetInstance()->CancelDialog(id); LOGI("CancelDialog start id:%d,event:%s,parms:%s", id, event.c_str(), params.c_str()); - authManager->VerifyPinAuthAuthentication(params.c_str()); + authManager->VerifyAuthentication(params.c_str()); } }); LOGI("ShowConfigDialog end"); diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 9e76a136103750e228535c364432533b4e55de33..4b814a7a72dff37daaaa7f514780a1f920b47701 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -54,6 +54,8 @@ public: virtual int32_t SetUserOperation(const std::string &pkgName, int32_t action) = 0; virtual int32_t GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &udid) = 0; virtual int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid) = 0; + virtual int32_t RegisterDevStateCallback(const std::string &pkgName, const std::string &extra) = 0; + virtual int32_t UnRegisterDevStateCallback(const std::string &pkgName, const std::string &extra) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index 1e38d7dbd2d428385033505db1e067daab71cf98..805d6640f31ecac2651d9c29b7e656bdfa1ebcb9 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -55,6 +55,8 @@ public: std::string &udid) override; virtual int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid) override; + virtual int32_t RegisterDevStateCallback(const std::string &pkgName, const std::string &extra) override; + virtual int32_t UnRegisterDevStateCallback(const std::string &pkgName, const std::string &extra) override; private: DeviceManagerImpl() = default; diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 452c1704a3fdfdb0b8c66cd3540d8c13f8df4bb7..91fd9fbe72f6d7f164f98f8bf201c7197085ede4 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -32,6 +32,7 @@ #include "ipc_stop_discovery_req.h" #include "ipc_unauthenticate_device_req.h" #include "ipc_verify_authenticate_req.h" +#include "ipc_register_dev_state_callback_req.h" #include "securec.h" namespace OHOS { @@ -143,6 +144,9 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, } DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); + if (!extra.empty()) { + RegisterDevStateCallback(pkgName, extra); + } LOGI("RegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); return DM_OK; } @@ -156,6 +160,8 @@ int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName } DeviceManagerNotify::GetInstance().UnRegisterDeviceStateCallback(pkgName); + std::string extra = ""; + UnRegisterDevStateCallback(pkgName, extra); LOGI("UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); return DM_OK; } @@ -267,17 +273,20 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons } DmDeviceInfo deviceInfo; - strcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, deviceId.c_str()); + int32_t ret = strcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, deviceId.c_str()); + if (ret != DM_OK) { + LOGE("UnAuthenticateDevice error: copy deviceId failed"); + return DM_INVALID_VALUE; + } std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); req->SetDeviceInfo(deviceInfo); - int32_t ret = ipcClientProxy_->SendRequest(UNAUTHENTICATE_DEVICE, req, rsp); + ret = ipcClientProxy_->SendRequest(UNAUTHENTICATE_DEVICE, req, rsp); if (ret != DM_OK) { LOGE("UnAuthenticateDevice error: Send Request failed ret: %d", ret); return DM_IPC_SEND_REQUEST_FAILED; } - ret = rsp->GetErrCode(); if (ret != DM_OK) { LOGE("UnAuthenticateDevice error: Failed with ret %d", ret); @@ -439,5 +448,51 @@ int32_t DeviceManagerImpl::GetUuidByNetworkId(const std::string &pkgName, const uuid = rsp->GetUuid(); return DM_OK; } + +int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra) +{ + if (pkgName.empty()) { + LOGE("RegisterDevStateCallback failed, pkgName is empty"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetExtra(extra); + + if (ipcClientProxy_->SendRequest(REGISTER_DEV_STATE_CALLBACK, req, rsp) != DM_OK) { + return DM_IPC_SEND_REQUEST_FAILED; + } + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("RegisterDevStateCallback Failed with ret %d", ret); + return ret; + } + return DM_OK; +} + +int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName, const std::string &extra) +{ + if (pkgName.empty()) { + LOGE("UnRegisterDevStateCallback failed, pkgName is empty"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetExtra(extra); + + if (ipcClientProxy_->SendRequest(UNREGISTER_DEV_STATE_CALLBACK, req, rsp) != DM_OK) { + return DM_IPC_SEND_REQUEST_FAILED; + } + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("UnRegisterDevStateCallback Failed with ret %d", ret); + return ret; + } + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_server_proxy.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_server_proxy.cpp index c81222fb8eb66db6633a35cc25a19db4ef250579..345243a15466d8e2839eaf1f960586dc01183e93 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_server_proxy.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_server_proxy.cpp @@ -33,6 +33,10 @@ int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr r MessageParcel data; MessageParcel reply; MessageOption option; + if (!data.WriteInterfaceToken(GetDescriptor())) { + LOGE("WriteInterfaceToken fail!"); + return DM_IPC_WRITE_TOKEN_ERROR; + } if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DM_OK) { return DM_IPC_SEND_REQUEST_FAILED; } diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_stub.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_stub.cpp index 9cacbbf9c2fcbbb0628b6b6cffc9bd08ce0d9670..aa022b55ff41fe7406d413450cf61aa6a349bc9a 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_stub.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_stub.cpp @@ -26,6 +26,12 @@ namespace DistributedHardware { int32_t IpcClientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { LOGI("code = %d, flags= %d.", code, option.GetFlags()); + auto remoteDescriptor = data.ReadInterfaceToken(); + if (GetDescriptor() != remoteDescriptor) { + LOGI("ReadInterfaceToken fail!"); + return ERR_INVALID_STATE; + } + if (IpcCmdRegister::GetInstance().OnIpcCmd((int32_t)code, data, reply) == DM_OK) { LOGE("on ipc cmd success"); return DM_OK; diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp index 5858e834d138221856836682dbd64de3623ada4e..38a52f75a389c4be8f7fbcafda21441bd25c3beb 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp @@ -34,6 +34,7 @@ #include "ipc_stop_discovery_req.h" #include "ipc_unauthenticate_device_req.h" #include "ipc_verify_authenticate_req.h" +#include "ipc_register_dev_state_callback_req.h" #include "securec.h" namespace OHOS { @@ -349,6 +350,56 @@ ON_IPC_READ_RESPONSE(SERVER_USER_AUTH_OPERATION, MessageParcel &reply, std::shar return DM_OK; } +ON_IPC_SET_REQUEST(REGISTER_DEV_STATE_CALLBACK, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = + std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string extra = pReq->GetExtra(); + + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return DM_IPC_TRANSACTION_FAILED; + } + if (!data.WriteString(extra)) { + LOGE("write extra failed"); + return DM_WRITE_FAILED; + } + + return DM_OK; +} + +ON_IPC_READ_RESPONSE(REGISTER_DEV_STATE_CALLBACK, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(UNREGISTER_DEV_STATE_CALLBACK, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = + std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string extra = pReq->GetExtra(); + + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return DM_IPC_TRANSACTION_FAILED; + } + if (!data.WriteString(extra)) { + LOGE("write extra failed"); + return DM_WRITE_FAILED; + } + + return DM_OK; +} + +ON_IPC_READ_RESPONSE(UNREGISTER_DEV_STATE_CALLBACK, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 71cb995b4f81a9ffcb6fd2b857fbecaeb4e5c78b..5736c29b64a7804fb00fa936dd36e722e2bd7e1d 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -47,6 +47,20 @@ struct DeviceInfoAsyncCallbackInfo { std::string bundleName; size_t bundleNameLen = 0; OHOS::DistributedHardware::DmDeviceInfo deviceInfo; + std::string extra; + // OHOS::DistributedHardware::DmFilterOptions filter; + napi_ref callback = nullptr; + napi_value thisVar = nullptr; + napi_deferred deferred = nullptr; + int32_t status = -1; +}; + +struct DeviceInfoListAsyncCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + + std::string bundleName; + size_t bundleNameLen = 0; std::vector devList; std::string extra; // OHOS::DistributedHardware::DmFilterOptions filter; @@ -54,7 +68,6 @@ struct DeviceInfoAsyncCallbackInfo { napi_value thisVar = nullptr; napi_deferred deferred = nullptr; int32_t status = -1; - int32_t isList = 0; }; struct AuthAsyncCallbackInfo { @@ -67,6 +80,39 @@ struct AuthAsyncCallbackInfo { int32_t authType = -1; }; +struct DmNapiStateJsCallback { + std::string bundleName_; + uint16_t subscribeId_; + int32_t reason_; + OHOS::DistributedHardware::DmDeviceInfo deviceInfo_; + + DmNapiStateJsCallback(std::string bundleName, uint16_t subscribeId, int32_t reason, + OHOS::DistributedHardware::DmDeviceInfo deviceInfo) + : bundleName_(bundleName), subscribeId_(subscribeId), reason_(reason), deviceInfo_(deviceInfo) {} +}; + +struct DmNapiAuthJsCallback { + std::string bundleName_; + std::string deviceId_; + std::string token_; + int32_t status_; + int32_t reason_; + + DmNapiAuthJsCallback(std::string bundleName, std::string deviceId, std::string token, int32_t status, + int32_t reason) + : bundleName_(bundleName), deviceId_(deviceId), token_(token), status_(status), reason_(reason) {} +}; + +struct DmNapiVerifyJsCallback { + std::string bundleName_; + std::string deviceId_; + int32_t resultCode_; + int32_t flag_; + + DmNapiVerifyJsCallback(std::string bundleName, std::string deviceId, int32_t resultCode, int32_t flag) + : bundleName_(bundleName), deviceId_(deviceId), resultCode_(resultCode), flag_(flag) {} +}; + enum DmNapiDevStateChangeAction { ONLINE = 0, READY = 1, OFFLINE = 2, CHANGE = 3 }; class DmNapiInitCallback : public OHOS::DistributedHardware::DmInitCallback { @@ -82,6 +128,7 @@ public: private: napi_env env_; std::string bundleName_; + std::unique_ptr jsCallback_; }; class DmNapiDeviceStateCallback : public OHOS::DistributedHardware::DeviceStateCallback { @@ -98,6 +145,7 @@ public: private: napi_env env_; std::string bundleName_; + std::unique_ptr jsCallback_; }; class DmNapiDiscoveryCallback : public OHOS::DistributedHardware::DiscoveryCallback { @@ -118,6 +166,7 @@ private: napi_env env_; std::atomic refCount_; std::string bundleName_; + std::unique_ptr jsCallback_; }; class DmNapiDeviceManagerFaCallback : public OHOS::DistributedHardware::DeviceManagerFaCallback { @@ -131,6 +180,7 @@ public: private: napi_env env_; std::string bundleName_; + std::unique_ptr jsCallback_; }; class DmNapiAuthenticateCallback : public OHOS::DistributedHardware::AuthenticateCallback { @@ -144,6 +194,7 @@ public: private: napi_env env_; std::string bundleName_; + std::unique_ptr jsCallback_; }; class DmNapiVerifyAuthCallback : public OHOS::DistributedHardware::VerifyAuthCallback { @@ -157,6 +208,7 @@ public: private: napi_env env_; std::string bundleName_; + std::unique_ptr jsCallback_; }; class DeviceManagerNapi : public DmNativeEvent { @@ -165,6 +217,13 @@ public: virtual ~DeviceManagerNapi(); static napi_value Init(napi_env env, napi_value exports); static napi_value Constructor(napi_env env, napi_callback_info info); + static napi_value EnumTypeConstructor(napi_env env, napi_callback_info info); + static napi_value InitDeviceTypeEnum(napi_env env, napi_value exports); + static napi_value InitDeviceStateChangeActionEnum(napi_env env, napi_value exports); + static napi_value InitDiscoverModeEnum(napi_env env, napi_value exports); + static napi_value InitExchangeMediumEnum(napi_env env, napi_value exports); + static napi_value InitExchangeFreqEnum(napi_env env, napi_value exports); + static napi_value InitSubscribeCapEnum(napi_env env, napi_value exports); static napi_value CreateDeviceManager(napi_env env, napi_callback_info info); static napi_value ReleaseDeviceManager(napi_env env, napi_callback_info info); static napi_value SetUserOperationSync(napi_env env, napi_callback_info info); @@ -183,6 +242,7 @@ public: static void HandleCreateDmCallBack(const napi_env &env, AsyncCallbackInfo *asCallbackInfo); static DeviceManagerNapi *GetDeviceManagerNapi(std::string &buldleName); static void CreateDmCallback(napi_env env, std::string &bundleName, std::string &eventType); + static void CreateDmCallback(napi_env env, std::string &bundleName, std::string &eventType, std::string &extra); static void ReleaseDmCallback(std::string &bundleName, std::string &eventType); static void DeviceInfoToJsArray(const napi_env &env, const std::vector &vecDevInfo, @@ -229,12 +289,14 @@ private: static napi_value JsOnFrench(napi_env env, int32_t num, napi_value thisVar, napi_value argv[]); static void CallAsyncWorkSync(napi_env env, DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); static void CallAsyncWork(napi_env env, DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + static void CallAsyncWorkSync(napi_env env, DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo); + static void CallAsyncWork(napi_env env, DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo); static void CallGetTrustedDeviceListStatusSync(napi_env env, napi_status &status, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo); static void CallGetTrustedDeviceListStatus(napi_env env, napi_status &status, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo); static napi_value CallDeviceList(napi_env env, napi_callback_info info, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); + DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo); static void CallGetLocalDeviceInfoSync(napi_env env, napi_status &status, DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo); static void CallGetLocalDeviceInfo(napi_env env, napi_status &status, diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 644386adf99511a04928c0371fd5ddd949158b53..172e641b243195cfefadd5fdb868f7e150edb905 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -46,6 +46,12 @@ const int32_t DM_NAPI_ARGS_TWO = 2; const int32_t DM_NAPI_ARGS_THREE = 3; const int32_t DM_NAPI_SUB_ID_MAX = 65535; +napi_ref deviceTypeEnumConstructor_ = nullptr; +napi_ref deviceStateChangeActionEnumConstructor_ = nullptr; +napi_ref discoverModeEnumConstructor_ = nullptr; +napi_ref exchangeMediumEnumConstructor_ = nullptr; +napi_ref exchangeFreqEnumConstructor_ = nullptr; +napi_ref subscribeCapEnumConstructor_ = nullptr; std::map g_deviceManagerMap; std::map> g_initCallbackMap; @@ -68,16 +74,20 @@ void DmNapiInitCallback::OnRemoteDied() return; } uv_work_t *work = new (std::nothrow) uv_work_t; - if (loop == nullptr) { + if (work == nullptr) { LOGE("DmNapiInitCallback: OnRemoteDied, No memory"); return; } - static std::string staticBundleName = bundleName_; + DmDeviceInfo info; + jsCallback_ = std::make_unique(bundleName_, 0, 0, info); + work->data = reinterpret_cast(jsCallback_.get()); + int ret = uv_queue_work(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) { - DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(staticBundleName); + DmNapiStateJsCallback *callback = reinterpret_cast(work->data); + DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_); if (deviceManagerNapi == nullptr) { - LOGE("OnRemoteDied, deviceManagerNapi not find for bunderName %s", staticBundleName.c_str()); + LOGE("OnRemoteDied, deviceManagerNapi not find for bunderName %s", callback->bundleName_.c_str()); return; } deviceManagerNapi->OnEvent("serviceDie", 0, nullptr); @@ -97,20 +107,22 @@ void DmNapiDeviceStateCallback::OnDeviceOnline(const DmDeviceInfo &deviceInfo) return; } uv_work_t *work = new (std::nothrow) uv_work_t; - if (loop == nullptr) { + if (work == nullptr) { LOGE("DmNapiDeviceStateCallback: OnDeviceOnline, No memory"); return; } - static std::string staticBundleName = bundleName_; - static DmDeviceInfo staticDeviceInfo = deviceInfo; + jsCallback_ = std::make_unique(bundleName_, 0, 0, deviceInfo); + work->data = reinterpret_cast(jsCallback_.get()); + int ret = uv_queue_work(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) { - DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(staticBundleName); + DmNapiStateJsCallback *callback = reinterpret_cast(work->data); + DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_); if (deviceManagerNapi == nullptr) { - LOGE("OnDeviceOnline, deviceManagerNapi not find for bunderName %s", staticBundleName.c_str()); + LOGE("OnDeviceOnline, deviceManagerNapi not find for bunderName %s", callback->bundleName_.c_str()); return; } - deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::ONLINE, staticDeviceInfo); + deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::ONLINE, callback->deviceInfo_); delete work; }); if (ret != 0) { @@ -127,20 +139,22 @@ void DmNapiDeviceStateCallback::OnDeviceReady(const DmDeviceInfo &deviceInfo) return; } uv_work_t *work = new (std::nothrow) uv_work_t; - if (loop == nullptr) { + if (work == nullptr) { LOGE("DmNapiDeviceStateCallback: OnDeviceReady, No memory"); return; } - static std::string staticBundleName = bundleName_; - static DmDeviceInfo staticDeviceInfo = deviceInfo; + jsCallback_ = std::make_unique(bundleName_, 0, 0, deviceInfo); + work->data = reinterpret_cast(jsCallback_.get()); + int ret = uv_queue_work(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) { - DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(staticBundleName); + DmNapiStateJsCallback *callback = reinterpret_cast(work->data); + DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_); if (deviceManagerNapi == nullptr) { - LOGE("OnDeviceReady, deviceManagerNapi not find for bunderName %s", staticBundleName.c_str()); + LOGE("OnDeviceReady, deviceManagerNapi not find for bunderName %s", callback->bundleName_.c_str()); return; } - deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::READY, staticDeviceInfo); + deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::READY, callback->deviceInfo_); delete work; }); if (ret != 0) { @@ -157,20 +171,22 @@ void DmNapiDeviceStateCallback::OnDeviceOffline(const DmDeviceInfo &deviceInfo) return; } uv_work_t *work = new (std::nothrow) uv_work_t; - if (loop == nullptr) { + if (work == nullptr) { LOGE("DmNapiDeviceStateCallback: OnDeviceOffline, No memory"); return; } - static std::string staticBundleName = bundleName_; - static DmDeviceInfo staticDeviceInfo = deviceInfo; + jsCallback_ = std::make_unique(bundleName_, 0, 0, deviceInfo); + work->data = reinterpret_cast(jsCallback_.get()); + int ret = uv_queue_work(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) { - DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(staticBundleName); + DmNapiStateJsCallback *callback = reinterpret_cast(work->data); + DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_); if (deviceManagerNapi == nullptr) { - LOGE("OnDeviceOffline, deviceManagerNapi not find for bunderName %s", staticBundleName.c_str()); + LOGE("OnDeviceOffline, deviceManagerNapi not find for bunderName %s", callback->bundleName_.c_str()); return; } - deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::OFFLINE, staticDeviceInfo); + deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::OFFLINE, callback->deviceInfo_); delete work; }); if (ret != 0) { @@ -192,15 +208,17 @@ void DmNapiDeviceStateCallback::OnDeviceChanged(const DmDeviceInfo &deviceInfo) return; } - static std::string staticBundleName = bundleName_; - static DmDeviceInfo staticDeviceInfo = deviceInfo; + jsCallback_ = std::make_unique(bundleName_, 0, 0, deviceInfo); + work->data = reinterpret_cast(jsCallback_.get()); + int ret = uv_queue_work(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) { - DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(staticBundleName); + DmNapiStateJsCallback *callback = reinterpret_cast(work->data); + DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_); if (deviceManagerNapi == nullptr) { - LOGE("OnDeviceChanged, deviceManagerNapi not find for bunderName %s", staticBundleName.c_str()); + LOGE("OnDeviceChanged, deviceManagerNapi not find for bunderName %s", callback->bundleName_.c_str()); return; } - deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::CHANGE, staticDeviceInfo); + deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::CHANGE, callback->deviceInfo_); delete work; }); if (ret != 0) { @@ -219,21 +237,22 @@ void DmNapiDiscoveryCallback::OnDeviceFound(uint16_t subscribeId, const DmDevice return; } uv_work_t *work = new (std::nothrow) uv_work_t; - if (loop == nullptr) { + if (work == nullptr) { LOGE("DmNapiDiscoveryCallback: OnDeviceFound, No memory"); return; } - static std::string staticBundleName = bundleName_; - static uint16_t staticSubscribeId = subscribeId; - static DmDeviceInfo staticDeviceInfo = deviceInfo; + jsCallback_ = std::make_unique(bundleName_, subscribeId, 0, deviceInfo); + work->data = reinterpret_cast(jsCallback_.get()); + int ret = uv_queue_work(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) { - DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(staticBundleName); + DmNapiStateJsCallback *callback = reinterpret_cast(work->data); + DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_); if (deviceManagerNapi == nullptr) { - LOGE("OnDeviceFound, deviceManagerNapi not find for bunderName %s", staticBundleName.c_str()); + LOGE("OnDeviceFound, deviceManagerNapi not find for bunderName %s", callback->bundleName_.c_str()); return; } - deviceManagerNapi->OnDeviceFound(staticSubscribeId, staticDeviceInfo); + deviceManagerNapi->OnDeviceFound(callback->subscribeId_, callback->deviceInfo_); delete work; }); if (ret != 0) { @@ -252,21 +271,23 @@ void DmNapiDiscoveryCallback::OnDiscoveryFailed(uint16_t subscribeId, int32_t fa return; } uv_work_t *work = new (std::nothrow) uv_work_t; - if (loop == nullptr) { + if (work == nullptr) { LOGE("DmNapiDiscoveryCallback: OnDiscoveryFailed, No memory"); return; } - static std::string staticBundleName = bundleName_; - static uint16_t staticSubscribeId = subscribeId; - static int32_t staticReason = failedReason; + DmDeviceInfo info; + jsCallback_ = std::make_unique(bundleName_, subscribeId, failedReason, info); + work->data = reinterpret_cast(jsCallback_.get()); + int ret = uv_queue_work(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) { - DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(staticBundleName); + DmNapiStateJsCallback *callback = reinterpret_cast(work->data); + DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_); if (deviceManagerNapi == nullptr) { - LOGE("OnDiscoveryFailed, deviceManagerNapi not find for bunderName %s", staticBundleName.c_str()); + LOGE("OnDiscoveryFailed, deviceManagerNapi not find for bunderName %s", callback->bundleName_.c_str()); return; } - deviceManagerNapi->OnDiscoveryFailed(staticSubscribeId, staticReason); + deviceManagerNapi->OnDiscoveryFailed(callback->subscribeId_, callback->reason_); delete work; }); if (ret != 0) { @@ -309,23 +330,22 @@ void DmNapiAuthenticateCallback::OnAuthResult(const std::string &deviceId, const return; } uv_work_t *work = new (std::nothrow) uv_work_t; - if (loop == nullptr) { + if (work == nullptr) { LOGE("DmNapiAuthenticateCallback: OnAuthResult, No memory"); return; } - static std::string staticBundleName = bundleName_; - static std::string staticDeviceId = deviceId; - static std::string staticToken = token; - static int32_t staticStatus = status; - static int32_t staticReason = reason; + jsCallback_ = std::make_unique(bundleName_, deviceId, token, status, reason); + work->data = reinterpret_cast(jsCallback_.get()); + int ret = uv_queue_work(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) { - DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(staticBundleName); + DmNapiAuthJsCallback *callback = reinterpret_cast(work->data); + DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_); if (deviceManagerNapi == nullptr) { - LOGE("OnAuthResult, deviceManagerNapi not find for bunderName %s", staticBundleName.c_str()); + LOGE("OnAuthResult, deviceManagerNapi not find for bunderName %s", callback->bundleName_.c_str()); return; } - deviceManagerNapi->OnAuthResult(staticDeviceId, staticToken, staticStatus, staticReason); + deviceManagerNapi->OnAuthResult(callback->deviceId_, callback->token_, callback->status_, callback->reason_); delete work; }); if (ret != 0) { @@ -342,22 +362,22 @@ void DmNapiVerifyAuthCallback::OnVerifyAuthResult(const std::string &deviceId, i return; } uv_work_t *work = new (std::nothrow) uv_work_t; - if (loop == nullptr) { + if (work == nullptr) { LOGE("DmNapiVerifyAuthCallback: OnVerifyAuthResult, No memory"); return; } - static std::string staticBundleName = bundleName_; - static std::string staticDeviceId = deviceId; - static int32_t staticCode = resultCode; - static int32_t staticFlag = flag; + jsCallback_ = std::make_unique(bundleName_, deviceId, resultCode, flag); + work->data = reinterpret_cast(jsCallback_.get()); + int ret = uv_queue_work(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) { - DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(staticBundleName); + DmNapiVerifyJsCallback *callback = reinterpret_cast(work->data); + DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_); if (deviceManagerNapi == nullptr) { - LOGE("OnVerifyAuthResult, deviceManagerNapi not find for bunderName %s", staticBundleName.c_str()); + LOGE("OnVerifyAuthResult, deviceManagerNapi not find for bunderName %s", callback->bundleName_.c_str()); return; } - deviceManagerNapi->OnVerifyResult(staticDeviceId, staticCode, staticFlag); + deviceManagerNapi->OnVerifyResult(callback->deviceId_, callback->resultCode_, callback->flag_); delete work; }); if (ret != 0) { @@ -731,7 +751,6 @@ void DeviceManagerNapi::JsToDmBuffer(const napi_env &env, const napi_value &obje void DeviceManagerNapi::JsToJsonObject(const napi_env &env, const napi_value &object, const std::string &fieldStr, nlohmann::json &jsonObj) { - LOGI("JsToJsonObject in."); bool hasProperty = false; NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty)); if (!hasProperty) { @@ -746,7 +765,6 @@ void DeviceManagerNapi::JsToJsonObject(const napi_env &env, const napi_value &ob uint32_t jsProCount = 0; napi_get_property_names(env, jsonField, &jsProNameList); napi_get_array_length(env, jsProNameList, &jsProCount); - LOGI("Property size=%d.", jsProCount); napi_value jsProName = nullptr; napi_value jsProValue = nullptr; @@ -860,6 +878,25 @@ void DeviceManagerNapi::CreateDmCallback(napi_env env, std::string &bundleName, } } +void DeviceManagerNapi::CreateDmCallback(napi_env env, std::string &bundleName, + std::string &eventType, std::string &extra) +{ + LOGE("CreateDmCallback for bundleName %s eventType %s extra=%s", + bundleName.c_str(), eventType.c_str(), extra.c_str()); + if (eventType == DM_NAPI_EVENT_DEVICE_STATE_CHANGE) { + auto iter = g_deviceStateCallbackMap.find(bundleName); + if (iter == g_deviceStateCallbackMap.end()) { + auto callback = std::make_shared(env, bundleName); + int32_t ret = DeviceManager::GetInstance().RegisterDevStateCallback(bundleName, extra, callback); + if (ret != 0) { + LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); + return; + } + g_deviceStateCallbackMap[bundleName] = callback; + } + } +} + void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string &eventType) { if (eventType == DM_NAPI_EVENT_DEVICE_STATE_CHANGE) { @@ -953,27 +990,28 @@ napi_value DeviceManagerNapi::SetUserOperationSync(napi_env env, napi_callback_i } void DeviceManagerNapi::CallGetTrustedDeviceListStatusSync(napi_env env, napi_status &status, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) + DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo) { - for (unsigned int i = 0; i < deviceInfoAsyncCallbackInfo->devList.size(); i++) { + for (unsigned int i = 0; i < deviceInfoListAsyncCallbackInfo->devList.size(); i++) { LOGI("DeviceManager::GetTrustedDeviceList deviceId:%s deviceName:%s deviceTypeId:%d ", - deviceInfoAsyncCallbackInfo->devList[i].deviceId, deviceInfoAsyncCallbackInfo->devList[i].deviceName, - deviceInfoAsyncCallbackInfo->devList[i].deviceTypeId); + deviceInfoListAsyncCallbackInfo->devList[i].deviceId, + deviceInfoListAsyncCallbackInfo->devList[i].deviceName, + deviceInfoListAsyncCallbackInfo->devList[i].deviceTypeId); } napi_value array[DM_NAPI_ARGS_TWO] = {0}; - if (deviceInfoAsyncCallbackInfo->status == 0) { - if (deviceInfoAsyncCallbackInfo->devList.size() > 0) { + if (deviceInfoListAsyncCallbackInfo->status == 0) { + if (deviceInfoListAsyncCallbackInfo->devList.size() > 0) { bool isArray = false; napi_create_array(env, &array[1]); napi_is_array(env, array[1], &isArray); if (isArray == false) { LOGE("napi_create_array fail"); } - for (unsigned int i = 0; i != deviceInfoAsyncCallbackInfo->devList.size(); ++i) { - DeviceInfoToJsArray(env, deviceInfoAsyncCallbackInfo->devList, (int32_t)i, array[1]); + for (unsigned int i = 0; i != deviceInfoListAsyncCallbackInfo->devList.size(); ++i) { + DeviceInfoToJsArray(env, deviceInfoListAsyncCallbackInfo->devList, (int32_t)i, array[1]); } - napi_resolve_deferred(env, deviceInfoAsyncCallbackInfo->deferred, array[1]); + napi_resolve_deferred(env, deviceInfoListAsyncCallbackInfo->deferred, array[1]); LOGE("devList is OK"); } else { LOGE("devList is null"); @@ -981,7 +1019,7 @@ void DeviceManagerNapi::CallGetTrustedDeviceListStatusSync(napi_env env, napi_st } else { napi_create_object(env, &array[0]); SetValueInt32(env, "code", status, array[0]); - napi_reject_deferred(env, deviceInfoAsyncCallbackInfo->deferred, array[0]); + napi_reject_deferred(env, deviceInfoListAsyncCallbackInfo->deferred, array[0]); } } @@ -993,20 +1031,22 @@ void DmNapiDeviceManagerFaCallback::OnCall(const std::string ¶mJson) return; } uv_work_t *work = new (std::nothrow) uv_work_t; - if (loop == nullptr) { + if (work == nullptr) { LOGE("DmNapiDeviceManagerFaCallback: OnCall, No memory"); return; } - static std::string staticBundleName = bundleName_; - static std::string staticParamJson = paramJson; + jsCallback_ = std::make_unique(bundleName_, "", paramJson, 0, 0); + work->data = reinterpret_cast(jsCallback_.get()); + int ret = uv_queue_work(loop, work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int status) { - DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(staticBundleName); + DmNapiAuthJsCallback *callback = reinterpret_cast(work->data); + DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(callback->bundleName_); if (deviceManagerNapi == nullptr) { - LOGE("OnCall, deviceManagerNapi not find for bunderName %s", staticBundleName.c_str()); + LOGE("OnCall, deviceManagerNapi not find for bunderName %s", callback->bundleName_.c_str()); return; } - deviceManagerNapi->OnDmfaCall(staticParamJson); + deviceManagerNapi->OnDmfaCall(callback->token_); delete work; }); if (ret != 0) { @@ -1025,28 +1065,28 @@ void DeviceManagerNapi::OnDmfaCall(const std::string ¶mJson) } void DeviceManagerNapi::CallGetTrustedDeviceListStatus(napi_env env, napi_status &status, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) + DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo) { - for (unsigned int i = 0; i < deviceInfoAsyncCallbackInfo->devList.size(); i++) { + for (unsigned int i = 0; i < deviceInfoListAsyncCallbackInfo->devList.size(); i++) { LOGI("DeviceManager::GetTrustedDeviceList deviceId:%s deviceName:%s deviceTypeId:%d ", - deviceInfoAsyncCallbackInfo->devList[i].deviceId, deviceInfoAsyncCallbackInfo->devList[i].deviceName, - deviceInfoAsyncCallbackInfo->devList[i].deviceTypeId); + deviceInfoListAsyncCallbackInfo->devList[i].deviceId, + deviceInfoListAsyncCallbackInfo->devList[i].deviceName, + deviceInfoListAsyncCallbackInfo->devList[i].deviceTypeId); } napi_value callResult = nullptr; napi_value handler = nullptr; napi_value array[DM_NAPI_ARGS_TWO] = {0}; - if (deviceInfoAsyncCallbackInfo->status == 0) { - if (deviceInfoAsyncCallbackInfo->devList.size() > 0) { + if (deviceInfoListAsyncCallbackInfo->status == 0) { + if (deviceInfoListAsyncCallbackInfo->devList.size() > 0) { bool isArray = false; napi_create_array(env, &array[1]); napi_is_array(env, array[1], &isArray); - if (isArray == false) { + if (!isArray) { LOGE("napi_create_array fail"); } - - for (int32_t i = 0; i != deviceInfoAsyncCallbackInfo->devList.size(); ++i) { - DeviceInfoToJsArray(env, deviceInfoAsyncCallbackInfo->devList, i, array[1]); + for (size_t i = 0; i != deviceInfoListAsyncCallbackInfo->devList.size(); ++i) { + DeviceInfoToJsArray(env, deviceInfoListAsyncCallbackInfo->devList, i, array[1]); } LOGE("devList is OK"); } else { @@ -1057,10 +1097,10 @@ void DeviceManagerNapi::CallGetTrustedDeviceListStatus(napi_env env, napi_status SetValueInt32(env, "code", status, array[0]); } - napi_get_reference_value(env, deviceInfoAsyncCallbackInfo->callback, &handler); + napi_get_reference_value(env, deviceInfoListAsyncCallbackInfo->callback, &handler); if (handler != nullptr) { napi_call_function(env, nullptr, handler, DM_NAPI_ARGS_TWO, &array[0], &callResult); - napi_delete_reference(env, deviceInfoAsyncCallbackInfo->callback); + napi_delete_reference(env, deviceInfoListAsyncCallbackInfo->callback); } else { LOGE("handler is nullptr"); } @@ -1121,14 +1161,8 @@ void DeviceManagerNapi::CallAsyncWorkSync(napi_env env, DeviceInfoAsyncCallbackI (void)env; DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; int32_t ret = 0; - if (deviceInfoAsyncCallbackInfo->isList == 1) { - ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, - deviceInfoAsyncCallbackInfo->extra, - deviceInfoAsyncCallbackInfo->devList); - } else { - ret = DeviceManager::GetInstance().GetLocalDeviceInfo(deviceInfoAsyncCallbackInfo->bundleName, - deviceInfoAsyncCallbackInfo->deviceInfo); - } + ret = DeviceManager::GetInstance().GetLocalDeviceInfo(deviceInfoAsyncCallbackInfo->bundleName, + deviceInfoAsyncCallbackInfo->deviceInfo); if (ret != 0) { LOGE("CallAsyncWorkSync for bunderName %s failed, ret %d", deviceInfoAsyncCallbackInfo->bundleName.c_str(), ret); @@ -1141,11 +1175,7 @@ void DeviceManagerNapi::CallAsyncWorkSync(napi_env env, DeviceInfoAsyncCallbackI [](napi_env env, napi_status status, void *data) { (void)status; DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; - if (deviceInfoAsyncCallbackInfo->isList == 1) { - CallGetTrustedDeviceListStatusSync(env, status, deviceInfoAsyncCallbackInfo); - } else { - CallGetLocalDeviceInfoSync(env, status, deviceInfoAsyncCallbackInfo); - } + CallGetLocalDeviceInfoSync(env, status, deviceInfoAsyncCallbackInfo); napi_delete_async_work(env, deviceInfoAsyncCallbackInfo->asyncWork); delete deviceInfoAsyncCallbackInfo; }, @@ -1162,17 +1192,11 @@ void DeviceManagerNapi::CallAsyncWork(napi_env env, DeviceInfoAsyncCallbackInfo [](napi_env env, void *data) { DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; int32_t ret = 0; - if (deviceInfoAsyncCallbackInfo->isList == 1) { - ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoAsyncCallbackInfo->bundleName, - deviceInfoAsyncCallbackInfo->extra, - deviceInfoAsyncCallbackInfo->devList); - } else { - ret = DeviceManager::GetInstance().GetLocalDeviceInfo(deviceInfoAsyncCallbackInfo->bundleName, - deviceInfoAsyncCallbackInfo->deviceInfo); - } + ret = DeviceManager::GetInstance().GetLocalDeviceInfo(deviceInfoAsyncCallbackInfo->bundleName, + deviceInfoAsyncCallbackInfo->deviceInfo); if (ret != 0) { - LOGE("CallAsyncWork for bunderName %s failed, ret %d", deviceInfoAsyncCallbackInfo->bundleName.c_str(), - ret); + LOGE("CallAsyncWork for bunderName %s failed, ret %d", + deviceInfoAsyncCallbackInfo->bundleName.c_str(), ret); deviceInfoAsyncCallbackInfo->status = -1; return; } @@ -1182,11 +1206,7 @@ void DeviceManagerNapi::CallAsyncWork(napi_env env, DeviceInfoAsyncCallbackInfo [](napi_env env, napi_status status, void *data) { (void)status; DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo = (DeviceInfoAsyncCallbackInfo *)data; - if (deviceInfoAsyncCallbackInfo->isList == 1) { - CallGetTrustedDeviceListStatus(env, status, deviceInfoAsyncCallbackInfo); - } else { - CallGetLocalDeviceInfo(env, status, deviceInfoAsyncCallbackInfo); - } + CallGetLocalDeviceInfo(env, status, deviceInfoAsyncCallbackInfo); napi_delete_async_work(env, deviceInfoAsyncCallbackInfo->asyncWork); delete deviceInfoAsyncCallbackInfo; }, @@ -1194,19 +1214,89 @@ void DeviceManagerNapi::CallAsyncWork(napi_env env, DeviceInfoAsyncCallbackInfo napi_queue_async_work(env, deviceInfoAsyncCallbackInfo->asyncWork); } +void DeviceManagerNapi::CallAsyncWorkSync(napi_env env, + DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo) +{ + napi_value resourceName; + napi_create_string_latin1(env, "GetTrustListInfo", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + (void)env; + DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo = (DeviceInfoListAsyncCallbackInfo *)data; + int32_t ret = 0; + ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoListAsyncCallbackInfo->bundleName, + deviceInfoListAsyncCallbackInfo->extra, + deviceInfoListAsyncCallbackInfo->devList); + if (ret != 0) { + LOGE("CallAsyncWorkSync for bunderName %s failed, ret %d", + deviceInfoListAsyncCallbackInfo->bundleName.c_str(), ret); + deviceInfoListAsyncCallbackInfo->status = -1; + return; + } + deviceInfoListAsyncCallbackInfo->status = 0; + LOGE("CallAsyncWorkSync status %d", deviceInfoListAsyncCallbackInfo->status); + }, + [](napi_env env, napi_status status, void *data) { + (void)status; + DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo = (DeviceInfoListAsyncCallbackInfo *)data; + CallGetTrustedDeviceListStatusSync(env, status, deviceInfoListAsyncCallbackInfo); + napi_delete_async_work(env, deviceInfoListAsyncCallbackInfo->asyncWork); + delete deviceInfoListAsyncCallbackInfo; + }, + (void *)deviceInfoListAsyncCallbackInfo, &deviceInfoListAsyncCallbackInfo->asyncWork); + napi_queue_async_work(env, deviceInfoListAsyncCallbackInfo->asyncWork); +} + +void DeviceManagerNapi::CallAsyncWork(napi_env env, DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo) +{ + napi_value resourceName; + napi_create_string_latin1(env, "GetTrustListInfo", NAPI_AUTO_LENGTH, &resourceName); + DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoListAsyncCallbackInfo->bundleName, + deviceInfoListAsyncCallbackInfo->extra, + deviceInfoListAsyncCallbackInfo->devList); + + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo = (DeviceInfoListAsyncCallbackInfo *)data; + int32_t ret = 0; + ret = DeviceManager::GetInstance().GetTrustedDeviceList(deviceInfoListAsyncCallbackInfo->bundleName, + deviceInfoListAsyncCallbackInfo->extra, + deviceInfoListAsyncCallbackInfo->devList); + if (ret != 0) { + LOGE("CallAsyncWork for bunderName %s failed, ret %d", + deviceInfoListAsyncCallbackInfo->bundleName.c_str(), ret); + deviceInfoListAsyncCallbackInfo->status = -1; + return; + } + deviceInfoListAsyncCallbackInfo->status = 0; + LOGE("CallAsyncWork status %d", deviceInfoListAsyncCallbackInfo->status); + }, + [](napi_env env, napi_status status, void *data) { + (void)status; + DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo = (DeviceInfoListAsyncCallbackInfo *)data; + CallGetTrustedDeviceListStatus(env, status, deviceInfoListAsyncCallbackInfo); + napi_delete_async_work(env, deviceInfoListAsyncCallbackInfo->asyncWork); + delete deviceInfoListAsyncCallbackInfo; + }, + (void *)deviceInfoListAsyncCallbackInfo, &deviceInfoListAsyncCallbackInfo->asyncWork); + napi_queue_async_work(env, deviceInfoListAsyncCallbackInfo->asyncWork); +} + napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info info, - DeviceInfoAsyncCallbackInfo *deviceInfoAsyncCallbackInfo) + DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo) { napi_value result = nullptr; std::string extra = ""; - deviceInfoAsyncCallbackInfo->extra = extra; + deviceInfoListAsyncCallbackInfo->extra = extra; GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); napi_valuetype eventHandleType = napi_undefined; napi_typeof(env, argv[0], &eventHandleType); if (eventHandleType == napi_function) { LOGE("CallDeviceList for argc %d Type = %d", argc, (int)eventHandleType); - napi_create_reference(env, argv[0], 1, &deviceInfoAsyncCallbackInfo->callback); - CallAsyncWork(env, deviceInfoAsyncCallbackInfo); + napi_create_reference(env, argv[0], 1, &deviceInfoListAsyncCallbackInfo->callback); + CallAsyncWork(env, deviceInfoListAsyncCallbackInfo); napi_get_undefined(env, &result); return result; } else { @@ -1214,11 +1304,11 @@ napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info in napi_deferred deferred; napi_value promise = 0; napi_create_promise(env, &deferred, &promise); - deviceInfoAsyncCallbackInfo->deferred = deferred; + deviceInfoListAsyncCallbackInfo->deferred = deferred; char extraString[20]; JsObjectToString(env, argv[0], "extra", extraString, sizeof(extraString)); - deviceInfoAsyncCallbackInfo->extra = extraString; - CallAsyncWorkSync(env, deviceInfoAsyncCallbackInfo); + deviceInfoListAsyncCallbackInfo->extra = extraString; + CallAsyncWorkSync(env, deviceInfoListAsyncCallbackInfo); return promise; } } @@ -1269,23 +1359,22 @@ napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_i DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - auto *deviceInfoAsyncCallbackInfo = new DeviceInfoAsyncCallbackInfo(); - deviceInfoAsyncCallbackInfo->env = env; - deviceInfoAsyncCallbackInfo->devList = devList; - deviceInfoAsyncCallbackInfo->isList = 1; - deviceInfoAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_; + auto *deviceInfoListAsyncCallbackInfo = new DeviceInfoListAsyncCallbackInfo(); + deviceInfoListAsyncCallbackInfo->env = env; + deviceInfoListAsyncCallbackInfo->devList = devList; + deviceInfoListAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_; LOGE("GetTrustedDeviceList for argc %d", argc); if (argc == 0) { std::string extra = ""; - deviceInfoAsyncCallbackInfo->extra = extra; + deviceInfoListAsyncCallbackInfo->extra = extra; napi_deferred deferred; napi_value promise = 0; napi_create_promise(env, &deferred, &promise); - deviceInfoAsyncCallbackInfo->deferred = deferred; - CallAsyncWorkSync(env, deviceInfoAsyncCallbackInfo); + deviceInfoListAsyncCallbackInfo->deferred = deferred; + CallAsyncWorkSync(env, deviceInfoListAsyncCallbackInfo); return promise; } else if (argc == 1) { - return CallDeviceList(env, info, deviceInfoAsyncCallbackInfo); + return CallDeviceList(env, info, deviceInfoListAsyncCallbackInfo); } else if (argc == DM_NAPI_ARGS_TWO) { GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); napi_valuetype valueType; @@ -1299,9 +1388,9 @@ napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_i NAPI_ASSERT(env, eventHandleType == napi_function, "Wrong argument type. Object expected."); char extra[20]; JsObjectToString(env, argv[0], "extra", extra, sizeof(extra)); - deviceInfoAsyncCallbackInfo->extra = extra; - napi_create_reference(env, argv[1], 1, &deviceInfoAsyncCallbackInfo->callback); - CallAsyncWork(env, deviceInfoAsyncCallbackInfo); + deviceInfoListAsyncCallbackInfo->extra = extra; + napi_create_reference(env, argv[1], 1, &deviceInfoListAsyncCallbackInfo->callback); + CallAsyncWork(env, deviceInfoListAsyncCallbackInfo); napi_get_undefined(env, &result); return result; } @@ -1347,7 +1436,6 @@ napi_value DeviceManagerNapi::GetLocalDeviceInfo(napi_env env, napi_callback_inf auto *deviceInfoAsyncCallbackInfo = new DeviceInfoAsyncCallbackInfo(); deviceInfoAsyncCallbackInfo->env = env; deviceInfoAsyncCallbackInfo->deviceInfo = deviceInfo; - deviceInfoAsyncCallbackInfo->isList = 0; deviceInfoAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_; LOGE("GetLocalDeviceInfo for argc %d", argc); if (argc == 0) { @@ -1491,8 +1579,8 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf JsToDmDeviceInfo(env, argv[0], deviceInfo); std::string extraString; JsToDmExtra(env, argv[PARAM_INDEX_ONE], extraString, authAsyncCallbackInfo_.authType); - int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, 1, deviceInfo, - extraString, authCallback); + int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, + authAsyncCallbackInfo_.authType, deviceInfo, extraString, authCallback); if (ret != 0) { LOGE("AuthenticateDevice for bundleName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); } @@ -1557,7 +1645,22 @@ napi_value DeviceManagerNapi::JsOnFrench(napi_env env, int32_t num, napi_value t LOGI("JsOn for bunderName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), eventType.c_str()); deviceManagerWrapper->On(eventType, argv[num + 1]); - CreateDmCallback(env, deviceManagerWrapper->bundleName_, eventType); + if (eventType == DM_NAPI_EVENT_DEVICE_STATE_CHANGE) { + if (num == 1) { + size_t extraLen = 0; + napi_get_value_string_utf8(env, argv[1], nullptr, 0, &extraLen); + NAPI_ASSERT(env, extraLen < DM_NAPI_BUF_LENGTH, "extraLen >= MAXLEN"); + char extra[DM_NAPI_BUF_LENGTH] = {0}; + napi_get_value_string_utf8(env, argv[1], extra, extraLen + 1, &extraLen); + std::string extraString = extra; + LOGI("extra = %s", extraString.c_str()); + CreateDmCallback(env, deviceManagerWrapper->bundleName_, eventType, extraString); + } else { + CreateDmCallback(env, deviceManagerWrapper->bundleName_, eventType); + } + } else { + CreateDmCallback(env, deviceManagerWrapper->bundleName_, eventType); + } napi_value result = nullptr; napi_get_undefined(env, &result); @@ -1570,7 +1673,7 @@ napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr)); if (argc == DM_NAPI_ARGS_THREE) { - LOGI("JsOff in argc == 3"); + LOGI("JsOn in argc == 3"); GET_PARAMS(env, info, DM_NAPI_ARGS_THREE); NAPI_ASSERT(env, argc >= DM_NAPI_ARGS_THREE, "Wrong number of arguments, required 2"); @@ -1580,7 +1683,7 @@ napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) napi_valuetype valueType; napi_typeof(env, argv[1], &valueType); - NAPI_ASSERT(env, valueType == napi_object, "type mismatch for parameter 2"); + NAPI_ASSERT(env, (valueType == napi_string || valueType == napi_object), "type mismatch for parameter 2"); napi_valuetype eventHandleType = napi_undefined; napi_typeof(env, argv[DM_NAPI_ARGS_TWO], &eventHandleType); @@ -1643,7 +1746,7 @@ napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) napi_valuetype valueType; napi_typeof(env, argv[1], &valueType); - NAPI_ASSERT(env, valueType == napi_object, "type mismatch for parameter 2"); + NAPI_ASSERT(env, (valueType == napi_string || valueType == napi_object), "type mismatch for parameter 2"); if (argc > requireArgc) { napi_valuetype eventHandleType = napi_undefined; @@ -1844,6 +1947,209 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) return exports; } +napi_value DeviceManagerNapi::EnumTypeConstructor(napi_env env, napi_callback_info info) +{ + size_t argc = 0; + napi_value args[DM_NAPI_ARGS_ONE] = {0}; + napi_value res = nullptr; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, args, &res, &data); + if (status != napi_ok) { + return nullptr; + } + + return res; +} + +napi_value DeviceManagerNapi::InitDeviceTypeEnum(napi_env env, napi_value exports) +{ + napi_value unknown_type; + napi_value speaker; + napi_value phone; + napi_value tablet; + napi_value wearable; + napi_value car; + napi_value tv; + int32_t refCount = 1; + + napi_create_uint32(env, static_cast(DmDeviceType::DEVICE_TYPE_UNKNOWN), + &unknown_type); + napi_create_uint32(env, static_cast(DmDeviceType::DEVICE_TYPE_AUDIO), + &speaker); + napi_create_uint32(env, static_cast(DmDeviceType::DEVICE_TYPE_PHONE), + &phone); + napi_create_uint32(env, static_cast(DmDeviceType::DEVICE_TYPE_PAD), + &tablet); + napi_create_uint32(env, static_cast(DmDeviceType::DEVICE_TYPE_WATCH), + &wearable); + napi_create_uint32(env, static_cast(DmDeviceType::DEVICE_TYPE_CAR), + &car); + napi_create_uint32(env, static_cast(DmDeviceType::DEVICE_TYPE_TV), + &tv); + + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("UNKNOWN_TYPE", unknown_type), + DECLARE_NAPI_STATIC_PROPERTY("SPEAKER", speaker), + DECLARE_NAPI_STATIC_PROPERTY("PHONE", phone), + DECLARE_NAPI_STATIC_PROPERTY("TABLET", tablet), + DECLARE_NAPI_STATIC_PROPERTY("WEARABLE", wearable), + DECLARE_NAPI_STATIC_PROPERTY("CAR", car), + DECLARE_NAPI_STATIC_PROPERTY("TV", tv), + }; + + napi_value result = nullptr; + napi_define_class(env, "DeviceType", NAPI_AUTO_LENGTH, EnumTypeConstructor, + nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_create_reference(env, result, refCount, &deviceTypeEnumConstructor_); + napi_set_named_property(env, exports, "DeviceType", result); + return exports; +} + +napi_value DeviceManagerNapi::InitDeviceStateChangeActionEnum(napi_env env, napi_value exports) +{ + napi_value device_state_online; + napi_value device_state_ready; + napi_value device_state_offline; + napi_value device_state_change; + int32_t refCount = 1; + + napi_create_uint32(env, static_cast(DmDeviceState::DEVICE_STATE_ONLINE), + &device_state_online); + napi_create_uint32(env, static_cast(DmDeviceState::DEVICE_INFO_READY), + &device_state_ready); + napi_create_uint32(env, static_cast(DmDeviceState::DEVICE_STATE_OFFLINE), + &device_state_offline); + napi_create_uint32(env, static_cast(DmDeviceState::DEVICE_INFO_CHANGED), + &device_state_change); + + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("ONLINE", device_state_online), + DECLARE_NAPI_STATIC_PROPERTY("READY", device_state_ready), + DECLARE_NAPI_STATIC_PROPERTY("OFFLINE", device_state_offline), + DECLARE_NAPI_STATIC_PROPERTY("CHANGE", device_state_change), + }; + + napi_value result = nullptr; + napi_define_class(env, "DeviceStateChangeAction", NAPI_AUTO_LENGTH, EnumTypeConstructor, + nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_create_reference(env, result, refCount, &deviceStateChangeActionEnumConstructor_); + napi_set_named_property(env, exports, "DeviceStateChangeAction", result); + return exports; +} + +napi_value DeviceManagerNapi::InitDiscoverModeEnum(napi_env env, napi_value exports) +{ + napi_value discover_mode_passive; + napi_value discover_mode_active; + int32_t refCount = 1; + + napi_create_uint32(env, static_cast(DmDiscoverMode::DM_DISCOVER_MODE_PASSIVE), + &discover_mode_passive); + napi_create_uint32(env, static_cast(DmDiscoverMode::DM_DISCOVER_MODE_ACTIVE), + &discover_mode_active); + + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("DISCOVER_MODE_PASSIVE", discover_mode_passive), + DECLARE_NAPI_STATIC_PROPERTY("DISCOVER_MODE_ACTIVE", discover_mode_active), + }; + + napi_value result = nullptr; + napi_define_class(env, "DiscoverMode", NAPI_AUTO_LENGTH, EnumTypeConstructor, + nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_create_reference(env, result, refCount, &discoverModeEnumConstructor_); + napi_set_named_property(env, exports, "DiscoverMode", result); + return exports; +} + +napi_value DeviceManagerNapi::InitExchangeMediumEnum(napi_env env, napi_value exports) +{ + napi_value medium_auto; + napi_value medium_ble; + napi_value medium_coap; + napi_value medium_usb; + int32_t refCount = 1; + + napi_create_uint32(env, static_cast(DmExchangeMedium::DM_AUTO), + &medium_auto); + napi_create_uint32(env, static_cast(DmExchangeMedium::DM_BLE), + &medium_ble); + napi_create_uint32(env, static_cast(DmExchangeMedium::DM_COAP), + &medium_coap); + napi_create_uint32(env, static_cast(DmExchangeMedium::DM_USB), + &medium_usb); + + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("AUTO", medium_auto), + DECLARE_NAPI_STATIC_PROPERTY("BLE", medium_ble), + DECLARE_NAPI_STATIC_PROPERTY("COAP", medium_coap), + DECLARE_NAPI_STATIC_PROPERTY("USB", medium_usb), + }; + + napi_value result = nullptr; + napi_define_class(env, "ExchangeMedium", NAPI_AUTO_LENGTH, EnumTypeConstructor, + nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_create_reference(env, result, refCount, &exchangeMediumEnumConstructor_); + napi_set_named_property(env, exports, "ExchangeMedium", result); + return exports; +} + +napi_value DeviceManagerNapi::InitExchangeFreqEnum(napi_env env, napi_value exports) +{ + napi_value low; + napi_value mid; + napi_value high; + napi_value super_high; + int32_t refCount = 1; + + napi_create_uint32(env, static_cast(DmExchangeFreq::DM_LOW), + &low); + napi_create_uint32(env, static_cast(DmExchangeFreq::DM_MID), + &mid); + napi_create_uint32(env, static_cast(DmExchangeFreq::DM_HIGH), + &high); + napi_create_uint32(env, static_cast(DmExchangeFreq::DM_SUPER_HIGH), + &super_high); + + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("LOW", low), + DECLARE_NAPI_STATIC_PROPERTY("MID", mid), + DECLARE_NAPI_STATIC_PROPERTY("HIGH", high), + DECLARE_NAPI_STATIC_PROPERTY("SUPER_HIGH", super_high), + }; + + napi_value result = nullptr; + napi_define_class(env, "ExchangeFreq", NAPI_AUTO_LENGTH, EnumTypeConstructor, + nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_create_reference(env, result, refCount, &exchangeFreqEnumConstructor_); + napi_set_named_property(env, exports, "ExchangeFreq", result); + return exports; +} + +napi_value DeviceManagerNapi::InitSubscribeCapEnum(napi_env env, napi_value exports) +{ + napi_value subscribe_capability_ddmp; + napi_value subscribe_capability_osd; + int32_t refCount = 1; + + napi_create_uint32(env, static_cast(DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP), + &subscribe_capability_ddmp); + napi_create_uint32(env, static_cast(DM_NAPI_SUBSCRIBE_CAPABILITY_OSD), + &subscribe_capability_osd); + + napi_property_descriptor desc[] = { + DECLARE_NAPI_STATIC_PROPERTY("SUBSCRIBE_CAPABILITY_DDMP", subscribe_capability_ddmp), + DECLARE_NAPI_STATIC_PROPERTY("SUBSCRIBE_CAPABILITY_OSD", subscribe_capability_osd), + }; + + napi_value result = nullptr; + napi_define_class(env, "SubscribeCap", NAPI_AUTO_LENGTH, EnumTypeConstructor, + nullptr, sizeof(desc) / sizeof(*desc), desc, &result); + napi_create_reference(env, result, refCount, &subscribeCapEnumConstructor_); + napi_set_named_property(env, exports, "SubscribeCap", result); + return exports; +} + /* * Function registering all props and functions of ohos.distributedhardware */ @@ -1851,6 +2157,12 @@ static napi_value Export(napi_env env, napi_value exports) { LOGI("Export() is called!"); DeviceManagerNapi::Init(env, exports); + DeviceManagerNapi::InitDeviceTypeEnum(env, exports); + DeviceManagerNapi::InitDeviceStateChangeActionEnum(env, exports); + DeviceManagerNapi::InitDiscoverModeEnum(env, exports); + DeviceManagerNapi::InitExchangeMediumEnum(env, exports); + DeviceManagerNapi::InitExchangeFreqEnum(env, exports); + DeviceManagerNapi::InitSubscribeCapEnum(env, exports); return exports; } diff --git a/services/devicemanagerservice/include/authentication/authentication.h b/services/devicemanagerservice/include/authentication/authentication.h index 67ca0c3ee86b1e0fccae4eb20927cda40dc3a829..7c59f31c49fe03087aa33a5f99a1ab6663f45866 100644 --- a/services/devicemanagerservice/include/authentication/authentication.h +++ b/services/devicemanagerservice/include/authentication/authentication.h @@ -24,9 +24,9 @@ class DmAuthManager; class IAuthentication { public: virtual ~IAuthentication() = default; - virtual int32_t ShowAuthInfo(int32_t code, std::shared_ptr authManager) = 0; - virtual int32_t StartAuth(int32_t code, std::shared_ptr authManager) = 0; - virtual int32_t VerifyAuthentication(std::string pinToken, int32_t code, const std::string &authParam) = 0; + virtual int32_t ShowAuthInfo(std::string &authToken, std::shared_ptr authManager) = 0; + virtual int32_t StartAuth(std::string &authToken, std::shared_ptr authManager) = 0; + virtual int32_t VerifyAuthentication(std::string &authToken, const std::string &authParam) = 0; }; using CreateIAuthAdapterFuncPtr = IAuthentication *(*)(void); diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 6a7ae6b85aeb7a5a7f90f58e97bf559765801835..9e1dd3b69b87226ad14636df7e4f07bcac202678 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -86,7 +86,6 @@ typedef struct DmAuthRequestContext { std::string appThumbnail; std::string token; int32_t reason; - int32_t aceId; std::vector syncGroupList; } DmAuthRequestContext; @@ -110,10 +109,11 @@ typedef struct DmAuthResponseContext { std::string appIcon; std::string appThumbnail; std::string token; + std::string authToken; + int32_t pageId; int64_t requestId; int32_t code; int32_t state; - int32_t aceId; std::vector syncGroupList; } DmAuthResponseContext; @@ -131,7 +131,6 @@ public: const std::string &extra); int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId); int32_t VerifyAuthentication(const std::string &authParam); - void VerifyPinAuthAuthentication(const std::string &action); void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result); void OnSessionClosed(int32_t sessionId); void OnDataReceived(int32_t sessionId, std::string message); @@ -164,7 +163,8 @@ public: int32_t GetAuthenticationParam(DmAuthParam &authParam); int32_t OnUserOperation(int32_t action); void UserSwitchEventCallback(int32_t userId); - void ClosePage(const int32_t &id); + int32_t SetPageId(int32_t pageId); + int32_t SetReason(int32_t reason, int32_t state); private: std::shared_ptr softbusConnector_; @@ -180,6 +180,7 @@ private: std::map> timerMap_; std::shared_ptr dmAbilityMgr_; bool isCryptoSupport_ = false; + bool isFinishOfLocal_ = true; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/config/json_config.h b/services/devicemanagerservice/include/config/json_config.h index a1c495cc0cf4d0215e66f50f16dff67664cdeb39..04c929323feca02bff158421aef27ba12ff72efe 100644 --- a/services/devicemanagerservice/include/config/json_config.h +++ b/services/devicemanagerservice/include/config/json_config.h @@ -38,6 +38,14 @@ const std::string adapterJsonConfigString = "funcName": "CreateDeviceProfileObject", "soName": "libdevicemanagerext_profile.z.so", "soPath": "/system/lib/" + }, + { + "name": "device_decision", + "type": "DECISION", + "version": "1.0", + "funcName": "CreateDeviceDecisionObject", + "soName": "libdevicemanagerext_decision.z.so", + "soPath": "/system/lib/" } ] })"; diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index a7f5f3aa7a9c193955841495ec4693df583cdb06..a957f42a83d211cfe2e686401bc6fa317c027f99 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -48,8 +48,6 @@ public: static bool IsDeviceOnLine(const std::string &deviceId); static int32_t GetUdidByNetworkId(const char *networkId, std::string &udid); static int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid); - static int32_t GetNodeKeyInfoByNetworkId(const char *networkId, NodeDeviceInfoKey key, uint8_t *info, - int32_t infoLen); public: SoftbusConnector(); diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index aedfc875dfa0cd9a280ed8b59b97eee6eb76ae63..d5e63692861a9a54f863e885d19ee4bedd5e9969 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -49,6 +49,8 @@ public: int32_t VerifyAuthentication(const std::string &authParam); int32_t GetFaParam(std::string &pkgName, DmAuthParam &authParam); int32_t SetUserOperation(std::string &pkgName, int32_t action); + int32_t RegisterDevStateCallback(const std::string &pkgName, const std::string &extra); + int32_t UnRegisterDevStateCallback(const std::string &pkgName, const std::string &extra); private: DeviceManagerService() = default; bool intFlag_ = false; diff --git a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h index 9dfe5b1597fa5d587615cf0ac6619b573b360cd9..9a9fbfc515bb2229fd343d5231e2ab064d4839f4 100644 --- a/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h +++ b/services/devicemanagerservice/include/deviceinfo/dm_device_info_manager.h @@ -29,11 +29,12 @@ class DmDeviceInfoManager { public: DmDeviceInfoManager(std::shared_ptr &softbusConnectorPtr); int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, - std::vector &deviceList); + std::vector &deviceList); int32_t GetLocalDeviceInfo(DmDeviceInfo &info); private: std::shared_ptr softbusConnector_; + std::string decisionSoName_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index 332976cdcb31dc1aeb9bed4f00bb97dd3d9eeaaa..7817313fc7a3af962550f2886f9560afa8ee4cbc 100755 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -36,6 +36,10 @@ public: std::shared_ptr listener, std::shared_ptr hiChainConnector); ~DmDeviceStateManager(); + int32_t RegisterProfileListener(const std::string &pkgName, const DmDeviceInfo &info); + int32_t UnRegisterProfileListener(const std::string &pkgName, const DmDeviceInfo &info); + void PostDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info); + void PostDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info); void OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info); void OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info); void OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &info); @@ -45,6 +49,9 @@ public: void RegisterOffLineTimer(const DmDeviceInfo &deviceInfo); void StartOffLineTimer(const DmDeviceInfo &deviceInfo); void DeleteTimeOutGroup(std::string deviceId); + void RegisterDevStateCallback(const std::string &pkgName, const std::string &extra); + void UnRegisterDevStateCallback(const std::string &pkgName, const std::string &extra); + private: std::string profileSoName_; std::mutex timerMapMutex_; @@ -52,8 +59,11 @@ private: std::shared_ptr softbusConnector_; std::shared_ptr listener_; std::map remoteDeviceInfos_; + std::map decisionInfos_; std::map> timerMap_; + std::map deviceinfoMap_; std::shared_ptr hiChainConnector_; + std::string decisionSoName_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp index 922c5cdfc4747ae13e083e3c9f9f8d44e31baccc..77c7126ad642f8270a2cfca5aed5db5110448b72 100644 --- a/services/devicemanagerservice/src/authentication/auth_message_processor.cpp +++ b/services/devicemanagerservice/src/authentication/auth_message_processor.cpp @@ -128,9 +128,6 @@ void AuthMessageProcessor::CreateResponseAuthMessage(nlohmann::json &json) json[TAG_REPLY] = authResponseContext_->reply; json[TAG_DEVICE_ID] = authResponseContext_->deviceId; json[TAG_TOKEN] = authResponseContext_->token; - // json[TAG_GROUPIDS] = authResponseContext_->deviceId; //? - LOGI("AuthMessageProcessor::ParseAuthResponseMessage %d,%d", authResponseContext_->reply, - authResponseContext_->code); LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s", authResponseContext_->deviceId.c_str()); if (authResponseContext_->reply == 0) { std::string groupId = authResponseContext_->groupId; @@ -141,11 +138,11 @@ void AuthMessageProcessor::CreateResponseAuthMessage(nlohmann::json &json) return; } groupId = jsonObject[TAG_GROUP_ID]; - json[PIN_CODE_KEY] = authResponseContext_->code; json[TAG_NET_ID] = authResponseContext_->networkId; json[TAG_REQUEST_ID] = authResponseContext_->requestId; json[TAG_GROUP_ID] = groupId; json[TAG_GROUP_NAME] = authResponseContext_->groupName; + json[TAG_AUTH_TOKEN] = authResponseContext_->authToken; LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s,%s", groupId.c_str(), authResponseContext_->groupName.c_str()); } @@ -220,11 +217,11 @@ void AuthMessageProcessor::ParseAuthResponseMessage(nlohmann::json &json) authResponseContext_->deviceId = json[TAG_DEVICE_ID]; authResponseContext_->token = json[TAG_TOKEN]; if (authResponseContext_->reply == 0) { - authResponseContext_->code = json[PIN_CODE_KEY]; authResponseContext_->networkId = json[TAG_NET_ID]; authResponseContext_->requestId = json[TAG_REQUEST_ID]; authResponseContext_->groupId = json[TAG_GROUP_ID]; authResponseContext_->groupName = json[TAG_GROUP_NAME]; + authResponseContext_->authToken = json[TAG_AUTH_TOKEN]; LOGI("AuthMessageProcessor::ParseAuthResponseMessage %s,%s", authResponseContext_->groupId.c_str(), authResponseContext_->groupName.c_str()); } diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 4188f510dd010e998e84156966ecd859198fd3fd..b45af3e11c017a9a73d6c84043f30f450e869dc4 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -80,7 +80,7 @@ DmAuthManager::~DmAuthManager() int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { - LOGE("DmAuthManager::AuthenticateDevice start"); + LOGE("DmAuthManager::AuthenticateDevice start auth type %d", authType); std::shared_ptr authentication = authenticationMap_[authType]; if (authentication == nullptr) { LOGE("DmAuthManager::AuthenticateDevice authType %d not support.", authType); @@ -148,14 +148,12 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st LOGI(" DmAuthManager::UnAuthenticateDevice failed pkgName is null"); return DM_FAILED; } - uint8_t udid[UDID_BUF_LEN] = {0}; - int32_t ret = SoftbusConnector::GetNodeKeyInfoByNetworkId(deviceId.c_str(), NodeDeviceInfoKey::NODE_KEY_UDID, udid, - sizeof(udid)); + std::string deviceUdid; + int32_t ret = SoftbusConnector::GetUdidByNetworkId(deviceId.c_str(), deviceUdid); if (ret != DM_OK) { LOGE("UnAuthenticateDevice GetNodeKeyInfo failed"); return DM_FAILED; } - std::string deviceUdid = (char *)udid; std::string groupId = ""; std::vector groupList; @@ -175,16 +173,19 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam) { LOGI("DmAuthManager::VerifyAuthentication"); + if (authResponseContext_ == nullptr) { + LOGI("authResponseContext_ is not init"); + return DM_FAILED; + } std::shared_ptr ptr; - if (authenticationMap_.find(1) == authenticationMap_.end() + if (authenticationMap_.find(authResponseContext_->authType) == authenticationMap_.end() || timerMap_.find(INPUT_TIMEOUT_TASK) == timerMap_.end()) { LOGE("DmAuthManager::authenticationMap_ is null"); return DM_FAILED; } timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); - - ptr = authenticationMap_[1]; - int32_t ret = ptr->VerifyAuthentication(authRequestContext_->token, authResponseContext_->code, authParam); + ptr = authenticationMap_[authResponseContext_->authType]; + int32_t ret = ptr->VerifyAuthentication(authResponseContext_->authToken, authParam); switch (ret) { case DM_OK: authRequestState_->TransitionTo(std::make_shared()); @@ -194,7 +195,6 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam) DM_AUTH_INPUT_FAILED, ""); break; default: - CancelDisplay(); authRequestContext_->reason = DM_AUTH_INPUT_FAILED; authResponseContext_->state = authRequestState_->GetStateType(); authRequestState_->TransitionTo(std::make_shared()); @@ -304,9 +304,12 @@ void DmAuthManager::OnDataReceived(int32_t sessionId, std::string message) case MSG_TYPE_REQ_AUTH_TERMINATE: if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) { + isFinishOfLocal_ = false; authResponseState_->TransitionTo(std::make_shared()); } else if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { + isFinishOfLocal_ = false; + authResponseContext_->state = authRequestState_->GetStateType(); authRequestState_->TransitionTo(std::make_shared()); } break; @@ -329,7 +332,13 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); return; } - authResponseContext_->code = GeneratePincode(); + nlohmann::json jsonObj; + jsonObj[PIN_CODE_KEY] = GeneratePincode(); + jsonObj[PIN_TOKEN] = authResponseContext_->token; + jsonObj[QR_CODE_KEY] = GenerateGroupName(); + jsonObj[NFC_CODE_KEY] = GenerateGroupName(); + authResponseContext_->authToken = jsonObj.dump(); + LOGI("DmAuthManager::AddMember start %s", authResponseContext_->authToken.c_str()); authResponseContext_->groupId = groupId; authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); @@ -409,7 +418,7 @@ void DmAuthManager::RespNegotiate(const int32_t &sessionId) char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); bool ret = hiChainConnector_->IsDevicesInGroup(authResponseContext_->localDeviceId, localDeviceId); - if (ret != true) { + if (!ret) { LOGE("DmAuthManager::EstablishAuthChannel device is in group"); authResponseContext_->reply = DM_AUTH_PEER_REJECT; } else { @@ -514,10 +523,16 @@ int32_t DmAuthManager::CreateGroup() int32_t DmAuthManager::AddMember(const std::string &deviceId) { LOGI("DmAuthManager::AddMember start"); + nlohmann::json jsonObj = nlohmann::json::parse(authResponseContext_->authToken, nullptr, false); + if (jsonObj.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + LOGI("DmAuthManager::AddMember start %s", authResponseContext_->authToken.c_str()); nlohmann::json jsonObject; jsonObject[TAG_GROUP_ID] = authResponseContext_->groupId; jsonObject[TAG_GROUP_NAME] = authResponseContext_->groupName; - jsonObject[PIN_CODE_KEY] = authResponseContext_->code; + jsonObject[PIN_CODE_KEY] = jsonObj[PIN_CODE_KEY]; jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; std::string connectInfo = jsonObject.dump(); @@ -529,7 +544,7 @@ int32_t DmAuthManager::AddMember(const std::string &deviceId) return DM_FAILED; } LOGI("DmAuthManager::authRequestContext CancelDisplay start"); - Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->aceId); + Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); return DM_OK; } @@ -559,7 +574,12 @@ void DmAuthManager::AuthenticateFinish() LOGI("DmAuthManager::AuthenticateFinish start"); if (authResponseState_ != nullptr) { if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH) { - Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->aceId); + Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); + } + if (isFinishOfLocal_) { + authMessageProcessor_->SetResponseContext(authResponseContext_); + std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); + softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); } if (!timerMap_.empty()) { for (auto &iter : timerMap_) { @@ -567,21 +587,21 @@ void DmAuthManager::AuthenticateFinish() } timerMap_.clear(); } + isFinishOfLocal_ = true; authResponseContext_ = nullptr; authResponseState_ = nullptr; authMessageProcessor_ = nullptr; } else if (authRequestState_ != nullptr) { - if (authResponseContext_->reply != DM_AUTH_BUSINESS_BUSY) { + if (isFinishOfLocal_) { authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); } else { - authRequestContext_->reason = DM_AUTH_BUSINESS_BUSY; - authResponseContext_->state = AuthState::AUTH_REQUEST_INIT; + authRequestContext_->reason = authResponseContext_->reply; } if (authResponseContext_->state == AuthState::AUTH_REQUEST_INPUT) { - Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->aceId); + Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); } listener_->OnAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, @@ -595,6 +615,7 @@ void DmAuthManager::AuthenticateFinish() } timerMap_.clear(); } + isFinishOfLocal_ = true; authRequestContext_ = nullptr; authResponseContext_ = nullptr; authRequestState_ = nullptr; @@ -662,7 +683,12 @@ int32_t DmAuthManager::SetAuthResponseState(std::shared_ptr a int32_t DmAuthManager::GetPinCode() { - return authResponseContext_->code; + nlohmann::json jsonObj = nlohmann::json::parse(authResponseContext_->authToken, nullptr, false); + if (jsonObj.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + return jsonObj[PIN_CODE_KEY]; } void DmAuthManager::ShowConfigDialog() @@ -693,25 +719,25 @@ void DmAuthManager::ShowAuthInfoDialog() { LOGI("DmAuthManager::ShowAuthInfoDialog start"); std::shared_ptr ptr; - if (authenticationMap_.find(1) == authenticationMap_.end()) { + if (authenticationMap_.find(authResponseContext_->authType) == authenticationMap_.end()) { LOGE("DmAuthManager::authenticationMap_ is null"); return; } - ptr = authenticationMap_[1]; - LOGI("ShowAuthInfoDialog code:%d", authResponseContext_->code); - ptr->ShowAuthInfo(authResponseContext_->code, shared_from_this()); + ptr = authenticationMap_[authResponseContext_->authType]; + LOGI("ShowAuthInfoDialog authToken:%s", authResponseContext_->authToken.c_str()); + ptr->ShowAuthInfo(authResponseContext_->authToken, shared_from_this()); } void DmAuthManager::ShowStartAuthDialog() { LOGI("DmAuthManager::ShowStartAuthDialog start"); std::shared_ptr ptr; - if (authenticationMap_.find(1) == authenticationMap_.end()) { + if (authenticationMap_.find(authResponseContext_->authType) == authenticationMap_.end()) { LOGE("DmAuthManager::authenticationMap_ is null"); return; } - ptr = authenticationMap_[1]; - ptr->StartAuth(authResponseContext_->code, shared_from_this()); + ptr = authenticationMap_[authResponseContext_->authType]; + ptr->StartAuth(authResponseContext_->authToken, shared_from_this()); } int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) @@ -720,6 +746,11 @@ int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) LOGI("dmAbilityMgr_ is nullptr"); return DM_POINT_NULL; } + + if (authResponseContext_ == nullptr) { + LOGI("authResponseContext_ is not init"); + return DM_FAILED; + } dmAbilityMgr_->StartAbilityDone(); AbilityRole role = dmAbilityMgr_->GetAbilityRole(); @@ -740,6 +771,11 @@ int32_t DmAuthManager::GetAuthenticationParam(DmAuthParam &authParam) int32_t DmAuthManager::OnUserOperation(int32_t action) { + if (authResponseContext_ == nullptr) { + LOGI("authResponseContext_ is not init"); + return DM_FAILED; + } + switch (action) { case USER_OPERATION_TYPE_ALLOW_AUTH: case USER_OPERATION_TYPE_CANCEL_AUTH: @@ -796,27 +832,20 @@ void DmAuthManager::UserSwitchEventCallback (int32_t userId) } } -void DmAuthManager::VerifyPinAuthAuthentication(const std::string &action) +int32_t DmAuthManager::SetPageId(int32_t pageId) { - LOGI("DmAuthManager::VerifyPinAuthAuthentication"); - if (timerMap_.find(INPUT_TIMEOUT_TASK) == timerMap_.end()) { - return; - } - timerMap_[INPUT_TIMEOUT_TASK]->Stop(SESSION_CANCEL_TIMEOUT); - if (action == "0") { - authRequestState_->TransitionTo(std::make_shared()); - } - if (action == "1") { - authRequestContext_->reason = DM_AUTH_INPUT_FAILED; - authResponseContext_->state = authRequestState_->GetStateType(); - authRequestState_->TransitionTo(std::make_shared()); - } - LOGI("DmAuthManager::VerifyAuthentication complete"); + authResponseContext_->pageId = pageId; + return DM_OK; } -void DmAuthManager::ClosePage(const int32_t &id) +int32_t DmAuthManager::SetReason(int32_t reason, int32_t state) { - authResponseContext_->aceId = id; + if (state < AuthState::AUTH_REQUEST_FINISH) { + authRequestContext_->reason = reason; + } + authResponseContext_->state = state; + authResponseContext_->reply = reason; + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index f3278fe8e811b45d325d7e0f0c53824a4297eced..a202a09d7773064c192ac7c0bc7bc80494bee014 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -237,21 +237,6 @@ int32_t SoftbusConnector::StopDiscovery(uint16_t subscribeId) return DM_OK; } -int32_t SoftbusConnector::GetNodeKeyInfoByNetworkId(const char *networkId, NodeDeviceInfoKey key, uint8_t *info, - int32_t infoLen) -{ - LOGI("GetNodeKeyInfoByNetworkId begin"); - - int32_t ret = GetNodeKeyInfo(DM_PKG_NAME.c_str(), networkId, key, info, infoLen); - if (ret != DM_OK) { - LOGE("GetNodeKeyInfoByNetworkId GetNodeKeyInfo failed"); - return DM_FAILED; - } - - LOGI("SoftbusConnector::GetNodeKeyInfoByNetworkId completed"); - return DM_OK; -} - int32_t SoftbusConnector::GetUdidByNetworkId(const char *networkId, std::string &udid) { LOGI("GetUdidByNetworkId begin"); diff --git a/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp b/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp index 897800efe5a5465b61b69f03c87eb34d600e8cbc..9ef388b1c3176f9c95ff23e7be8673a752beb4bd 100644 --- a/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp +++ b/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp @@ -73,7 +73,6 @@ DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data) mStatus_ = DmTimerStatus::DM_STATUS_RUNNING; mThread_ = std::thread(&DmTimer::WaitForTimeout, this); mThread_.detach(); - return mStatus_; } @@ -87,12 +86,9 @@ void DmTimer::Stop(int32_t code) if (mTimeFd_[1]) { char event = 'S'; if (write(mTimeFd_[1], &event, 1) < 0) { - LOGE("DmTimer %s Stop timer failed, errno %d", mTimerName_.c_str(), errno); return; } - LOGI("DmTimer %s Stop success", mTimerName_.c_str()); } - return; } void DmTimer::WaitForTimeout() @@ -122,7 +118,6 @@ void DmTimer::WaitForTimeout() Release(); LOGE("DmTimer %s end timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_); } - return; } int32_t DmTimer::CreateTimeFd() diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index a5f33b609193ee288ac7aebf569854318f89ea69..cda681629c4ac9db5dee1f4785e55dff8109a551 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -299,5 +299,17 @@ int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t act authMgr_->OnUserOperation(action); return DM_OK; } + +int32_t DeviceManagerService::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra) +{ + deviceStateMgr_->RegisterDevStateCallback(pkgName, extra); + return DM_OK; +} + +int32_t DeviceManagerService::UnRegisterDevStateCallback(const std::string &pkgName, const std::string &extra) +{ + deviceStateMgr_->UnRegisterDevStateCallback(pkgName, extra); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_service_listener.cpp b/services/devicemanagerservice/src/device_manager_service_listener.cpp index 108fefb2e8502b949ed7d29307fbeab8c26479a1..432481830ed686ee0e793095c630780c4c82025b 100644 --- a/services/devicemanagerservice/src/device_manager_service_listener.cpp +++ b/services/devicemanagerservice/src/device_manager_service_listener.cpp @@ -33,9 +33,14 @@ void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgNam std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); + pReq->SetPkgName(pkgName); pReq->SetDeviceState(state); pReq->SetDeviceInfo(info); - ipcServerListener_.SendAll(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + if (pkgName == DM_PKG_NAME) { + ipcServerListener_.SendAll(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } else { + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } } void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, diff --git a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp index dcf240abf089cfb91eb3b53d8357e4ea853aae11..5138eb9002e5a6e9234696840a9e7c22a7bbbf0a 100644 --- a/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp +++ b/services/devicemanagerservice/src/deviceinfo/dm_device_info_manager.cpp @@ -24,6 +24,7 @@ DmDeviceInfoManager::DmDeviceInfoManager(std::shared_ptr &soft : softbusConnector_(softbusConnectorPtr) { LOGI("DmDeviceInfoManager constructor"); + decisionSoName_ = "libdevicemanagerext_decision.z.so"; } int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, @@ -36,9 +37,8 @@ int32_t DmDeviceInfoManager::GetTrustedDeviceList(const std::string &pkgName, co } if (!extra.empty() && !deviceList.empty()) { - std::string soName; DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); - std::shared_ptr decisionAdapter = adapterMgrPtr.GetDecisionAdapter(soName); + std::shared_ptr decisionAdapter = adapterMgrPtr.GetDecisionAdapter(decisionSoName_); if (decisionAdapter != nullptr) { decisionAdapter->FilterDeviceList(deviceList, extra); } else { diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 794837bc78d2df1ff3d652b9c00cc18517db550a..1cef6db5644e8e04a502580e21820ae27e4a98a5 100755 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -40,6 +40,7 @@ DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr sof : softbusConnector_(softbusConnector), listener_(listener), hiChainConnector_(hiChainConnector) { profileSoName_ = "libdevicemanagerext_profile.z.so"; + decisionSoName_ = "libdevicemanagerext_decision.z.so"; LOGI("DmDeviceStateManager constructor"); } @@ -51,16 +52,13 @@ DmDeviceStateManager::~DmDeviceStateManager() } } -void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) +int32_t DmDeviceStateManager::RegisterProfileListener(const std::string &pkgName, const DmDeviceInfo &info) { - LOGI("OnDeviceOnline function is called back with pkgName: %s", pkgName.c_str()); - RegisterOffLineTimer(info); DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(profileSoName_); if (profileAdapter != nullptr) { - uint8_t udid[UDID_BUF_LEN + 1] = {0}; - int32_t ret = SoftbusConnector::GetNodeKeyInfoByNetworkId(info.deviceId, - NodeDeviceInfoKey::NODE_KEY_UDID, udid, sizeof(udid)); + std::string deviceUdid; + int32_t ret = SoftbusConnector::GetUdidByNetworkId(info.deviceId, deviceUdid); if (ret == DM_OK) { std::string uuid; DmDeviceInfo saveInfo = info; @@ -69,22 +67,16 @@ void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDe std::lock_guard mutexLock(remoteDeviceInfosMutex_); remoteDeviceInfos_[uuid] = saveInfo; } - std::string deviceUdid = (char *)udid; LOGI("RegisterProfileListener in, deviceId = %s, deviceUdid = %s, uuid = %s", info.deviceId, deviceUdid.c_str(), uuid.c_str()); profileAdapter->RegisterProfileListener(pkgName, deviceUdid, shared_from_this()); } } - if (listener_ != nullptr) { - DmDeviceState state = DEVICE_STATE_ONLINE; - listener_->OnDeviceStateChange(pkgName, state, info); - } + return DM_OK; } -void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) +int32_t DmDeviceStateManager::UnRegisterProfileListener(const std::string &pkgName, const DmDeviceInfo &info) { - LOGI("OnDeviceOnline function is called with pkgName: %s", pkgName.c_str()); - StartOffLineTimer(info); DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); std::shared_ptr profileAdapter = adapterMgrPtr.GetProfileAdapter(profileSoName_); if (profileAdapter != nullptr) { @@ -97,10 +89,89 @@ void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmD remoteDeviceInfos_.erase(std::string(info.deviceId)); } } + return DM_OK; +} + +void DmDeviceStateManager::PostDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) +{ + LOGI("DmDeviceStateManager::PostDeviceOnline in"); + if (listener_ != nullptr) { + DmDeviceState state = DEVICE_STATE_ONLINE; + listener_->OnDeviceStateChange(pkgName, state, info); + } + LOGI("DmDeviceStateManager::PostDeviceOnline out"); +} + +void DmDeviceStateManager::PostDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) +{ + LOGI("DmDeviceStateManager::PostDeviceOffline in"); if (listener_ != nullptr) { DmDeviceState state = DEVICE_STATE_OFFLINE; listener_->OnDeviceStateChange(pkgName, state, info); } + LOGI("DmDeviceStateManager::PostDeviceOffline out"); +} + +void DmDeviceStateManager::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &info) +{ + LOGI("OnDeviceOnline function is called back with pkgName: %s", pkgName.c_str()); + RegisterOffLineTimer(info); + RegisterProfileListener(pkgName, info); + + DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); + std::shared_ptr decisionAdapter = adapterMgrPtr.GetDecisionAdapter(decisionSoName_); + if (decisionAdapter == nullptr) { + LOGE("OnDeviceOnline decision adapter is null"); + PostDeviceOnline(pkgName, info); + } else if (decisionInfos_.size() == 0) { + PostDeviceOnline(pkgName, info); + } else { + std::string extra; + std::vector infoList; + LOGI("OnDeviceOnline decision decisionInfos_ size: %d", decisionInfos_.size()); + for (auto iter : decisionInfos_) { + std::string listenerPkgName = iter.first; + std::string extra = iter.second; + infoList.clear(); + infoList.push_back(info); + decisionAdapter->FilterDeviceList(infoList, extra); + if (infoList.size() == 1) { + PostDeviceOnline(listenerPkgName, info); + } + } + } + LOGI("DmDeviceStateManager::OnDeviceOnline out"); +} + +void DmDeviceStateManager::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &info) +{ + LOGI("OnDeviceOnline function is called with pkgName: %s", pkgName.c_str()); + StartOffLineTimer(info); + UnRegisterProfileListener(pkgName, info); + + DmAdapterManager &adapterMgrPtr = DmAdapterManager::GetInstance(); + std::shared_ptr decisionAdapter = adapterMgrPtr.GetDecisionAdapter(decisionSoName_); + if (decisionAdapter == nullptr) { + LOGE("OnDeviceOnline decision adapter is null"); + PostDeviceOffline(pkgName, info); + } else if (decisionInfos_.size() == 0) { + PostDeviceOffline(pkgName, info); + } else { + std::string extra; + std::vector infoList; + LOGI("OnDeviceOnline decision decisionInfos_ size: %d", decisionInfos_.size()); + for (auto iter : decisionInfos_) { + std::string listenerPkgName = iter.first; + std::string extra = iter.second; + infoList.clear(); + infoList.push_back(info); + decisionAdapter->FilterDeviceList(infoList, extra); + if (infoList.size() == 1) { + PostDeviceOffline(listenerPkgName, info); + } + } + } + LOGI("DmDeviceStateManager::OnDeviceOffline out"); } void DmDeviceStateManager::OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &info) @@ -144,6 +215,24 @@ int32_t DmDeviceStateManager::RegisterSoftbusStateCallback() return DM_OK; } +void DmDeviceStateManager::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra) +{ + LOGI("DmDeviceStateManager::RegisterDevStateCallback pkgName=%s, extra=%s", pkgName.c_str(), extra.c_str()); + if (pkgName != "") { + decisionInfos_[pkgName] = extra; + } +} + +void DmDeviceStateManager::UnRegisterDevStateCallback(const std::string &pkgName, const std::string &extra) +{ + LOGI("DmDeviceStateManager::UnRegisterDevStateCallback pkgName=%s, extra=%s", pkgName.c_str(), extra.c_str()); + auto iter = decisionInfos_.find(pkgName); + if (iter == decisionInfos_.end()) { + } else { + decisionInfos_.erase(pkgName); + } +} + void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) { std::string deviceId; @@ -155,6 +244,7 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) LOGI("Register OffLine Timer with device: %s", GetAnonyString(deviceId).c_str()); std::lock_guard mutexLock(timerMapMutex_); + deviceinfoMap_[deviceInfo.deviceId] = deviceId; auto iter = timerMap_.find(deviceId); if (iter != timerMap_.end()) { iter->second->Stop(SESSION_CANCEL_TIMEOUT); @@ -168,20 +258,19 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) { - std::string deviceId; - int32_t ret = softbusConnector_->GetUdidByNetworkId(deviceInfo.deviceId, deviceId); - if (ret != DM_OK) { + if (deviceinfoMap_.find(deviceInfo.deviceId) == deviceinfoMap_.end()) { LOGE("fail to get udid by networkId"); return; } - LOGI("start offline timer with device: %s", GetAnonyString(deviceId).c_str()); + LOGI("start offline timer with device: %s", GetAnonyString(deviceinfoMap_[deviceInfo.deviceId]).c_str()); std::lock_guard mutexLock(timerMapMutex_); for (auto &iter : timerMap_) { - if (iter.first == deviceId) { + if (iter.first == deviceinfoMap_[deviceInfo.deviceId]) { iter.second->Start(OFFLINE_TIMEOUT, TimeOut, this); } } + deviceinfoMap_.erase(deviceInfo.deviceId); } void DmDeviceStateManager::DeleteTimeOutGroup(std::string deviceId) @@ -192,4 +281,4 @@ void DmDeviceStateManager::DeleteTimeOutGroup(std::string deviceId) } } } // namespace DistributedHardware -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index a3a6663d186954b4302db5de3501ea2742139492..f4f0d6837a9f3784a93a4392537db9714e879555 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -73,14 +73,14 @@ int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, con int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { - if (discoveryQueue_.empty()) { - LOGE("discovery is not start"); - return DM_FAILED; + if (!discoveryQueue_.empty()) { + discoveryQueue_.pop(); + } + if (!discoveryContextMap_.empty()) { + discoveryContextMap_.erase(pkgName); + softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); + discoveryTimer_->Stop(SESSION_CANCEL_TIMEOUT); } - discoveryQueue_.pop(); - discoveryContextMap_.erase(pkgName); - softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); - discoveryTimer_->Stop(SESSION_CANCEL_TIMEOUT); return softbusConnector_->StopDiscovery(subscribeId); } diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index d5da15591b08205a2b46f362287a4f307190df71..42654f175cfe3560a2a5f6756767181bbebeecb5 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -394,7 +394,7 @@ ON_IPC_CMD(SERVER_GET_DMFA_INFO, MessageParcel &data, MessageParcel &reply) int32_t ret = DM_OK; ret = DeviceManagerService::GetInstance().GetFaParam(packName, authParam); int32_t appIconLen = authParam.imageinfo.GetAppIconLen(); - uint32_t appThumbnailLen = authParam.imageinfo.GetAppThumbnailLen(); + int32_t appThumbnailLen = authParam.imageinfo.GetAppThumbnailLen(); if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || !reply.WriteString(authParam.authToken) || !reply.WriteString(authParam.packageName) || @@ -431,5 +431,29 @@ ON_IPC_CMD(SERVER_USER_AUTH_OPERATION, MessageParcel &data, MessageParcel &reply } return result; } + +ON_IPC_CMD(REGISTER_DEV_STATE_CALLBACK, MessageParcel &data, MessageParcel &reply) +{ + std::string packageName = data.ReadString(); + std::string extra = data.ReadString(); + int result = DeviceManagerService::GetInstance().RegisterDevStateCallback(packageName, extra); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + return result; +} + +ON_IPC_CMD(UNREGISTER_DEV_STATE_CALLBACK, MessageParcel &data, MessageParcel &reply) +{ + std::string packageName = data.ReadString(); + std::string extra = data.ReadString(); + int result = DeviceManagerService::GetInstance().UnRegisterDevStateCallback(packageName, extra); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return DM_WRITE_FAILED; + } + return result; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp index a20ed41098730de36c3d605e8df187d564d1a33e..30f37fc6bf28db25333fcd537c218bbb4c3e1a9d 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp @@ -81,6 +81,12 @@ void IpcServerStub::OnStop() int32_t IpcServerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { LOGI("code = %d, flags= %d.", code, option.GetFlags()); + auto remoteDescriptor = data.ReadInterfaceToken(); + if (GetDescriptor() != remoteDescriptor) { + LOGI("ReadInterfaceToken fail!"); + return ERR_INVALID_STATE; + } + int32_t ret = DM_OK; ret = IpcCmdRegister::GetInstance().OnIpcCmd((int32_t)code, data, reply); if (ret == DM_IPC_NOT_REGISTER_FUNC) { @@ -127,12 +133,17 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr< LOGI("RegisterDeviceManagerListener: listener already exists"); return DM_OK; } - sptr appRecipient = sptr(new AppDeathRecipient()); - if (!listener->AddDeathRecipient(appRecipient)) { - LOGE("RegisterDeviceManagerListener: AddDeathRecipient Failed"); + try { + sptr appRecipient = sptr(new AppDeathRecipient()); + if (!listener->AddDeathRecipient(appRecipient)) { + LOGE("RegisterDeviceManagerListener: AddDeathRecipient Failed"); + } + dmListener_[pkgName] = listener; + appRecipient_[pkgName] = appRecipient; + } catch (const std::bad_alloc &e) { + LOGE("new AppDeathRecipient failed"); + return DM_MALLOC_ERROR; } - dmListener_[pkgName] = listener; - appRecipient_[pkgName] = appRecipient; return DM_OK; } diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 8e3dbd99a44ad7edcb27a92eb8dc1ffdf8791940..9325d03ef428e43f7cc3753ec610c25ac8d08270 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -28,7 +28,12 @@ group("unittest") { ":UTTest_dm_device_info_manager", ":UTTest_dm_device_state_manager", ":UTTest_dm_discovery_manager", - ":UTTest_hichain_connector", + ":UTTest_ipc_client_manager", + ":UTTest_ipc_client_proxy", + ":UTTest_ipc_client_stub", + ":UTTest_ipc_server_client_proxy", + ":UTTest_ipc_server_listener", + ":UTTest_ipc_server_stub", ":UTTest_softbus_connector", ":UTTest_softbus_session", ] @@ -100,6 +105,116 @@ ohos_unittest("UTTest_softbus_session") { ## UnitTest UTTest_softbus_session }}} +## UnitTest UTTest_ipc_client_manager {{{ +ohos_unittest("UTTest_ipc_client_manager") { + module_out_path = module_out_path + + sources = [ "UTTest_ipc_client_manager.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_ipc_client_manager }}} + +## UnitTest UTTest_ipc_client_proxy {{{ +ohos_unittest("UTTest_ipc_client_proxy") { + module_out_path = module_out_path + + sources = [ "UTTest_ipc_client_proxy.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_ipc_client_proxy }}} + +## UnitTest UTTest_ipc_client_stub {{{ +ohos_unittest("UTTest_ipc_client_stub") { + module_out_path = module_out_path + + sources = [ "UTTest_ipc_client_stub.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_ipc_client_stub }}} + +## UnitTest UTTest_ipc_server_client_proxy {{{ +ohos_unittest("UTTest_ipc_server_client_proxy") { + module_out_path = module_out_path + + sources = [ "UTTest_ipc_server_client_proxy.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_ipc_server_client_proxy }}} + +## UnitTest UTTest_ipc_server_listener {{{ +ohos_unittest("UTTest_ipc_server_listener") { + module_out_path = module_out_path + + sources = [ "UTTest_ipc_server_listener.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_ipc_server_listener }}} + +## UnitTest UTTest_ipc_server_stub {{{ +ohos_unittest("UTTest_ipc_server_stub") { + module_out_path = module_out_path + + sources = [ "UTTest_ipc_server_stub.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_ipc_server_stub }}} + +## UnitTest UTTest_device_manager_impl {{{ +ohos_unittest("UTTest_device_manager_impl") { + module_out_path = module_out_path + + sources = [ "UTTest_device_manager_impl.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_device_manager_impl }}} + +## UnitTest UTTest_profile_connector {{{ +ohos_unittest("UTTest_profile_connector") { + module_out_path = module_out_path + + sources = [ "UTTest_profile_connector.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_profile_connector }}} + +## UnitTest UTTest_device_manager_notify {{{ +ohos_unittest("UTTest_device_manager_notify") { + module_out_path = module_out_path + + sources = [ "UTTest_device_manager_notify.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_device_manager_notify }}} + +## UnitTest UTTest_ipc_client_server_proxy {{{ +ohos_unittest("UTTest_ipc_client_server_proxy") { + module_out_path = module_out_path + + sources = [ "UTTest_ipc_client_server_proxy.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_ipc_client_server_proxy }}} + ## UnitTest UTTest_dm_device_state_manager {{{ ohos_unittest("UTTest_dm_device_state_manager") { module_out_path = module_out_path @@ -173,6 +288,17 @@ ohos_unittest("UTTest_auth_request_state") { ## UTTest_auth_request_state }}} +## UnitTest ipc_client_manager_test {{{ +ohos_unittest("ipc_client_manager_test") { + module_out_path = module_out_path + + sources = [ "ipc_client_manager_test.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest ipc_client_manager_test }}} + ## UnitTest UTTest_dm_auth_manager {{{ ohos_unittest("UTTest_dm_auth_manager") { module_out_path = module_out_path @@ -202,6 +328,7 @@ ohos_unittest("UTTest_dm_discovery_manager") { } ## UnitTest UTTest_dm_discovery_manager }}} + ## Build device_manager_test_common.a {{{ config("device_manager_test_common_public_config") { include_dirs = [ @@ -237,6 +364,14 @@ config("device_manager_test_common_public_config") { "//foundation/communication/dsoftbus/interfaces/kits/discovery", "//foundation/communication/dsoftbus/interfaces/inner_kits/transport", "//foundation/distributedhardware/devicemanager/test/unittest/mock", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/distributedhardware/devicemanager/ext/mini/services/devicemanagerservice/include/dispatch", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", + "//foundation/distributedhardware/devicemanager/ext/profile/include", + "//foundation/deviceprofile/device_profile_core/interfaces/innerkits/core/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/distributedhardware/devicemanager/ext/mini/common/include", "//base/security/deviceauth/interfaces/innerkits", "${services_path}/include/ability", "${services_path}/include/config", @@ -318,6 +453,7 @@ config("device_manager_test_common_public") { "//base/account/os_account/interfaces/innerkits/osaccount/native/include", "//base/account/os_account/frameworks/common/database/include", "//base/account/os_account/frameworks/common/account_error/include", + "//foundation/distributedschedule/safwk/services/safwk", ] cflags = [ diff --git a/test/unittest/UTTest_auth_message_processor.cpp b/test/unittest/UTTest_auth_message_processor.cpp index c648ff9b52b6ae56a1021a068df91b8f230e7bc2..eaf46bd49c2ab888e1d19dedba5c3dbfce0c200c 100644 --- a/test/unittest/UTTest_auth_message_processor.cpp +++ b/test/unittest/UTTest_auth_message_processor.cpp @@ -124,14 +124,14 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext:: nlohmann::json jsonb; jsonb[TAG_GROUP_ID] = "123456"; authMessageProcessor->authResponseContext_->groupId = jsonb.dump(); - authMessageProcessor->authResponseContext_->code = 1; + authMessageProcessor->authResponseContext_->authToken = "123456"; authMessageProcessor->authResponseContext_->networkId = "11112222"; authMessageProcessor->authResponseContext_->requestId = 222222; authMessageProcessor->authResponseContext_->groupName = "333333"; jsona[TAG_TOKEN] = authMessageProcessor->authResponseContext_->token; jsona[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; jsona[TAG_DEVICE_ID] = authMessageProcessor->authResponseContext_->deviceId; - jsona[PIN_CODE_KEY] = authMessageProcessor->authResponseContext_->code; + jsona[TAG_AUTH_TOKEN] = authMessageProcessor->authResponseContext_->authToken; jsona[TAG_NET_ID] = authMessageProcessor->authResponseContext_->networkId; jsona[TAG_REQUEST_ID] = authMessageProcessor->authResponseContext_->requestId; jsona[TAG_GROUP_ID] = "123456"; @@ -203,7 +203,7 @@ HWTEST_F(AuthMessageProcessorTest, ParseAuthResponseMessage_001, testing::ext::T nlohmann::json jsona; authResponseContext->reply = 0; authResponseContext->deviceId = "11111"; - authResponseContext->code = 1; + authResponseContext->authToken = "123456"; authResponseContext->networkId = "12345"; authResponseContext->requestId = 2; authResponseContext->groupId = "23456"; @@ -212,7 +212,7 @@ HWTEST_F(AuthMessageProcessorTest, ParseAuthResponseMessage_001, testing::ext::T jsona[TAG_TOKEN] = authResponseContext->token; jsona[TAG_REPLY] = authResponseContext->reply; jsona[TAG_DEVICE_ID] = authResponseContext->deviceId; - jsona[PIN_CODE_KEY] = authResponseContext->code; + jsona[TAG_AUTH_TOKEN] = authResponseContext->authToken; jsona[TAG_NET_ID] = authResponseContext->networkId; jsona[TAG_REQUEST_ID] = authResponseContext->requestId; jsona[TAG_GROUP_ID] = authResponseContext->groupId; diff --git a/test/unittest/UTTest_auth_request_state.cpp b/test/unittest/UTTest_auth_request_state.cpp index bf554ee3bb9573fa3e7d313bf449dd452b5fcfec..310d859d3d9949c3fb7d1e301f8e6e4f4e5c7168 100644 --- a/test/unittest/UTTest_auth_request_state.cpp +++ b/test/unittest/UTTest_auth_request_state.cpp @@ -417,6 +417,7 @@ HWTEST_F(AuthRequestStateTest, Enter_010, testing::ext::TestSize.Level0) { std::shared_ptr authManager = std::make_shared(softbusConnector, listener, hiChainConnector); + authManager->authResponseContext_ = std::make_shared(); std::shared_ptr authRequestState = std::make_shared(); authRequestState->SetAuthManager(authManager); int32_t ret = authRequestState->Enter(); diff --git a/test/unittest/UTTest_auth_response_state.cpp b/test/unittest/UTTest_auth_response_state.cpp index 625f3444321fe67fa49be009083cbbbd3ac4c3c9..e3db904f1997047c54bf4b976d27f0ebc9391031 100644 --- a/test/unittest/UTTest_auth_response_state.cpp +++ b/test/unittest/UTTest_auth_response_state.cpp @@ -254,6 +254,7 @@ HWTEST_F(AuthResponseStateTest, Enter_005, testing::ext::TestSize.Level0) { std::shared_ptr authManager = std::make_shared(softbusConnector, listener, hiChainConnector); + authManager->authResponseContext_ = std::make_shared(); std::shared_ptr authResponseState = std::make_shared(); authResponseState->SetAuthManager(authManager); int32_t ret = authResponseState->Enter(); @@ -356,6 +357,7 @@ HWTEST_F(AuthResponseStateTest, Enter_009, testing::ext::TestSize.Level0) { std::shared_ptr authManager = std::make_shared(softbusConnector, listener, hiChainConnector); + authManager->authResponseContext_ = std::make_shared(); std::shared_ptr authResponseState = std::make_shared(); authResponseState->SetAuthManager(authManager); int32_t ret = authResponseState->Enter(); diff --git a/test/unittest/UTTest_auth_response_state.h b/test/unittest/UTTest_auth_response_state.h index ba8ff298765c53cc1ff91a9b927209d4a3b9bc3d..2b86d9d1bd3efc21fa42c325e189c202888ddb16 100644 --- a/test/unittest/UTTest_auth_response_state.h +++ b/test/unittest/UTTest_auth_response_state.h @@ -20,6 +20,8 @@ #include +#include "device_manager_impl.h" +#include "mock/mock_ipc_client_proxy.h" #include "auth_response_state.h" namespace OHOS { diff --git a/test/unittest/UTTest_dm_auth_manager.cpp b/test/unittest/UTTest_dm_auth_manager.cpp index 65f84540613f1712c490f59505b839ff7bdde2da..70f3bf7e2f9aeed6f20994feecbdbddb342bc7e6 100644 --- a/test/unittest/UTTest_dm_auth_manager.cpp +++ b/test/unittest/UTTest_dm_auth_manager.cpp @@ -217,8 +217,7 @@ HWTEST_F(DmAuthManagerTest, AddMember_001, testing::ext::TestSize.Level0) authManager->hiChainConnector_->RegisterHiChainCallback(authManager); authManager->SetAuthResponseState(authResponseState); int32_t ret = authManager->AddMember(deviceId); - ASSERT_EQ(ret, DM_OK); - sleep(15); + ASSERT_EQ(ret, DM_FAILED); } /** @@ -272,7 +271,7 @@ HWTEST_F(DmAuthManagerTest, GetPinCode_001, testing::ext::TestSize.Level0) std::make_shared(softbusConnector, listener, hiChainConnector_); authManager->authResponseContext_ = std::make_shared(); int32_t ret = authManager->GetPinCode(); - ASSERT_EQ(ret, authManager->authResponseContext_->code); + ASSERT_EQ(ret, DM_FAILED); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_dm_device_state_manager.cpp b/test/unittest/UTTest_dm_device_state_manager.cpp index 52e341847fe8cedbc26af61351bed556ef20af75..af0a2addaf096b8bf9b6444cee400e0810685ef2 100644 --- a/test/unittest/UTTest_dm_device_state_manager.cpp +++ b/test/unittest/UTTest_dm_device_state_manager.cpp @@ -44,7 +44,7 @@ void DmDeviceStateManagerTest::TearDownTestCase() { } namespace { - std::shared_ptr hiChainConnector_ = std::make_shared(); +std::shared_ptr hiChainConnector_ = std::make_shared(); std::shared_ptr softbusConnector = std::make_shared(); std::shared_ptr listener_ = std::make_shared(); std::shared_ptr dmDeviceStateManager = @@ -151,7 +151,7 @@ HWTEST_F(DmDeviceStateManagerTest, OnProfileReady_001, testing::ext::TestSize.Le std::static_pointer_cast(listener_->ipcServerListener_.req_); DmDeviceInfo ret = pReq->GetDeviceInfo(); int result = strcmp(info.deviceId, ret.deviceId); - ASSERT_NE(result, 0); + EXPECT_EQ(result, 0); } /** @@ -170,7 +170,7 @@ HWTEST_F(DmDeviceStateManagerTest, OnDeviceReady_001, testing::ext::TestSize.Lev std::static_pointer_cast(listener_->ipcServerListener_.req_); DmDeviceInfo ret = pReq->GetDeviceInfo(); int result = strcmp(info.deviceId, ret.deviceId); - ASSERT_NE(result, 0); + EXPECT_EQ(result, 0); } /** @@ -189,7 +189,7 @@ HWTEST_F(DmDeviceStateManagerTest, OnDeviceChanged_002, testing::ext::TestSize.L std::static_pointer_cast(listener_->ipcServerListener_.req_); DmDeviceInfo ret = pReq->GetDeviceInfo(); int result = strcmp(info.deviceId, ret.deviceId); - ASSERT_NE(result, 0); + EXPECT_EQ(result, 0); } /** diff --git a/test/unittest/UTTest_dm_discovery_manager.cpp b/test/unittest/UTTest_dm_discovery_manager.cpp index 088a392d8f2c0c9e7c3e119cb36a7a2815765165..03fff20ce718c6046f9610262fad6b5fa17f0f8a 100644 --- a/test/unittest/UTTest_dm_discovery_manager.cpp +++ b/test/unittest/UTTest_dm_discovery_manager.cpp @@ -236,7 +236,7 @@ HWTEST_F(DmDiscoveryManagerTest, OnDiscoverySuccess_002, testing::ext::TestSize. std::string pkgName; int32_t subscribeId = 1; discoveryMgr_->OnDiscoverySuccess(pkgName, subscribeId); - uint32_t ret1 = discoveryMgr_->discoveryContextMap_.count(pkgName); + int ret1 = discoveryMgr_->discoveryContextMap_.count(pkgName); EXPECT_EQ(ret1, 1); std::shared_ptr pReq = std::static_pointer_cast(listener_->ipcServerListener_.req_); @@ -254,7 +254,7 @@ HWTEST_F(DmDiscoveryManagerTest, HandleDiscoveryTimeout_001, testing::ext::TestS { std::string pkgName = "com.ohos.helloworld"; discoveryMgr_->HandleDiscoveryTimeout(); - uint32_t ret = discoveryMgr_->discoveryContextMap_.count(pkgName); + int ret = discoveryMgr_->discoveryContextMap_.count(pkgName); EXPECT_EQ(ret, 1); } } // namespace diff --git a/test/unittest/UTTest_hichain_connector.cpp b/test/unittest/UTTest_hichain_connector.cpp deleted file mode 100644 index ae46c25140fbd41a4557155c629a59945cbf5046..0000000000000000000000000000000000000000 --- a/test/unittest/UTTest_hichain_connector.cpp +++ /dev/null @@ -1,479 +0,0 @@ -/* - * Copyright (c) 2021 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 -#include -#include -#include - -#include "parameter.h" -#include "dm_anonymous.h" -#include "dm_log.h" -#include "dm_constants.h" -#include "dm_random.h" -#include "hichain_connector.h" -#include "UTTest_hichain_connector.h" - -namespace OHOS { -namespace DistributedHardware { -void HichainConnectorTest::SetUp() -{ -} -void HichainConnectorTest::TearDown() -{ -} -void HichainConnectorTest::SetUpTestCase() -{ -} -void HichainConnectorTest::TearDownTestCase() -{ -} -namespace { -std::shared_ptr listener_ = std::make_shared(); -std::shared_ptr softbusConnector = std::make_shared(); -std::shared_ptr hiChainConnector_ = std::make_shared(); -std::shared_ptr discoveryMgr_ = - std::make_shared(softbusConnector, listener_, hiChainConnector_); - -/** - * @tc.name: CreateGroup_001 - * @tc.desc: Set the deviceGroupManager_ pointer to CreateGroup to NULlptr and return DM_INVALID_VALUE - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, CreateGroup_001, testing::ext::TestSize.Level0) -{ - int64_t requestId = 123456; - std::string groupName = "dfggg"; - std::shared_ptr hichainConnector = std::make_shared(); - hichainConnector->deviceGroupManager_ = nullptr; - int ret = hichainConnector->CreateGroup(requestId, groupName); - EXPECT_EQ(ret, DM_INVALID_VALUE); -} - -/** - * @tc.name: CreateGroup_002 - * @tc.desc: Set CreateGroup to the correct process and return DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, CreateGroup_002, testing::ext::TestSize.Level0) -{ - int64_t requestId = 123456; - std::string groupName = "uuiioo"; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->CreateGroup(requestId, groupName); - EXPECT_EQ(ret, DM_OK); -} - -/** - * @tc.name: GetGroupInfo_001 - * @tc.desc: set groupName not null and return false - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, GetGroupInfo_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr hichainConnector = std::make_shared(); - std::string groupName = "dcdkdkd1"; - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); - std::string queryParams = jsonObj.dump(); - std::vector groupList; - int ret = hichainConnector->GetGroupInfo(queryParams, groupList); - EXPECT_EQ(ret, 0); -} - -/** - * @tc.name: GetGroupInfo_003 - * @tc.desc: set groupName nou null groupListot null and return 0 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, GetGroupInfo_003, testing::ext::TestSize.Level0) -{ - std::string groupName = "lcdkddkd1 "; - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); - std::string queryParams = jsonObj.dump(); - GroupInfo aa; - aa.groupName = "afa"; - std::vector groupList; - groupList.push_back(aa); - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->GetGroupInfo(queryParams, groupList); - EXPECT_EQ(ret, 0); -} - -/** - * @tc.name: IsGroupInfoInvalid_001 - * @tc.desc: GroupType is GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP, group.groupVisibility is not GROUP_VISIBILITY_PUBLIC. - Group.return true - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ - -HWTEST_F(HichainConnectorTest, IsGroupInfoInvalid_001, testing::ext::TestSize.Level0) -{ - GroupInfo group; - group.groupName = "dkdkkdkdk"; - group.groupId = 1; - group.groupOwner = "ohos.distributedhardware.devicemanager"; - group.groupType = 7; - group.groupVisibility = 1; - std::shared_ptr hichainConnector = std::make_shared(); - bool ret = hichainConnector->IsGroupInfoInvalid(group); - EXPECT_EQ(ret, false); -} - -/** - * @tc.name: IsGroupInfoInvalid_002 - * @tc.desc: GroupType is GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP, group.groupVisibility is GROUP_VISIBILITY_PUBLIC, - Grou. groupOwner is not equal to DM_PKG_NAME. The value is true - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, IsGroupInfoInvalid_002, testing::ext::TestSize.Level0) -{ - GroupInfo group; - group.groupName = "test"; - group.groupId = 1; - group.groupOwner = "ohos.disware"; - group.groupType = 1; - group.groupVisibility = -1; - std::shared_ptr hichainConnector = std::make_shared(); - bool ret = hichainConnector->IsGroupInfoInvalid(group); - EXPECT_EQ(ret, true); -} - -/** - * @tc.name: DelMemberFromGroup_001 - * @tc.desc:set groupId, deviceId null and return DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, DelMemberFromGroup_001, testing::ext::TestSize.Level0) -{ - std::string groupId; - std::string deviceId; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->DelMemberFromGroup(groupId, deviceId); - EXPECT_EQ(ret, DM_OK); -} - -/** - * @tc.name: DelMemberFromGroup_002 - * @tc.desc: The groupId "34451"; The deviceId = "123"; Can be deleted correctly - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, DelMemberFromGroup_002, testing::ext::TestSize.Level0) -{ - std::string groupId = "34451"; - std::string deviceId = "123"; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->DelMemberFromGroup(groupId, deviceId); - EXPECT_EQ(ret, DM_OK); -} - -/** - * @tc.name: GenRequestId_001 - * @tc.desc:Call the GenRequestId function - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, GenRequestId_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->GenRequestId(); - ASSERT_NE(ret, 0); -} - -/** - * @tc.name: from_json_001 - * @tc.desc: Pass in arguments to the from_JSON function and convert it to the correct value - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, from_json_001, testing::ext::TestSize.Level0) -{ - GroupInfo groupInfo; - groupInfo.groupName = "aaaa"; - groupInfo.groupId = "345678"; - groupInfo.groupOwner = "lllll"; - groupInfo.groupType = 5; - groupInfo.groupVisibility = 5; - nlohmann::json jsonObject; - jsonObject[FIELD_GROUP_NAME] = groupInfo.groupName; - jsonObject[FIELD_GROUP_ID] = groupInfo.groupId; - jsonObject[FIELD_GROUP_OWNER] = groupInfo.groupOwner; - jsonObject[FIELD_GROUP_TYPE] = groupInfo.groupType; - jsonObject[FIELD_GROUP_VISIBILITY] = groupInfo.groupVisibility; - from_json(jsonObject, groupInfo); - EXPECT_EQ(groupInfo.groupName, "aaaa"); - EXPECT_EQ(groupInfo.groupId, "345678"); - EXPECT_EQ(groupInfo.groupOwner, "lllll"); - EXPECT_EQ(groupInfo.groupType, 5); - EXPECT_EQ(groupInfo.groupVisibility, 5); -} - -/** - * @tc.name: HiChainConnector_001 - * @tc.desc: Returns a new pointer to the HiChainConnector constructor new - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, HiChainConnector_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr m_HiChainConnector = std::make_shared(); - ASSERT_NE(m_HiChainConnector, nullptr); -} - -/** - * @tc.name: HiChainConnector_002 - * @tc.desc: Give the HiChainConnector constructor new a new pointer and delete it - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, HiChainConnector_002, testing::ext::TestSize.Level0) -{ - std::shared_ptr m_HiChainConnector = std::make_shared(); - m_HiChainConnector.reset(); - EXPECT_EQ(m_HiChainConnector, nullptr); -} - -/** - * @tc.name:RegisterHiChainCallback_001 - * @tc.desc: Call the RegisterHiChainCallback function with a return value of DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, RegisterHiChainCallback_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->RegisterHiChainCallback(std::shared_ptr(discoveryMgr_)); - EXPECT_EQ(ret, DM_OK); -} - -/** - * @tc.name: IsGroupCreated_001 - * @tc.desc: Call the RegisterHiChainCallback function with a return value of DM_OK - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, IsGroupCreated_001, testing::ext::TestSize.Level0) -{ - std::string groupName = "dcdkdkd1"; - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); - std::string queryParams = jsonObj.dump(); - std::vector groupList; - GroupInfo groupInfo; - std::shared_ptr hichainConnector = std::make_shared(); - bool ret = hichainConnector->IsGroupCreated(groupName, groupInfo); - EXPECT_EQ(ret, false); -} - -/** - * @tc.name: AddMember_001 - * @tc.desc: set deviceGroupManager_ = nullptr; - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, AddMember_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr hichainConnector = std::make_shared(); - hichainConnector->deviceGroupManager_ = nullptr; - std::string deviceId; - std::string connectInfo; - int ret = hichainConnector->AddMember(deviceId, connectInfo); - EXPECT_EQ(ret, -1); -} - -/** - * @tc.name: AddMember_002 - * @tc.desc: set deviceId and connectInfo = null; - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, AddMember_002, testing::ext::TestSize.Level0) -{ - std::string deviceId; - std::string connectInfo; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->AddMember(deviceId, connectInfo); - EXPECT_EQ(ret, DM_FAILED); -} - -/** - * @tc.name: AddMember_002 - * @tc.desc: set deviceId and connectInfo = null; - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, AddMember3, testing::ext::TestSize.Level0) -{ - std::string deviceId = "123456"; - std::string connectInfo = "dkdkk"; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->AddMember(deviceId, connectInfo); - ASSERT_GE(ret, 1); -} - -/** - * @tc.name: onRequest_001 - * @tc.desc:set operationCode != GroupOperationCode::MEMBER_JOIN(3); return nullptr ; - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, onRequest_001, testing::ext::TestSize.Level0) -{ - int64_t requestId = 2; - int32_t operationCode = 2; - char *reqParams; - std::shared_ptr hichainConnector = std::make_shared(); - char *ret = hichainConnector->onRequest(requestId, operationCode, reqParams); - EXPECT_EQ(ret, nullptr); -} - -/** - * @tc.name: GetConnectPara_001 - * @tc.desc: set para not null and go to the second master - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, GetConnectPara_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr hichainConnector = std::make_shared(); - hichainConnector->RegisterHiChainCallback(std::shared_ptr(discoveryMgr_)); - std::string deviceId = "23445"; - std::string reqDeviceId = "234566"; - std::string p; - std::string ret = hichainConnector->GetConnectPara(deviceId, reqDeviceId); - EXPECT_EQ(ret, p); -} - -/** - * @tc.name: GetConnectPara_002 - * @tc.desc:Empty deviceId so that jsonObject.is_discarded is null and the value of connectAddr is returned - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, GetConnectPara_002, testing::ext::TestSize.Level0) -{ - std::string deviceId; - std::string reqDeviceId = "234566"; - std::shared_ptr hichainConnector = std::make_shared(); - hichainConnector->RegisterHiChainCallback(std::shared_ptr(discoveryMgr_)); - std::string ret = hichainConnector->GetConnectPara(deviceId, reqDeviceId); - EXPECT_EQ(ret, ""); -} - -/** - * @tc.name: DeleteGroup_001 - * @tc.desc: set groupId = "34567",and return DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, DeleteGroup_001, testing::ext::TestSize.Level0) -{ - std::string groupId = "34567"; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->DeleteGroup(groupId); - EXPECT_EQ(ret, DM_OK); -} - -/** - * @tc.name: GetRelatedGroups_001 - * @tc.desc: set DeviceId 123 groupList null and return DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, GetRelatedGroups_001, testing::ext::TestSize.Level0) -{ - std::string DeviceId = "123"; - std::vector groupList; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->GetRelatedGroups(DeviceId, groupList); - EXPECT_EQ(ret, DM_FAILED); -} - -/** - * @tc.name: GetRelatedGroups_002 - * @tc.desc: set DeviceId = 12345,groupList null and return DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, GetRelatedGroups_002, testing::ext::TestSize.Level0) -{ - std::string DeviceId = "12345"; - std::vector groupList; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->GetRelatedGroups(DeviceId, groupList); - EXPECT_EQ(ret, DM_FAILED); -} - -/** - * @tc.name: SyncGroups_001 - * @tc.desc: set deviceId = "34567",and return DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, SyncGroups_001, testing::ext::TestSize.Level0) -{ - std::string deviceId = "34567"; - std::vector remoteGroupIdList; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->SyncGroups(deviceId, remoteGroupIdList); - EXPECT_EQ(ret, DM_OK); -} - -/** - * @tc.name: GetSyncGroupList_001 - * @tc.desc: set groupList null,and return DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, GetSyncGroupList_001, testing::ext::TestSize.Level0) -{ - std::vector groupList; - std::vector syncGroupList; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->GetSyncGroupList(groupList, syncGroupList); - EXPECT_EQ(ret, DM_FAILED); -} - -/** - * @tc.name: GetSyncGroupList_002 - * @tc.desc: set groupList not null,and return DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, GetSyncGroupList_002, testing::ext::TestSize.Level0) -{ - std::vector groupList; - GroupInfo groupList1; - groupList1.groupName = "hichainconnector"; - groupList1.groupId = "123456"; - groupList1.groupOwner = "doftbus"; - groupList1.groupType = 1; - groupList1.groupVisibility = 2; - groupList.push_back(groupList1); - std::vector syncGroupList; - std::shared_ptr hichainConnector = std::make_shared(); - int ret = hichainConnector->GetSyncGroupList(groupList, syncGroupList); - EXPECT_EQ(ret, DM_OK); -} -} // namespace -} // namespace DistributedHardware -} // namespace OHOS diff --git a/test/unittest/UTTest_ipc_client_manager.cpp b/test/unittest/UTTest_ipc_client_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c31bae3431bad61456ce272bb77e61a6507802fe --- /dev/null +++ b/test/unittest/UTTest_ipc_client_manager.cpp @@ -0,0 +1,583 @@ +/* + * Copyright (c) 2021 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 "UTTest_ipc_client_manager.h" +#include "device_manager_notify.h" +#include "dm_device_info.h" +#include "ipc_client_stub.h" +#include "ipc_register_listener_req.h" +#include "ipc_remote_broker.h" +#include "iremote_object.h" +#include "iservice_registry.h" +#include "dm_constants.h" +#include "system_ability_definition.h" + +#include + +namespace OHOS { +namespace DistributedHardware { +void IpcClientManagerTest::SetUp() +{ +} + +void IpcClientManagerTest::TearDown() +{ +} + +void IpcClientManagerTest::SetUpTestCase() +{ +} + +void IpcClientManagerTest::TearDownTestCase() +{ +} + +namespace { +/** + * @tc.name: ClientInit_001 + * @tc.desc: 1. new a dmInterface + * 2. set IpcClientManager dmInterface_ not null + * 3. call ClientInit + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, ClientInit_001, testing::ext::TestSize.Level0) +{ + // 1. new a dmInterface + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + auto object = samgr->CheckSystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); + sptr dmInterface = iface_cast(object); + // 2. set IpcClientManager dmInterface_ not null + std::shared_ptr instance = std::make_shared(); + instance->dmInterface_ = dmInterface; + // 3. call ClientInit + int ret = instance->ClientInit(); + // 4. check ret is DM_SERVICE_NOT_READY + ASSERT_EQ(ret, DM_SERVICE_NOT_READY); +} + +/** + * @tc.name: ClientInit_002 + * @tc.desc: 1. new a dmInterface + * 2. set IpcClientManager dmInterface_ not null + * 3. call ClientInit + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, ClientInit_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr instance = std::make_shared(); + // 3. call ClientInit + int ret = instance->ClientInit(); + // 4. check ret is DM_SERVICE_NOT_READY + ASSERT_EQ(ret, DM_SERVICE_NOT_READY); +} + +/** + * @tc.name: Init_001 + * @tc.desc: 1. new a listener + * 2. set a pkgName not null + * 3. add listener and pkgName in dmListener_ Map + * 4. call Init with pkgName + * 5. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, Init_001, testing::ext::TestSize.Level0) +{ + // 1. new a listener + sptr listener = sptr(new IpcClientStub()); + // 2. set a pkgName not null + std::string pkgName = "com.ohos.test"; + std::shared_ptr instance = std::make_shared(); + // 3. add listener and pkgName in dmListener_ Map + instance->dmListener_[pkgName] = listener; + // 4. call Init with pkgName + int32_t ret = instance->Init(pkgName); + // 5. check ret is DM_SERVICE_NOT_READY + ASSERT_EQ(ret, DM_SERVICE_NOT_READY); +} + +/** + * @tc.name: Init_002 + * @tc.desc: 1. set pkcName not null + * 2. Mock IpcClientServerProxy SendCmd return DM_FAILED + * 3. call Init with pkgName + * 4. check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, Init_002, testing::ext::TestSize.Level0) +{ + // 1. set pkcName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClientServerProxy SendCmd return DM_FAILED + sptr remoteObject = nullptr; + auto mockInstance = new MockIpcClientManager(remoteObject); + std::shared_ptr instance = std::make_shared(); + instance->dmInterface_ = mockInstance; + EXPECT_CALL(*mockInstance, SendCmd(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_FAILED)); + // 3. call Init with pkgName + int32_t ret = instance->Init(pkgName); + // 4. check ret is DM_FAILED + ASSERT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: Init_003 + * @tc.desc: 1. set pkcName not null + * 2. Mock IpcClientServerProxy SendCmd return DM_OK + * 3. call Init with pkgName + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, Init_003, testing::ext::TestSize.Level0) +{ + // 1. set pkcName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClientServerProxy SendCmd return DM_OK + sptr remoteObject = nullptr; + auto mockInstance = new MockIpcClientManager(remoteObject); + std::shared_ptr instance = std::make_shared(); + instance->dmInterface_ = mockInstance; + EXPECT_CALL(*mockInstance, SendCmd(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_OK)); + // 3. call Init with pkgName + int32_t ret = instance->Init(pkgName); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: Init_004 + * @tc.desc: 1. set pkcName not null + * 2. Mock IpcClientServerProxy SendCmd return DM_OK + * 3. call Init with pkgName + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, Init_004, testing::ext::TestSize.Level0) +{ + // 1. set pkcName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClientServerProxy SendCmd return DEVICEMANAGER_SERVICE_NOT_READY + sptr remoteObject = nullptr; + auto mockInstance = new MockIpcClientManager(remoteObject); + std::shared_ptr instance = std::make_shared(); + instance->dmInterface_ = mockInstance; + EXPECT_CALL(*mockInstance, SendCmd(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_SERVICE_NOT_READY)); + // 3. call Init with pkgName + int32_t ret = instance->Init(pkgName); + // 4. check ret is DEVICEMANAGER_OK + ASSERT_EQ(ret, ret); +} + +/** + * @tc.name: Init_005 + * @tc.desc: 1. set pkcName not null + * 2. Mock IpcClientServerProxy SendCmd return DM_IPC_FAILED + * 3. call Init with pkgName + * 4. check ret is DM_IPC_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, Init_005, testing::ext::TestSize.Level0) +{ + // 1. set pkcName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClientServerProxy SendCmd return DM_OK + sptr remoteObject = nullptr; + auto mockInstance = new MockIpcClientManager(remoteObject); + std::shared_ptr instance = std::make_shared(); + instance->dmInterface_ = mockInstance; + EXPECT_CALL(*mockInstance, SendCmd(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_IPC_FAILED)); + // 3. call Init with pkgName + int32_t ret = instance->Init(pkgName); + // 4. check ret is DM_IPC_FAILED + ASSERT_EQ(ret, DM_IPC_FAILED); +} + +/** + * @tc.name: UnInit_001 + * @tc.desc: 1. set pkgName null + * set IpcClientManager dmInterface_ null + * 2. call UnInit with pkgName + * 3. check ret is DEVICEMANAGER_SERVICE_NOT_READY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, UnInit1, testing::ext::TestSize.Level0) +{ + // 1. set pkgName null + std::string pkgName = ""; + // set IpcClientManager dmInterface_ null + std::shared_ptr instance = std::make_shared(); + instance->dmInterface_ = nullptr; + // 2. call UnInit with pkgName + int32_t ret = instance->UnInit(pkgName); + // 3. check ret is DM_SERVICE_NOT_READY + ASSERT_EQ(ret, DM_SERVICE_NOT_READY); +} + +/** + * @tc.name: UnInit_002 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClientServerProxy SendCmd return DM_FAILED + * 3. set IpcClientManager dmInterface_ not null + * 4. set IpcClientManager dmListener_ not null + * 5. call UnInit with pkgName + * 6. check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, UnInit_002, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClientServerProxy SendCmd return DM_FAILED + sptr remoteObject = nullptr; + auto mockInstance = new MockIpcClientManager(remoteObject); + EXPECT_CALL(*mockInstance, SendCmd(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_FAILED)); + // 3. set IpcClientManager dmInterface_ not null + std::shared_ptr instance = std::make_shared(); + instance->dmInterface_ = mockInstance; + // 4. set IpcClientManager dmListener_ not null + sptr listener = sptr(new IpcClientStub()); + instance->dmListener_[pkgName] = listener; + // 5. call UnInit with pkgName + int32_t ret = instance->UnInit(pkgName); + // 6. check ret is DM_FAILED + ASSERT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: UnInit_003 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClientServerProxy SendCmd return DM_OK + * 3. set IpcClientManager dmInterface_ not null + * 4. set IpcClientManager dmListener_ not null + * 5. call UnInit with pkgName + * 6. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, UnInit_003, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClientServerProxy SendCmd return DM_OK + sptr remoteObject = nullptr; + auto mockInstance = new MockIpcClientManager(remoteObject); + EXPECT_CALL(*mockInstance, SendCmd(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_OK)); + // 3. set IpcClientManager dmInterface_ not null + std::shared_ptr instance = std::make_shared(); + instance->dmInterface_ = mockInstance; + // 4. set IpcClientManager dmListener_ not null + sptr listener = sptr(new IpcClientStub()); + instance->dmListener_[pkgName] = listener; + // 5. call UnInit with pkgName + int32_t ret = instance->UnInit(pkgName); + // 6. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: UnInit_004 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClientServerProxy SendCmd return DM_SERVICE_NOT_READY + * 3. set IpcClientManager dmInterface_ not null + * 4. set IpcClientManager dmListener_ not null + * 5. call UnInit with pkgName + * 6. check ret is DM_SERVICE_NOT_READY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, UnInit_004, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClientServerProxy SendCmd return DM_SERVICE_NOT_READY + sptr remoteObject = nullptr; + auto mockInstance = new MockIpcClientManager(remoteObject); + EXPECT_CALL(*mockInstance, SendCmd(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_SERVICE_NOT_READY)); + // 3. set IpcClientManager dmInterface_ not null + std::shared_ptr instance = std::make_shared(); + instance->dmInterface_ = mockInstance; + // 4. set IpcClientManager dmListener_ not null + sptr listener = sptr(new IpcClientStub()); + instance->dmListener_[pkgName] = listener; + // 5. call UnInit with pkgName + int32_t ret = instance->UnInit(pkgName); + // 6. check ret is DM_SERVICE_NOT_READY + ASSERT_EQ(ret, DM_SERVICE_NOT_READY); +} + +/** + * @tc.name: UnInit_005 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClientServerProxy SendCmd return DM_IPC_FAILED + * 3. set IpcClientManager dmInterface_ not null + * 4. set IpcClientManager dmListener_ not null + * 5. call UnInit with pkgName + * 6. check ret is DM_IPC_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, UnInit_005, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClientServerProxy SendCmd return DM_IPC_FAILED + sptr remoteObject = nullptr; + auto mockInstance = new MockIpcClientManager(remoteObject); + EXPECT_CALL(*mockInstance, SendCmd(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_IPC_FAILED)); + // 3. set IpcClientManager dmInterface_ not null + std::shared_ptr instance = std::make_shared(); + instance->dmInterface_ = mockInstance; + // 4. set IpcClientManager dmListener_ not null + sptr listener = sptr(new IpcClientStub()); + instance->dmListener_[pkgName] = listener; + // 5. call UnInit with pkgName + int32_t ret = instance->UnInit(pkgName); + // 6. check ret is DM_IPC_FAILED + ASSERT_EQ(ret, DM_IPC_FAILED); +} + +/** + * @tc.name: SendRequest_001 + * @tc.desc: 1. set pkgName null + * 2. set IpcClientManager dmInterface_null + * 3. call SendRequest with parameter + * 4. check ret is DM_SERVICE_NOT_READY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, SendRequest_001, testing::ext::TestSize.Level0) +{ + // 1. set pkgName null + std::string pkgName = ""; + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 2. set IpcClientManager dmInterface_null + std::shared_ptr instance = std::make_shared(); + instance->dmInterface_ = nullptr; + // 3. call SendRequest with parameter + int ret = instance->SendRequest(0, req, rsp); + // 4. check ret is DM_SERVICE_NOT_READY + ASSERT_EQ(ret, DM_SERVICE_NOT_READY); +} + +/** + * @tc.name: SendRequest_002 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClientServerProxy SendCmd return DM_FAILED + * 3. set IpcClientManager dmInterface_ not null + * 4. set IpcClientManager dmListener_ not null + * 5. call SendRequest with parameter + * 6. check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, SendRequest_002, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 2. Mock IpcClientServerProxy SendCmd return DM_FAILED + sptr remoteObject = nullptr; + auto mockInstance = new MockIpcClientManager(remoteObject); + EXPECT_CALL(*mockInstance, SendCmd(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_FAILED)); + std::shared_ptr instance = std::make_shared(); + // 3. set IpcClientManager dmInterface_ not null + instance->dmInterface_ = mockInstance; + sptr listener = sptr(new IpcClientStub()); + // 4. set IpcClientManager dmListener_ not null + instance->dmListener_[pkgName] = listener; + // 5. call SendRequest with parameter + int ret = instance->SendRequest(0, req, rsp); + // 6. check ret is DM_FAILED + ASSERT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: SendRequest_003 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClientServerProxy SendCmd return DM_OK + * 3. set IpcClientManager dmInterface_ not null + * 4. set IpcClientManager dmListener_ not null + * 5. call SendRequest with parameter + * 6. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, SendRequest_003, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 2. Mock IpcClientServerProxy SendCmd return DM_OK + sptr remoteObject = nullptr; + auto mockInstance = new MockIpcClientManager(remoteObject); + EXPECT_CALL(*mockInstance, SendCmd(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_OK)); + std::shared_ptr instance = std::make_shared(); + // 3. set IpcClientManager dmInterface_ not null + instance->dmInterface_ = mockInstance; + sptr listener = sptr(new IpcClientStub()); + // 4. set IpcClientManager dmListener_ not null + instance->dmListener_[pkgName] = listener; + // 5. call SendRequest with parameter + int ret = instance->SendRequest(0, req, rsp); + // 6. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SendRequest_004 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClientServerProxy SendCmd return DM_SERVICE_NOT_READY + * 3. set IpcClientManager dmInterface_ not null + * 4. set IpcClientManager dmListener_ not null + * 5. call SendRequest with parameter + * 6. check ret is DM_SERVICE_NOT_READY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, SendRequest_004, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 2. Mock IpcClientServerProxy SendCmd return DM_SERVICE_NOT_READY + sptr remoteObject = nullptr; + auto mockInstance = new MockIpcClientManager(remoteObject); + EXPECT_CALL(*mockInstance, SendCmd(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_SERVICE_NOT_READY)); + std::shared_ptr instance = std::make_shared(); + // 3. set IpcClientManager dmInterface_ not null + instance->dmInterface_ = mockInstance; + sptr listener = sptr(new IpcClientStub()); + // 4. set IpcClientManager dmListener_ not null + instance->dmListener_[pkgName] = listener; + // 5. call SendRequest with parameter + int ret = instance->SendRequest(0, req, rsp); + // 6. check ret is DM_SERVICE_NOT_READY + ASSERT_EQ(ret, DM_SERVICE_NOT_READY); +} + +/** + * @tc.name: SendRequest_005 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClientServerProxy SendCmd return DM_IPC_FAILED + * 3. set IpcClientManager dmInterface_ not null + * 4. set IpcClientManager dmListener_ not null + * 5. call SendRequest with parameter + * 6. check ret is DM_IPC_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, SendRequest_005, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 2. Mock IpcClientServerProxy SendCmd return DM_IPC_FAILED + sptr remoteObject = nullptr; + auto mockInstance = new MockIpcClientManager(remoteObject); + EXPECT_CALL(*mockInstance, SendCmd(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_IPC_FAILED)); + std::shared_ptr instance = std::make_shared(); + // 3. set IpcClientManager dmInterface_ not null + instance->dmInterface_ = mockInstance; + sptr listener = sptr(new IpcClientStub()); + // 4. set IpcClientManager dmListener_ not null + instance->dmListener_[pkgName] = listener; + // 5. call SendRequest with parameter + int ret = instance->SendRequest(0, req, rsp); + // 6. check ret is DM_IPC_FAILED + ASSERT_EQ(ret, DM_IPC_FAILED); +} + +/** + * @tc.name: IsInit_001 + * @tc.desc: 1. set pkgName null + * 2. set IpcClientManager dmInterface_null + * 3. call IsInit with parameter + * 4. check ret is false + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, IsInit_001, testing::ext::TestSize.Level0) +{ + // 1. set pkgName null + std::string pkgName = ""; + // 2. set IpcClientManager dmInterface_null + std::shared_ptr instance = std::make_shared(); + instance->dmInterface_ = nullptr; + // 3. call SendRequest with parameter + bool ret = instance->IsInit(pkgName); + // 4. check ret is false + ASSERT_EQ(ret, false); +} + +/** + * @tc.name: IsInit_002 + * @tc.desc: 1. set pkgName not null + * 2. set IpcClientManager dmInterface_ not null + * 3. call IsInit with parameter + * 4. check ret is false + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientManagerTest, IsInit_002, testing::ext::TestSize.Level0) +{ + // 1. set pkgName null + std::string pkgName = ""; + // 2. set IpcClientManager dmInterface_ not null + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + auto object = samgr->CheckSystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); + sptr dmInterface = iface_cast(object); + std::shared_ptr instance = std::make_shared(); + instance->dmInterface_ = dmInterface; + // 3. call IsInit with parameter + bool ret = instance->IsInit(pkgName); + // 4. check ret is false + ASSERT_EQ(ret, false); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_hichain_connector.h b/test/unittest/UTTest_ipc_client_manager.h similarity index 60% rename from test/unittest/UTTest_hichain_connector.h rename to test/unittest/UTTest_ipc_client_manager.h index 9e706061524563f56c85d16931e069b7e646cd88..bd25fb4de836f01f7eef14a6d480fbbdfcff66a2 100644 --- a/test/unittest/UTTest_hichain_connector.h +++ b/test/unittest/UTTest_ipc_client_manager.h @@ -4,7 +4,7 @@ * 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 + * 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, @@ -12,29 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef OHOS_UTTEST_HICHAIN_CONNECTOR_H -#define OHOS_UTTEST_HICHAIN_CONNECTOR_H + +#ifndef OHOS_IPC_CLIENT_MANAGER_TEST_H +#define OHOS_IPC_CLIENT_MANAGER_TEST_H #include #include -#include -#include -#include -#include -#include - -#include "nlohmann/json.hpp" -#include "device_auth.h" -#include "single_instance.h" -#include "hichain_connector_callback.h" -#include "device_manager_service_listener.h" -#include "dm_auth_manager.h" -#include "dm_device_state_manager.h" -#include "hichain_connector.h" +#include "mock/mock_ipc_client_manager.h" +#include "ipc_client_manager.h" namespace OHOS { namespace DistributedHardware { -class HichainConnectorTest : public testing::Test { +class IpcClientManagerTest : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); @@ -43,4 +32,5 @@ public: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_HICHAIN_CONNECTOR_H + +#endif // OHOS_IPC_CLIENT_MANAGER_TEST_H diff --git a/test/unittest/UTTest_ipc_client_proxy.cpp b/test/unittest/UTTest_ipc_client_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..336800b964157d84cc07840048686ae8d61126a5 --- /dev/null +++ b/test/unittest/UTTest_ipc_client_proxy.cpp @@ -0,0 +1,414 @@ +/* + * Copyright (c) 2021 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 "UTTest_ipc_client_proxy.h" +#include "dm_device_info.h" +#include "ipc_remote_broker.h" +#include "iremote_object.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "ipc_client_manager.h" +#include "dm_constants.h" + +#include + +namespace OHOS { +namespace DistributedHardware { +void IpcClientProxyTest::SetUp() +{ +} + +void IpcClientProxyTest::TearDown() +{ +} + +void IpcClientProxyTest::SetUpTestCase() +{ +} + +void IpcClientProxyTest::TearDownTestCase() +{ +} + +namespace { +/** + * @tc.name: Init_001 + * @tc.desc: 1. set pkgName not null + * 2. set IpcClientProxy ipcClientManager nullptr + * 3. call IpcClientProxy Init + * 4. check ret is DM_POINT_NULL + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, Init_001, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. set IpcClientProxy ipcClientManager nullptr + std::shared_ptr ipcClientManager = nullptr; + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + // 3. call IpcClientProxy + int32_t ret = ipcClientProxy->Init(pkgName); + // 4. check ret is DM_POINT_NULL + ASSERT_EQ(ret, DM_POINT_NULL); +} + +/** + * @tc.name: Init_002 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClient Init return DM_FAILED + * 3. call IpcClientProxy Init + * 4. check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, Init_002, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClient Init return DM_FAILED + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientManager = mockInstance; + EXPECT_CALL(*mockInstance, Init(testing::_)).Times(1).WillOnce(testing::Return(DM_FAILED)); + // 3. call IpcClientProxy Init + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + int32_t ret = ipcClientProxy->Init(pkgName); + // 4. check ret is DM_FAILED + ASSERT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: Init_003 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClient Init return DM_OK + * 3. call IpcClientProxy Init + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, Init_003, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClient Init return DM_OK + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientManager = mockInstance; + EXPECT_CALL(*mockInstance, Init(testing::_)).Times(1).WillOnce(testing::Return(DM_OK)); + // 3. call IpcClientProxy Init + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + int32_t ret = ipcClientProxy->Init(pkgName); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: Init_004 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClient Init return DM_SERVICE_NOT_READY + * 3. call IpcClientProxy Init + * 4. check ret is DM_SERVICE_NOT_READY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, Init_004, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClient Init return DM_SERVICE_NOT_READY + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientManager = mockInstance; + EXPECT_CALL(*mockInstance, Init(testing::_)).Times(1).WillOnce(testing::Return(DM_SERVICE_NOT_READY)); + // 3. call IpcClientProxy Init + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + int32_t ret = ipcClientProxy->Init(pkgName); + // 4. check ret is DM_SERVICE_NOT_READY + ASSERT_EQ(ret, DM_SERVICE_NOT_READY); +} + +/** + * @tc.name: Init_005 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClient Init return DM_IPC_FAILED + * 3. call IpcClientProxy Init + * 4. check ret is DM_IPC_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, Init_005, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClient Init return DM_IPC_FAILED + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientManager = mockInstance; + EXPECT_CALL(*mockInstance, Init(testing::_)).Times(1).WillOnce(testing::Return(DM_IPC_FAILED)); + // 3. call IpcClientProxy Init + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + int32_t ret = ipcClientProxy->Init(pkgName); + // 4. check ret is DM_IPC_FAILED + ASSERT_EQ(ret, DM_IPC_FAILED); +} + +/** + * @tc.name: UnInit_001 + * @tc.desc: 1. set pkgName not null + * 2. set IpcClientProxy ipcClientManager nullptr + * 3. call IpcClientProxy UnInit + * 4. check ret is DM_POINT_NULL + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, UnInit_001, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. set IpcClientProxy ipcClientManager nullptr + std::shared_ptr ipcClientManager = nullptr; + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + // 3. call IpcClientProxy + int32_t ret = ipcClientProxy->UnInit(pkgName); + // 4. check ret is DM_POINT_NULL + ASSERT_EQ(ret, DM_POINT_NULL); +} + +/** + * @tc.name: UnInit_002 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClient Init return DM_FAILED + * 3. call IpcClientProxy UnInit + * 4. check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, UnInit_002, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClient Init return DM_FAILED + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientManager = mockInstance; + EXPECT_CALL(*mockInstance, UnInit(testing::_)).Times(1).WillOnce(testing::Return(DM_FAILED)); + // 3. call IpcClientProxy Init + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + int32_t ret = ipcClientProxy->UnInit(pkgName); + // 4. check ret is DM_FAILED + ASSERT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: UnInit_003 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClient UnInit return DM_OK + * 3. call IpcClientProxy UnInit + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, UnInit_003, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClient Init return DM_OK + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientManager = mockInstance; + EXPECT_CALL(*mockInstance, UnInit(testing::_)).Times(1).WillOnce(testing::Return(DM_OK)); + // 3. call IpcClientProxy Init + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + int32_t ret = ipcClientProxy->UnInit(pkgName); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: UnInit_004 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClient UnInit return DM_SERVICE_NOT_READY + * 3. call IpcClientProxy UnInit + * 4. check ret is DM_SERVICE_NOT_READY + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, UnInit_004, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClient Init return DM_SERVICE_NOT_READY + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientManager = mockInstance; + EXPECT_CALL(*mockInstance, UnInit(testing::_)).Times(1).WillOnce(testing::Return(DM_SERVICE_NOT_READY)); + // 3. call IpcClientProxy Init + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + int32_t ret = ipcClientProxy->UnInit(pkgName); + // 4. check ret is DM_SERVICE_NOT_READY + ASSERT_EQ(ret, DM_SERVICE_NOT_READY); +} + +/** + * @tc.name: UnInit_005 + * @tc.desc: 1. set pkgName not null + * 2. Mock IpcClient UnInit return DM_IPC_FAILED + * 3. call IpcClientProxy UnInit + * 4. check ret is DM_IPC_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, UnInit_005, testing::ext::TestSize.Level0) +{ + // 1. set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. Mock IpcClient Init return DM_IPC_FAILED + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientManager = mockInstance; + EXPECT_CALL(*mockInstance, UnInit(testing::_)).Times(1).WillOnce(testing::Return(DM_IPC_FAILED)); + // 3. call IpcClientProxy Init + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + int32_t ret = ipcClientProxy->UnInit(pkgName); + // 4. check ret is DM_IPC_FAILED + ASSERT_EQ(ret, DM_IPC_FAILED); +} + +/** + * @tc.name: SendRequest_001 + * @tc.desc: 1. set req nullptr + * set rsp not nullptr + * set IpcClientProxy ipcClientManager not null + * 2. call IpcClientProxy SendRequest + * 3. check ret is DEVICEMANAGER_NULLPTR + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, SendRequest_001, testing::ext::TestSize.Level0) +{ + // 1. set req nullptr + std::shared_ptr req = nullptr; + // set rsp not nullptr + std::shared_ptr rsp = std::make_shared(); + // set pcClientProxy ipcClientManager not null + std::shared_ptr ipcClientManager = std::make_shared(); + // 2. call IpcClientProxy SendRequest + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + int32_t ret = ipcClientProxy->SendRequest(0, req, rsp); + // 3. check ret is DEVICEMANAGER_NULLPTR + ASSERT_EQ(ret, DM_POINT_NULL); +} + +/** + * @tc.name: SendRequest_002 + * @tc.desc: 1. set req not nullptr + * set rsp nullptr + * set IpcClientProxy ipcClientManager not null + * 2. call IpcClientProxy SendRequest + * 3. check ret is DM_POINT_NULL + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, SendRequest_002, testing::ext::TestSize.Level0) +{ + // 1. set req not nullptr + std::shared_ptr req = std::make_shared(); + // set rsp nullptr + std::shared_ptr rsp = nullptr; + // set pcClientProxy ipcClientManager not null + std::shared_ptr ipcClientManager = std::make_shared(); + // 2. call IpcClientProxy SendRequest + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + int32_t ret = ipcClientProxy->SendRequest(0, req, rsp); + // 3. check ret is DM_POINT_NULL + ASSERT_EQ(ret, DM_POINT_NULL); +} + +/** + * @tc.name: SendRequest_003 + * @tc.desc: 1. set req not nullptr + * set rsp not nullptr + * set IpcClientProxy ipcClientManager null + * 2. call IpcClientProxy SendRequest + * 3. check ret is DM_POINT_NULL + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, SendRequest_003, testing::ext::TestSize.Level0) +{ + // 1. set req not nullptr + std::shared_ptr req = std::make_shared(); + // set rsp not nullptr + std::shared_ptr rsp = std::make_shared(); + // set pcClientProxy ipcClientManager null + std::shared_ptr ipcClientManager = nullptr; + // 2. call IpcClientProxy SendRequest + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + int32_t ret = ipcClientProxy->SendRequest(0, req, rsp); + // 3. check ret is DM_POINT_NULL + ASSERT_EQ(ret, DM_POINT_NULL); +} + +/** + * @tc.name: SendRequest_004 + * @tc.desc: 1. set req not nullptr + * set rsp not nullptr + * 2. Mock IpcClient SendRequest return DM_FAILED + * 3. call IpcClientProxy SendRequest + * 4. check ret is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, SendRequest_004, testing::ext::TestSize.Level0) +{ + // 1. set req not nullptr + std::shared_ptr req = std::make_shared(); + // set rsp not nullptr + std::shared_ptr rsp = std::make_shared(); + // 2. Mock IpcClient SendRequest return DM_FAILED + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientManager = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_FAILED)); + // 3. call IpcClientProxy SendRequest + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + int32_t ret = ipcClientProxy->SendRequest(0, req, rsp); + // 4. check ret is DM_FAILED + ASSERT_EQ(ret, DM_FAILED); +} + +/** + * @tc.name: SendRequest_004 + * @tc.desc: 1. set req not nullptr + * set rsp not nullptr + * 2. Mock IpcClient SendRequest return DM_OK + * 3. call IpcClientProxy SendRequest + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientProxyTest, SendRequest5, testing::ext::TestSize.Level0) +{ + // 1. set req not nullptr + std::shared_ptr req = std::make_shared(); + // set rsp not nullptr + std::shared_ptr rsp = std::make_shared(); + // 2. Mock IpcClient SendRequest return DM_FAILED + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientManager = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(DM_OK)); + // 3. call IpcClientProxy SendRequest + std::shared_ptr ipcClientProxy = std::make_shared(ipcClientManager); + int32_t ret = ipcClientProxy->SendRequest(0, req, rsp); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_ipc_client_proxy.h b/test/unittest/UTTest_ipc_client_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..b6c6556ac3884604c91564edf6c7b6bb1eccc416 --- /dev/null +++ b/test/unittest/UTTest_ipc_client_proxy.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 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. + */ + +#ifndef OHOS_IPC_CLIENT_PROXY_TEST_H +#define OHOS_IPC_CLIENT_PROXY_TEST_H + +#include +#include + +#include "mock/mock_ipc_client.h" +#include "ipc_client_proxy.h" +#include "ipc_client.h" +#include "ipc_req.h" +#include "ipc_rsp.h" +namespace OHOS { +namespace DistributedHardware { +class IpcClientProxyTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_IPC_CLIENT_PROXY_TEST_H diff --git a/test/unittest/UTTest_ipc_client_stub.cpp b/test/unittest/UTTest_ipc_client_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c3ff9a86af5a16ac1811da346c4b342dddfa9552 --- /dev/null +++ b/test/unittest/UTTest_ipc_client_stub.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2021 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 "UTTest_ipc_client_stub.h" +#include "dm_device_info.h" +#include "ipc_remote_broker.h" +#include "iremote_object.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "ipc_client_manager.h" +#include "ipc_set_useroperation_req.h" +#include "ipc_cmd_register.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "ipc_rsp.h" +#include "ipc_def.h" +#include "dm_constants.h" + +#include + +namespace OHOS { +namespace DistributedHardware { +void IpcClientStubTest::SetUp() +{ +} + +void IpcClientStubTest::TearDown() +{ +} + +void IpcClientStubTest::SetUpTestCase() +{ +} + +void IpcClientStubTest::TearDownTestCase() +{ +} + +namespace { +/** + * @tc.name: OnRemoteRequest_001 + * @tc.desc: 1. set MessageOption not null + * set MessageParcel not null + * set MessageParcel not null + * 2. set set code is 999 + * 3. call IpcClientStub OnRemoteRequest with parameter + * 4. check result is DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientStubTest, OnRemoteRequest_001, testing::ext::TestSize.Level0) +{ + // 1. set MessageOption not null + MessageOption option; + // set MessageParcel not null + MessageParcel data; + // set MessageParcel not null + MessageParcel reply; + // 2. set set code is 999 + int code = 999; + sptr instance = new IpcClientStub(); + // 3. call IpcClientStub OnRemoteRequest with parameter + int32_t ret = instance->OnRemoteRequest(code, data, reply, option); + int32_t result = DM_OK; + if (ret != result) { + result = DM_FAILED; + } + // 4. check result is DM_FAILED + ASSERT_EQ(result, DM_FAILED); +} + +/** + * @tc.name: OnRemoteRequest_002 + * @tc.desc: 1. set MessageOption not null + * set MessageParcel not null + * set MessageParcel not null + * 2. set set code is SERVER_DEVICE_FA_NOTIFY + * 3. call IpcClientStub OnRemoteRequest with parameter + * 4. check result is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientStubTest, OnRemoteRequest_002, testing::ext::TestSize.Level0) +{ + // 1. set MessageOption not null + MessageOption option; + // set MessageParcel not null + MessageParcel data; + // set MessageParcel not null + MessageParcel reply; + // 2. set set code is SERVER_DEVICE_FA_NOTIFY + int code = SERVER_DEVICE_FA_NOTIFY; + sptr instance = new IpcClientStub(); + // 3. call IpcClientStub OnRemoteRequest with parameter + int ret = instance->OnRemoteRequest(code, data, reply, option); + // 4. check result is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SendCmd_001 + * @tc.desc: 1. set set code is SERVER_DEVICE_FA_NOTIFY + * set req is nullptr + * set rsp is nullptr + * 2. call IpcClientStub SendCmd with parameter + * 3. check result is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcClientStubTest, SendCmd_001, testing::ext::TestSize.Level0) +{ + // 1. set set code is SERVER_DEVICE_FA_NOTIFY + int cmdCode = SERVER_DEVICE_FA_NOTIFY; + // set req is nullptr + std::shared_ptr req = nullptr; + // set rsp is nullptr + std::shared_ptr rsp = nullptr; + sptr instance = new IpcClientStub(); + // 2. call IpcClientStub SendCmd with parameter + int ret = instance->SendCmd(cmdCode, req, rsp); + // 3. check result is DM_OK + ASSERT_EQ(ret, DM_IPC_FAILED); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_ipc_client_stub.h b/test/unittest/UTTest_ipc_client_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..5ba7391c9f0b0e077cb9413e6f2a2a1e9dcf66f1 --- /dev/null +++ b/test/unittest/UTTest_ipc_client_stub.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 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. + */ + +#ifndef OHOS_IPC_CLIENT_STUB_TEST_H +#define OHOS_IPC_CLIENT_STUB_TEST_H + +#include +#include + +#include "ipc_client_stub.h" +namespace OHOS { +namespace DistributedHardware { +class IpcClientStubTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_IPC_CLIENT_STUB_TEST_H diff --git a/test/unittest/UTTest_ipc_server_client_proxy.cpp b/test/unittest/UTTest_ipc_server_client_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61d825e3a3ca781bd599c4f01ce83173e857890f --- /dev/null +++ b/test/unittest/UTTest_ipc_server_client_proxy.cpp @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2021 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 "UTTest_ipc_server_client_proxy.h" +#include +#include "dm_device_info.h" +#include "ipc_remote_broker.h" +#include "iremote_object.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "ipc_client_manager.h" +#include "ipc_set_useroperation_req.h" +#include "ipc_notify_device_state_req.h" +#include "ipc_rsp.h" +#include "ipc_notify_device_found_req.h" +#include "ipc_notify_discover_result_req.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { +void IpcServerClientProxyTest::SetUp() +{ +} + +void IpcServerClientProxyTest::TearDown() +{ +} + +void IpcServerClientProxyTest::SetUpTestCase() +{ +} + +void IpcServerClientProxyTest::TearDownTestCase() +{ +} + +namespace { +/** + * @tc.name: SendCmd_001 + * @tc.desc: 1. set cmdCode not null + * 2. set remoteObject nullptr + * 3. call IpcServerClientProxy SendCmd + * 4. check ret is DEVICEMANAGER_NULLPTR + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerClientProxyTest, SendCmd_001, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = 1; + // 2. set remoteObject nullptr + sptr remoteObject = nullptr; + // 3. call IpcServerClientProxy SendCmd + auto instance = new IpcServerClientProxy(remoteObject); + int ret = instance->SendCmd(cmdCode, nullptr, nullptr); + // 4. check ret is DEVICEMANAGER_NULLPTR + ASSERT_EQ(ret, DM_POINT_NULL); +} + +/** + * @tc.name: SendCmd_002 + * @tc.desc: 1. set cmdCode not null + * set pkgName not null + * set action not null + * 2. set remoteObject not nullptr + * set req not null + * set rsp not null + * 3. call IpcServerClientProxy SendCmd with parameter + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerClientProxyTest, SendCmd_002, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = SERVER_DEVICE_STATE_NOTIFY; + // set pkgName not null + std::string pkgName = "com.ohos.test"; + // set action not null + int deviceState = 1; + DmDeviceInfo deviceInfo; + // 2. set remoteObject not nullptr + sptr remoteObject = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + // set req not null + req->SetPkgName(pkgName); + // set rsp not null + req->SetDeviceState(deviceState); + req->SetDeviceInfo(deviceInfo); + // 3. call IpcServerClientProxy SendCmd with parameter + int ret = 0; + std::shared_ptr ipcServerListener = std::make_shared(); + ret = ipcServerListener->SendRequest(cmdCode, req, rsp); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SendCmd_003 + * @tc.desc: 1. set cmdCode not null + * set pkgName not null + * set action not null + * 2. set remoteObject not nullptr + * set req not null + * set rsp not null + * 3. call IpcServerClientProxy SendCmd with parameter + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerClientProxyTest, SendCmd_003, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = SERVER_DEVICE_FOUND; + // set pkgName not null + std::string pkgName = "com.ohos.test"; + // set action not null + uint16_t subscribeId = 1; + DmDeviceInfo dmDeviceInfo; + // 2. set remoteObject not nullptr + sptr remoteObject = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + // set req not null + req->SetPkgName(pkgName); + // set rsp not null + req->SetSubscribeId(subscribeId); + req->SetDeviceInfo(dmDeviceInfo); + // 3. call IpcServerClientProxy SendCmd with parameter + int ret = 0; + std::shared_ptr ipcServerListener = std::make_shared(); + ret = ipcServerListener->SendRequest(cmdCode, req, rsp); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SendCmd_004 + * @tc.desc: 1. set cmdCode not null + * set pkgName not null + * set action not null + * 2. set remoteObject not nullptr + * set req not null + * set rsp not null + * 3. call IpcServerClientProxy SendCmd with parameter + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerClientProxyTest, SendCmd_004, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = SERVER_DISCOVER_FINISH; + // set pkgName not null + std::string pkgName = "com.ohos.test"; + // set action not null + uint16_t subscribeId = 1; + int32_t result = 1; + // 2. set remoteObject not nullptr + sptr remoteObject = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + // set req not null + req->SetPkgName(pkgName); + // set rsp not null + req->SetSubscribeId(subscribeId); + req->SetResult(result); + // 3. call IpcServerClientProxy SendCmd with parameter + int ret = 0; + std::shared_ptr ipcServerListener = std::make_shared(); + ret = ipcServerListener->SendRequest(cmdCode, req, rsp); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_ipc_server_client_proxy.h b/test/unittest/UTTest_ipc_server_client_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..2de4bdf6ccf6b2b38a020de08ce12b0b75fa5bf7 --- /dev/null +++ b/test/unittest/UTTest_ipc_server_client_proxy.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 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. + */ + +#ifndef OHOS_IPC_SERVER_CLIENT_PROXY_TEST_H +#define OHOS_IPC_SERVER_CLIENT_PROXY_TEST_H + +#include + +#include "ipc_server_client_proxy.h" +#include "ipc_client_stub.h" +#include "ipc_server_stub.h" +#include "ipc_server_listener.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcServerClientProxyTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_IPC_SERVER_CLIENT_PROXY_TEST_H diff --git a/test/unittest/UTTest_ipc_server_listener.cpp b/test/unittest/UTTest_ipc_server_listener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2c4674cb163ed7775f932e70b5ebd8dd092dfafa --- /dev/null +++ b/test/unittest/UTTest_ipc_server_listener.cpp @@ -0,0 +1,381 @@ +/* + * Copyright (c) 2021 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 "UTTest_ipc_server_listener.h" + +#include +#include "dm_device_info.h" +#include "ipc_remote_broker.h" +#include "iremote_object.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "ipc_client_manager.h" +#include "ipc_set_useroperation_req.h" +#include "ipc_notify_device_state_req.h" +#include "ipc_req.h" +#include "ipc_rsp.h" +#include "dm_constants.h" + + +namespace OHOS { +namespace DistributedHardware { +void IpcServerListenerTest::SetUp() +{ +} + +void IpcServerListenerTest::TearDown() +{ +} + +void IpcServerListenerTest::SetUpTestCase() +{ +} + +void IpcServerListenerTest::TearDownTestCase() +{ +} + +namespace { +/** + * @tc.name: SendRequest_001 + * @tc.desc: 1. set cmdCode not null + * set pkgName not null + * 2. set remoteObject nullptr + * set req not null + * set rsp not null + * 3. call IpcServerListener SendRequest + * 4. check ret is DM_POINT_NULL + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerListenerTest, SendRequest_001, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = 999; + // set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. set remoteObject nullptr + sptr remoteObject = nullptr; + // set req not null + std::shared_ptr req = std::make_shared(); + // set rsp not null + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 3. call IpcServerListener SendRequest + std::shared_ptr ipcServerListener = std::make_shared(); + int ret = ipcServerListener->SendRequest(cmdCode, req, rsp); + // 4. check ret is DM_POINT_NULL + ASSERT_EQ(ret, DM_POINT_NULL); +} + +/** + * @tc.name: SendRequest_002 + * @tc.desc: 1. set cmdCode not null + * set pkgName not null + * 2. set remoteObject nullptr + * set req not null + * set rsp not null + * 3. call IpcServerListener SendRequest + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerListenerTest, SendRequest_002, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = SERVER_DEVICE_STATE_NOTIFY; + // set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. set remoteObject not nullptr + sptr remoteObject = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + // set req not null + std::shared_ptr req = std::make_shared(); + // set rsp not null + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 3. call IpcServerListener SendRequest + std::shared_ptr ipcServerListener = std::make_shared(); + int ret = ipcServerListener->SendRequest(cmdCode, req, rsp); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SendRequest_003 + * @tc.desc: 1. set cmdCode not null + * set pkgName not null + * 2. set remoteObject nullptr + * set req not null + * set rsp not null + * 3. call IpcServerListener SendRequest + * 4. check ret is DM_IPC_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerListenerTest, SendRequest_003, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = 9999; + // set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. set remoteObject not nullptr + sptr remoteObject = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + // set req not null + std::shared_ptr req = std::make_shared(); + // set rsp not null + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 3. call IpcServerListener SendRequest + std::shared_ptr ipcServerListener = std::make_shared(); + int ret = ipcServerListener->SendRequest(cmdCode, req, rsp); + // 4. check ret is DM_IPC_FAILED + ASSERT_EQ(ret, DM_IPC_FAILED); +} + +/** + * @tc.name: SendRequest_004 + * @tc.desc: 1. set cmdCode not null + * set pkgName not null + * 2. set remoteObject nullptr + * set req not null + * set rsp not null + * 3. call IpcServerListener SendRequest + * 4. check ret is DM_POINT_NULL + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerListenerTest, SendRequest_004, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = SERVER_DEVICE_STATE_NOTIFY; + // set pkgName not null + std::string pkgName = ""; + // 2. set remoteObject not nullptr + sptr remoteObject = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + // set req not null + std::shared_ptr req = std::make_shared(); + // set rsp not null + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 3. call IpcServerListener SendRequest + std::shared_ptr ipcServerListener = std::make_shared(); + int ret = ipcServerListener->SendRequest(cmdCode, req, rsp); + // 4. check ret is DM_POINT_NULL + ASSERT_EQ(ret, DM_POINT_NULL); +} + +/** + * @tc.name: SendRequest_005 + * @tc.desc: 1. set cmdCode not null + * set pkgName not null + * 2. set remoteObject nullptr + * set req not null + * set rsp not null + * 3. call IpcServerListener SendRequest + * 4. check ret is DM_POINT_NULL + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerListenerTest, SendRequest_005, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = 9999; + // set pkgName not null + std::string pkgName = ""; + // 2. set remoteObject not nullptr + sptr remoteObject = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + // set req not null + std::shared_ptr req = std::make_shared(); + // set rsp not null + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 3. call IpcServerListener SendRequest + std::shared_ptr ipcServerListener = std::make_shared(); + int ret = ipcServerListener->SendRequest(cmdCode, req, rsp); + // 4. check ret is DM_POINT_NULL + ASSERT_EQ(ret, DM_POINT_NULL); +} + +/** + * @tc.name: SendAll_001 + * @tc.desc: 1. set cmdCode not null + * set pkgName not null + * 2. set remoteObject nullptr + * set req not null + * set rsp not null + * 3. call IpcServerListener SendRequest + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerListenerTest, SendAll_001, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = SERVER_DEVICE_STATE_NOTIFY; + // set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. set remoteObject not nullptr + sptr remoteObject = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + // set req not null + std::shared_ptr req = std::make_shared(); + // set rsp not null + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 3. call IpcServerListener SendRequest + std::shared_ptr ipcServerListener = std::make_shared(); + int ret = ipcServerListener->SendAll(cmdCode, req, rsp); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SendAll_002 + * @tc.desc: 1. set cmdCode not null + * set pkgName not null + * 2. set remoteObject nullptr + * set req not null + * set rsp not null + * 3. call IpcServerListener SendRequest + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerListenerTest, SendAll_002, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = 9999; + // set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. set remoteObject not nullptr + sptr remoteObject = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + // set req not null + std::shared_ptr req = std::make_shared(); + // set rsp not null + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 3. call IpcServerListener SendRequest + std::shared_ptr ipcServerListener = std::make_shared(); + int ret = ipcServerListener->SendAll(cmdCode, req, rsp); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SendAll_003 + * @tc.desc: 1. set cmdCode not null + * set pkgName not null + * 2. set remoteObject nullptr + * set req not null + * set rsp not null + * 3. call IpcServerListener SendRequest + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerListenerTest, SendAll_003, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = SERVER_DEVICE_STATE_NOTIFY; + // set pkgName not null + std::string pkgName = ""; + // 2. set remoteObject not nullptr + sptr remoteObject = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + // set req not null + std::shared_ptr req = std::make_shared(); + // set rsp not null + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 3. call IpcServerListener SendRequest + std::shared_ptr ipcServerListener = std::make_shared(); + int ret = ipcServerListener->SendAll(cmdCode, req, rsp); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SendAll_004 + * @tc.desc: 1. set cmdCode not null + * set pkgName not null + * 2. set remoteObject nullptr + * set req not null + * set rsp not null + * 3. call IpcServerListener SendRequest + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerListenerTest, SendAll_004, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = 9999; + // set pkgName not null + std::string pkgName = ""; + // 2. set remoteObject not nullptr + sptr remoteObject = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + // set req not null + std::shared_ptr req = std::make_shared(); + // set rsp not null + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + // 3. call IpcServerListener SendRequest + std::shared_ptr ipcServerListener = std::make_shared(); + int ret = ipcServerListener->SendAll(cmdCode, req, rsp); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SendAll_005 + * @tc.desc: 1. set cmdCode not null + * set pkgName not null + * 2. set remoteObject nullptr + * set req not null + * set rsp not null + * 3. call IpcServerListener SendRequest + * 4. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerListenerTest, SendAll_005, testing::ext::TestSize.Level0) +{ + // 1. set cmdCode not null + int32_t cmdCode = SERVER_DEVICE_STATE_NOTIFY; + // set pkgName not null + std::string pkgName = "com.ohos.test"; + // 2. set remoteObject not nullptr + sptr remoteObject = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + // set req not null + std::shared_ptr req = std::make_shared(); + // set rsp not null + std::shared_ptr rsp = nullptr; + req->SetPkgName(pkgName); + // 3. call IpcServerListener SendRequest + std::shared_ptr ipcServerListener = std::make_shared(); + int ret = ipcServerListener->SendAll(cmdCode, req, rsp); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_ipc_server_listener.h b/test/unittest/UTTest_ipc_server_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..0d51a7aac18205373b59204df0920b469e82414b --- /dev/null +++ b/test/unittest/UTTest_ipc_server_listener.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 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. + */ + +#ifndef OHOS_IPC_SERVER_LISTENER_TEST_H +#define OHOS_IPC_SERVER_LISTENER_TEST_H + +#include + +#include "ipc_client_stub.h" +#include "ipc_server_stub.h" +#include "ipc_server_listener.h" +namespace OHOS { +namespace DistributedHardware { +class IpcServerListenerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_IPC_SERVER_CLIENT_PROXY_TEST_H diff --git a/test/unittest/UTTest_ipc_server_stub.cpp b/test/unittest/UTTest_ipc_server_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9bd4cf34970f9798567968783cf8e56577dacfdb --- /dev/null +++ b/test/unittest/UTTest_ipc_server_stub.cpp @@ -0,0 +1,546 @@ +/* + * Copyright (c) 2021 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 "UTTest_ipc_server_stub.h" +#include "dm_device_info.h" +#include "ipc_server_stub.h" +#include "device_manager_impl.h" +#include "dm_constants.h" +#include "if_system_ability_manager.h" +#include "ipc_cmd_register.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "system_ability_definition.h" + +#include +#include +#include + +namespace OHOS { +namespace DistributedHardware { +void IpcServerStubTest::SetUp() +{ +} + +void IpcServerStubTest::TearDown() +{ +} + +void IpcServerStubTest::SetUpTestCase() +{ +} + +void IpcServerStubTest::TearDownTestCase() +{ +} + +namespace { +/** + * @tc.name: OnStart_001 + * @tc.desc: 1. Call IpcServerStub OnStart + * 2. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, OnStart_001, testing::ext::TestSize.Level0) +{ + // 1. Call IpcServerStub OnStart + IpcServerStub::GetInstance().OnStart(); + // 2. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + ASSERT_EQ(ServiceRunningState::STATE_RUNNING, IpcServerStub::GetInstance().state_); +} + +/** + * @tc.name: OnStart_002 + * @tc.desc: 1. set IpcServerStub state is ServiceRunningState::STATE_RUNNING + * 2. Call IpcServerStub OnStart + * 3. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, OnStart_002, testing::ext::TestSize.Level0) +{ + // 1. set IpcServerStub state is ServiceRunningState::STATE_RUNNING + IpcServerStub::GetInstance().state_ = ServiceRunningState::STATE_RUNNING; + // 2. Call IpcServerStub OnStart + IpcServerStub::GetInstance().OnStart(); + // 3. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + ASSERT_EQ(ServiceRunningState::STATE_RUNNING, IpcServerStub::GetInstance().state_); +} + +/** + * @tc.name: Init_001 + * @tc.desc: 1. Call IpcServerStub OnStart + * 2. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, Init_001, testing::ext::TestSize.Level0) +{ + IpcServerStub::GetInstance().registerToService_=true; + bool result = IpcServerStub::GetInstance().Init(); + // 2. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + ASSERT_EQ(result, true); +} + +/** + * @tc.name: Init_002 + * @tc.desc: 1. Call IpcServerStub OnStart + * 2. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, Init_002, testing::ext::TestSize.Level0) +{ + IpcServerStub::GetInstance().registerToService_=false; + bool result = IpcServerStub::GetInstance().Init(); + // 2. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + ASSERT_EQ(result, true); +} + +/** + * @tc.name: OnStop_001 + * @tc.desc: 1. Call IpcServerStub OnStop + * 2. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, OnStop_001, testing::ext::TestSize.Level0) +{ + // 1. Call IpcServerStub OnStop + IpcServerStub::GetInstance().OnStop(); + // 2. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + ASSERT_EQ(ServiceRunningState::STATE_NOT_START, IpcServerStub::GetInstance().state_); + ASSERT_EQ(IpcServerStub::GetInstance().registerToService_, false); +} + +/** + * @tc.name: OnRemoteRequest_001 + * @tc.desc: 1. Set Code = 999 + * 2. Call IpcServerStub OnRemoteRequest with param + * 3. check ret not DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, OnRemoteRequest_001, testing::ext::TestSize.Level0) +{ + // 1. Set Code = 999 + uint32_t code = 999; + MessageParcel data; + MessageParcel reply; + MessageOption option; + int ret = 0; + // 2. Call IpcServerStub OnRemoteRequest with param + ret = IpcServerStub::GetInstance().OnRemoteRequest(code, data, reply, option); + // 3. check ret not DM_OK + ASSERT_NE(ret, DM_OK); +} + +/** + * @tc.name: OnRemoteRequest_002 + * @tc.desc: 1. Set Code = 999 + * 2. Call IpcServerStub OnRemoteRequest with param + * 3. check ret not DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, OnRemoteRequest_002, testing::ext::TestSize.Level0) +{ + // 1. Set Code is SERVER_DEVICE_STATE_NOTIFY + uint32_t code = SERVER_DEVICE_STATE_NOTIFY; + MessageParcel data; + MessageParcel reply; + MessageOption option; + int ret = 0; + // 2. Call IpcServerStub OnRemoteRequest with param + ret = IpcServerStub::GetInstance().OnRemoteRequest(code, data, reply, option); + // 3. check ret not DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SendCmd_001 + * @tc.desc: 1. Call IpcServerStub SendCmd + * 2. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, SendCmd_001, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = 1; + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + // 1. Call IpcServerStub SendCmd + int32_t ret = IpcServerStub::GetInstance().SendCmd(cmdCode, req, rsp); + // 2. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: QueryServiceState_001 + * @tc.desc: 1. Call IpcServerStub QueryServiceState + * 2. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, QueryServiceState_001, testing::ext::TestSize.Level0) +{ + IpcServerStub::GetInstance().state_ = ServiceRunningState::STATE_NOT_START; + // 1. Call IpcServerStub QueryServiceState + ServiceRunningState state = IpcServerStub::GetInstance().QueryServiceState(); + // 2. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + ASSERT_EQ(state, ServiceRunningState::STATE_NOT_START); +} + +/** + * @tc.name: RegisterDeviceManagerListener_001 + * @tc.desc: 1. Call IpcServerStub RegisterDeviceManagerListener + * 2. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + int ret = 0; + sptr listener = nullptr; + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ASSERT_EQ(ret, DM_POINT_NULL); +} + +/** + * @tc.name: RegisterDeviceManagerListener_002 + * @tc.desc: 1. Call IpcServerStub RegisterDeviceManagerListener + * 2. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_002, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + int ret = 0; + sptr listener = sptr(new IpcClientStub()); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: RegisterDeviceManagerListener_003 + * @tc.desc: 1. Call IpcServerStub RegisterDeviceManagerListener + * 2. check IpcServerStub.state is ServiceRunningState::STATE_RUNNING + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + int ret = 0; + sptr listener = sptr(new IpcClientStub()); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ASSERT_EQ(ret, DM_POINT_NULL); +} + +/** + * @tc.name: RegisterDeviceManagerListener_004 + * @tc.desc: 1. Set PkgName is com.ohos.test + * 2. Call IpcServerStub RegisterDeviceManagerListener with param + * 3. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_004, testing::ext::TestSize.Level0) +{ + // 1. Set PkgName is com.ohos.test + std::string pkgName = "com.ohos.test"; + int ret = 0; + sptr listener = sptr(new IpcClientStub()); + // 2. Call IpcServerStub RegisterDeviceManagerListener with param + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + // 3. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: RegisterDeviceManagerListener_005 + * @tc.desc: 1. Set PkgName is com.ohos.test + * 2. Call IpcServerStub RegisterDeviceManagerListener with param + * 3. check ret is DM_OK + * 4. Call IpcServerStub RegisterDeviceManagerListener with same pkgName another listener + * 5. check result is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_005, testing::ext::TestSize.Level0) +{ + // 1. Set PkgName is com.ohos.test + std::string pkgName = "com.ohos.test"; + int ret = 0; + int result = 0; + sptr listener = sptr(new IpcClientStub()); + // 2. Call IpcServerStub RegisterDeviceManagerListener with param + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + // 3. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); + sptr listener2 = sptr(new IpcClientStub()); + // 4. Call IpcServerStub RegisterDeviceManagerListener with same pkgName another listener + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener2); + // 5. check result is DM_OK + ASSERT_EQ(result, DM_OK); +} + +/** + * @tc.name: UnRegisterDeviceManagerListener_001 + * @tc.desc: 1. Call IpcServerStub UnRegisterDeviceManagerListener + * 2. check ret is DM_POINT_NULL + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + int ret = 0; + ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + ASSERT_EQ(ret, DM_POINT_NULL); +} + +/** + * @tc.name: UnRegisterDeviceManagerListener_002 + * @tc.desc: 1. Set PkgName is com.ohos.test + * 2. Call IpcServerStub RegisterDeviceManagerListener with param + * 3. check ret is DM_OK + * 4. Call IpcServerStub UnRegisterDeviceManagerListener + * 5. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_002, testing::ext::TestSize.Level0) +{ + // 1. Set PkgName is com.ohos.test + std::string pkgName = "com.ohos.test"; + int ret = 0; + sptr listener = sptr(new IpcClientStub()); + // 2. Call IpcServerStub RegisterDeviceManagerListener with param + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + // 3. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); + int result = 0; + // 4. Call IpcServerStub UnRegisterDeviceManagerListener + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + // 5. check ret is DM_OK + ASSERT_EQ(result, DM_OK); +} + +/** + * @tc.name: UnRegisterDeviceManagerListener_003 + * @tc.desc: 1. Set pkgName is com.ohos.test + * 2. Call IpcServerStub UnRegisterDeviceManagerListener + * 3. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_003, testing::ext::TestSize.Level0) +{ + // 1. Set pkgName is com.ohos.test + std::string pkgName = "com.ohos.test"; + int ret = 0; + // 2. Call IpcServerStub UnRegisterDeviceManagerListener + ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + // 3. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: UnRegisterDeviceManagerListener_004 + * @tc.desc: 1. Set PkgName is com.ohos.test + * 2. Call IpcServerStub RegisterDeviceManagerListener with param + * 3. check ret is DM_OK + * 4. Call IpcServerStub UnRegisterDeviceManagerListener + * 5. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_004, testing::ext::TestSize.Level0) +{ + // 1. Set PkgName is com.ohos.test + std::string pkgName = "com.ohos.test1"; + int ret = 0; + sptr listener = sptr(new IpcClientStub()); + // 2. Call IpcServerStub RegisterDeviceManagerListener with param + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + // 3. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); + int result = 0; + // 4. Call IpcServerStub UnRegisterDeviceManagerListener + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + // 5. check ret is DM_OK + ASSERT_EQ(result, DM_OK); + sptr dmListener = IpcServerStub::GetInstance().dmListener_[pkgName]; + ASSERT_EQ(dmListener, nullptr); +} + +/** + * @tc.name: UnRegisterDeviceManagerListener_005 + * @tc.desc: 1. Set PkgName is com.ohos.test + * 2. Call IpcServerStub RegisterDeviceManagerListener with param + * 3. check ret is DM_OK + * 4. Call IpcServerStub UnRegisterDeviceManagerListener + * 5. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_005, testing::ext::TestSize.Level0) +{ + // 1. Set PkgName is com.ohos.test + std::string pkgName = "com.ohos.test2"; + int ret = 0; + sptr listener = sptr(new IpcClientStub()); + // 2. Call IpcServerStub RegisterDeviceManagerListener with param + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + // 3. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); + int result = 0; + // 4. Call IpcServerStub UnRegisterDeviceManagerListener + std::string testPkgName = "com.test"; + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(testPkgName); + // 5. check ret is DM_OK + ASSERT_EQ(result, DM_OK); + sptr dmListener = IpcServerStub::GetInstance().dmListener_[pkgName]; + ASSERT_NE(dmListener, nullptr); +} + +/** + * @tc.name: GetDmListener_001 + * @tc.desc: 1. Set pkgName is com.ohos.test + * 2. Call IpcServerStub GetDmListener + * 3. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, GetDmListener_001, testing::ext::TestSize.Level0) +{ + // 1. Set pkgName is com.ohos.test + std::string pkgName = "com.ohos.test"; + sptr ret = nullptr; + // 2. Call IpcServerStub UnRegisterDeviceManagerListener + ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + // 3. check ret is DM_OK + ASSERT_EQ(ret, nullptr); +} + +/** + * @tc.name: GetDmListener_002 + * @tc.desc: 1. Set pkgName is com.ohos.test + * 2. Call IpcServerStub GetDmListener + * 3. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, GetDmListener_002, testing::ext::TestSize.Level0) +{ + // 1. Set pkgName is com.ohos.test + std::string pkgName = "com.ohos.test"; + int result = 0; + sptr listener = sptr(new IpcClientStub()); + // 2. Call IpcServerStub RegisterDeviceManagerListener with param + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + // 3. check ret is DM_OK + ASSERT_EQ(result, DM_OK); + sptr ret = nullptr; + // 2. Call IpcServerStub UnRegisterDeviceManagerListener + ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + // 3. check ret is DM_OK + ASSERT_NE(ret, nullptr); +} + +/** + * @tc.name: GetDmListener_003 + * @tc.desc: 1. Set pkgName is com.ohos.test + * 2. Call IpcServerStub GetDmListener + * 3. check ret is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, GetDmListener_003, testing::ext::TestSize.Level0) +{ + // 1. Set pkgName is com.ohos.test + std::string pkgName = "com.ohos.test"; + int result = 0; + sptr listener = sptr(new IpcClientStub()); + // 2. Call IpcServerStub RegisterDeviceManagerListener with param + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + // 3. check ret is DM_OK + ASSERT_EQ(result, DM_OK); + sptr ret = nullptr; + // 2. Call IpcServerStub UnRegisterDeviceManagerListener + std::string testPkgName = "test"; + ret = IpcServerStub::GetInstance().GetDmListener(testPkgName); + // 3. check ret is DM_OK + ASSERT_EQ(ret, nullptr); +} + +/** + * @tc.name: GetDmListener_004 + * @tc.desc: 1. Set pkgName is com.ohos.test + * 2. Call IpcServerStub GetDmListener + * 3. check ret is DM_POINT_NULL + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, GetDmListener_004, testing::ext::TestSize.Level0) +{ + // 1. Set pkgName is null + std::string pkgName = ""; + int result = 0; + sptr listener = sptr(new IpcClientStub()); + // 2. Call IpcServerStub RegisterDeviceManagerListener with param + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + // 3. check ret is DM_POINT_NULL + ASSERT_EQ(result, DM_POINT_NULL); + sptr ret = nullptr; + // 2. Call IpcServerStub UnRegisterDeviceManagerListener + ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + // 3. check ret is nullptr + ASSERT_EQ(ret, nullptr); +} + +/** + * @tc.name: GetDmListener_005 + * @tc.desc: 1. Set pkgName is com.ohos.test + * 2. Call IpcServerStub GetDmListener + * 3. check ret is DM_POINT_NULL + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, GetDmListener_005, testing::ext::TestSize.Level0) +{ + // 1. Set pkgName is null + std::string pkgName = "com.test.ohos"; + int result = 0; + sptr listener = nullptr; + // 2. Call IpcServerStub RegisterDeviceManagerListener with param + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + // 3. check ret is DM_POINT_NULL + ASSERT_EQ(result, DM_POINT_NULL); + sptr ret = nullptr; + // 2. Call IpcServerStub UnRegisterDeviceManagerListener + ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + // 3. check ret is nullptr + ASSERT_EQ(ret, nullptr); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_ipc_server_stub.h b/test/unittest/UTTest_ipc_server_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..f4b00c361c056baa66c58a217b0c5aa9ba54c87d --- /dev/null +++ b/test/unittest/UTTest_ipc_server_stub.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 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. + */ + +#ifndef OHOS_IPC_SERVER_STUB_TEST_H +#define OHOS_IPC_SERVER_STUB_TEST_H + +#include + +#include "ipc_client_stub.h" +#include "ipc_server_stub.h" +#include "ipc_server_listener.h" +namespace OHOS { +namespace DistributedHardware { +class IpcServerStubTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() override; + virtual void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_IPC_SERVER_STUB_TEST_H diff --git a/test/unittest/UTTest_softbus_connector.cpp b/test/unittest/UTTest_softbus_connector.cpp index 32491e69256ed4367dff0a1415a191fb977f976d..740b4e8e03a3b621b7a15ea307dba9121f7dea3e 100644 --- a/test/unittest/UTTest_softbus_connector.cpp +++ b/test/unittest/UTTest_softbus_connector.cpp @@ -87,7 +87,7 @@ HWTEST_F(SoftbusConnectorTest, UnRegisterSoftbusDiscoveryCallback_001, testing:: { std::string pkgName = "com.ohos.helloworld"; int ret = softbusConnector->UnRegisterSoftbusDiscoveryCallback(pkgName); - uint32_t ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); + int ret1 = SoftbusConnector::discoveryCallbackMap_.count(pkgName); EXPECT_EQ(ret1, 0); EXPECT_EQ(ret, DM_OK); } @@ -317,17 +317,6 @@ HWTEST_F(SoftbusConnectorTest, CovertNodeBasicInfoToDmDevice_001, testing::ext:: int ret = softbusConnector->CovertNodeBasicInfoToDmDevice(nodeBasicInfo, dmDeviceInfo); EXPECT_EQ(ret, DM_OK); } - -/** - * @tc.name: OnParameterChgCallback_001 - * @tc.desc: set some corrort para and return DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(SoftbusConnectorTest, OnParameterChgCallback_001, testing::ext::TestSize.Level0) -{ - EXPECT_EQ(DM_OK, DM_OK); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_softbus_session.cpp b/test/unittest/UTTest_softbus_session.cpp index 8d14ff0e15e2f64120c6dabf195f78ad9dd3307f..41bc71f33aae5cf10b6919578a4d1c786f88ca29 100644 --- a/test/unittest/UTTest_softbus_session.cpp +++ b/test/unittest/UTTest_softbus_session.cpp @@ -38,11 +38,11 @@ void SoftbusSessionTest::TearDownTestCase() namespace { std::shared_ptr softbusSession = std::make_shared(); -std::shared_ptr listener_ = std::make_shared(); +std::shared_ptr listener = std::make_shared(); std::shared_ptr softbusConnector = std::make_shared(); std::shared_ptr hiChainConnector = std::make_shared(); -std::shared_ptr discoveryMgr_ = - std::make_shared(softbusConnector, listener_, hiChainConnector); +std::shared_ptr discoveryMgr = + std::make_shared(softbusConnector, listener, hiChainConnector); /** * @tc.name: OpenAuthSession_001 @@ -98,7 +98,7 @@ HWTEST_F(SoftbusSessionTest, SendData_002, testing::ext::TestSize.Level0) jsonObj[TAG_TYPE] = msgType; std::string message = jsonObj.dump(); int32_t sessionId = 0; - softbusSession->RegisterSessionCallback(std::shared_ptr(discoveryMgr_)); + softbusSession->RegisterSessionCallback(std::shared_ptr(discoveryMgr)); int ret = softbusSession->SendData(sessionId, message); EXPECT_EQ(ret, DM_FAILED); } diff --git a/test/unittest/mock/device_auth.h b/test/unittest/mock/device_auth.h index 68e7cba41e08f83cc745f6d9c1812ae402f76999..b55bf24f54efae9dc639053c580239758db2709d 100644 --- a/test/unittest/mock/device_auth.h +++ b/test/unittest/mock/device_auth.h @@ -16,8 +16,7 @@ #ifndef DEVICE_AUTH_H #define DEVICE_AUTH_H -#include -#include +#include #if defined(__LINUX__) || defined(_UNIX) #define DEVICE_AUTH_API_PUBLIC __attribute__ ((visibility("default"))) @@ -69,37 +68,37 @@ #define FIELD_BLE_CHALLENGE "bleChallenge" #define FIELD_OS_ACCOUNT_ID "osAccountId" -typedef enum { +using OsAccountEnum = enum _OsAccountEnum : int32_t { DEFAULT_OS_ACCOUNT = 0, INVALID_OS_ACCOUNT = -1, ANY_OS_ACCOUNT = -2, -} OsAccountEnum; +}; -typedef enum { +using GroupType = enum _GroupType : int32_t { ALL_GROUP = 0, IDENTICAL_ACCOUNT_GROUP = 1, PEER_TO_PEER_GROUP = 256, COMPATIBLE_GROUP = 512, ACROSS_ACCOUNT_AUTHORIZE_GROUP = 1282 -} GroupType; +}; -typedef enum { +using GroupOperationCode = enum _GroupOperationCode : int32_t { GROUP_CREATE = 0, GROUP_DISBAND = 1, MEMBER_INVITE = 2, MEMBER_JOIN = 3, MEMBER_DELETE = 4, ACCOUNT_BIND = 5 -} GroupOperationCode; +}; -typedef enum { +using GroupAuthForm = enum _GroupAuthForm : int32_t { AUTH_FORM_INVALID_TYPE = -1, AUTH_FORM_ACCOUNT_UNRELATED = 0, AUTH_FORM_IDENTICAL_ACCOUNT = 1, AUTH_FORM_ACROSS_ACCOUNT = 2, -} GroupAuthForm; +}; -typedef enum { +using CredentialCode = enum _CredentialCode : int32_t { IMPORT_SELF_CREDENTIAL = 0, DELETE_SELF_CREDENTIAL = 1, QUERY_SELF_CREDENTIAL_INFO = 2, @@ -107,27 +106,27 @@ typedef enum { DELETE_TRUSTED_CREDENTIALS = 4, QUERY_TRUSTED_CREDENTIALS = 5, REQUEST_SIGNATURE = 6, -} CredentialCode; +}; -typedef enum { +using UserType = enum _UserType : int32_t { DEVICE_TYPE_ACCESSORY = 0, DEVICE_TYPE_CONTROLLER = 1, DEVICE_TYPE_PROXY = 2 -} UserType; +}; -typedef enum { +using ExpireTime = enum _ExpireTime : int32_t { EXPIRE_TIME_INDEFINITE = -1, EXPIRE_TIME_MIN = 1, EXPIRE_TIME_MAX = 90, -} ExpireTime; +}; -typedef enum { +using RequestResponse = enum _RequestResponse : int32_t { REQUEST_REJECTED = 0x80000005, REQUEST_ACCEPTED = 0x80000006, REQUEST_WAITING = 0x80000007 -} RequestResponse; +}; -typedef struct { +using DataChangeListener = struct _DataChangeListener { void (*onGroupCreated)(const char *groupInfo); void (*onGroupDeleted)(const char *groupInfo); void (*onDeviceBound)(const char *peerUdid, const char *groupInfo); @@ -135,17 +134,17 @@ typedef struct { void (*onDeviceNotTrusted)(const char *peerUdid); void (*onLastGroupDeleted)(const char *peerUdid, int groupType); void (*onTrustedDeviceNumChanged)(int curTrustedDeviceNum); -} DataChangeListener; +}; -typedef struct { +using DeviceAuthCallback = struct _DeviceAuthCallback { bool (*onTransmit)(int64_t requestId, const uint8_t *data, uint32_t dataLen); void (*onSessionKeyReturned)(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen); void (*onFinish)(int64_t requestId, int operationCode, const char *returnData); void (*onError)(int64_t requestId, int operationCode, int errorCode, const char *errorReturn); char *(*onRequest)(int64_t requestId, int operationCode, const char *reqParams); -} DeviceAuthCallback; +}; -typedef struct { +using GroupAuthManager = struct _GroupAuthManager { int32_t (*processData)(int64_t authReqId, const uint8_t *data, uint32_t dataLen, const DeviceAuthCallback *gaCallback); int32_t (*queryTrustedDeviceNum)(void); @@ -155,9 +154,9 @@ typedef struct { int32_t (*authDevice)(int32_t osAccountId, int64_t authReqId, const char *authParams, const DeviceAuthCallback *gaCallback); void (*informDeviceDisconnection)(const char *udid); -} GroupAuthManager; +}; -typedef struct { +using DeviceGroupManager = struct _DeviceGroupManager { int32_t (*regCallback)(const char *appId, const DeviceAuthCallback *callback); int32_t (*unRegCallback)(const char *appId); int32_t (*regDataChangeListener)(const char *appId, const DataChangeListener *listener); @@ -202,7 +201,7 @@ typedef struct { char **returnDevInfoVec, uint32_t *deviceNum); bool (*isDeviceInGroup)(int32_t osAccountId, const char *appId, const char *groupId, const char *deviceId); void (*destroyInfo)(char **returnInfo); -} DeviceGroupManager; +}; #ifdef __cplusplus extern "C" { diff --git a/test/unittest/mock/mock_ipc_client.h b/test/unittest/mock/mock_ipc_client.h new file mode 100644 index 0000000000000000000000000000000000000000..35c2de529f13c7e0fcee12d2662b40f755164775 --- /dev/null +++ b/test/unittest/mock/mock_ipc_client.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 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. + */ + +#ifndef OHOS_MOCK_IPC_CLIENTMANAGER_H +#define OHOS_MOCK_IPC_CLIENTMANAGER_H + +#include +#include + +#include "ipc_client.h" + +namespace OHOS { +namespace DistributedHardware { +class MockIpcClient : public IpcClient { +public: + MOCK_METHOD1(Init, int32_t(const std::string &pkgName)); + MOCK_METHOD1(UnInit, int32_t(const std::string &pkgName)); + MOCK_METHOD3(SendRequest, int32_t(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp)); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_MOCK_IPC_CLIENTMANAGER_H diff --git a/test/unittest/mock/mock_ipc_client_manager.h b/test/unittest/mock/mock_ipc_client_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..46ed4705e0ed6b4636e4fe0a4676078d9227a9ad --- /dev/null +++ b/test/unittest/mock/mock_ipc_client_manager.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 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. + */ + +#ifndef OHOS_MOCK_IPC_CLIENTMANAGER_H +#define OHOS_MOCK_IPC_CLIENTMANAGER_H + +#include +#include + +#include "ipc_client_server_proxy.h" + +namespace OHOS { +namespace DistributedHardware { +class MockIpcClientManager : public IpcClientServerProxy { +public: + explicit MockIpcClientManager (const sptr &impl): IpcClientServerProxy(impl) {}; + MOCK_METHOD3(SendCmd, int32_t(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp)); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_MOCK_IPC_CLIENTMANAGER_H diff --git a/utils/src/dm_anonymous.cpp b/utils/src/dm_anonymous.cpp index 907c9f20880f77eabe86f5524587e762e7bbb7f7..8fbe5b580d178b9d4a7de9cd33a5b5a29086f30c 100644 --- a/utils/src/dm_anonymous.cpp +++ b/utils/src/dm_anonymous.cpp @@ -24,7 +24,7 @@ std::string GetAnonyString(const std::string &value) const int32_t INT32_MIN_ID_LENGTH = 3; std::string tmpStr("******"); - int32_t strLen = value.length(); + size_t strLen = value.length(); if (strLen < INT32_MIN_ID_LENGTH) { return tmpStr; } @@ -46,7 +46,7 @@ std::string GetAnonyString(const std::string &value) std::string GetAnonyInt32(const int32_t value) { std::string tempString = std::to_string(value); - int32_t length = tempString.length(); + size_t length = tempString.length(); if (length == 0x01) { tempString[0] = '*'; return tempString;