diff --git a/ohos.build b/ohos.build index 3f3e8af2b..098ff8f66 100755 --- a/ohos.build +++ b/ohos.build @@ -62,6 +62,22 @@ "header_base": "//foundation/communication/wifi/services/wifi_standard/wifi_hal/" } } + ], + "test_list": [ + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan:unittest", + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta:unittest", + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test:unittest", + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/:unittest", + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat:unittest", + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service:unittest", + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client:unittest", + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest:unittest", + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test:unittest", + "//foundation/communication/wifi/tests/wifi_standard/ipc_framework/cRPC/unittest:unittest", + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/common/unittest:unittest", + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/unittest:unittest", + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest:unittest", + "//foundation/communication/wifi/tests/wifi_standard/wifi_hal/unittest:unittest" ] }, diff --git a/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp b/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp index 2af68af6d..f4b09a25c 100644 --- a/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp +++ b/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp @@ -976,90 +976,90 @@ bool WifiSettings::GetWhetherToAllowNetworkSwitchover() return mWifiConfig.whetherToAllowNetworkSwitchover; } -int WifiSettings::SetscoretacticsScoreSlope(const int &score) +int WifiSettings::SetScoretacticsScoreSlope(const int &score) { mWifiConfig.scoretacticsScoreSlope = score; return 0; } -int WifiSettings::GetscoretacticsScoreSlope() +int WifiSettings::GetScoretacticsScoreSlope() { return mWifiConfig.scoretacticsScoreSlope; } -int WifiSettings::SetscoretacticsInitScore(const int &score) +int WifiSettings::SetScoretacticsInitScore(const int &score) { mWifiConfig.scoretacticsInitScore = score; return 0; } -int WifiSettings::GetscoretacticsInitScore() +int WifiSettings::GetScoretacticsInitScore() { return mWifiConfig.scoretacticsInitScore; } -int WifiSettings::SetscoretacticsSameBssidScore(const int &score) +int WifiSettings::SetScoretacticsSameBssidScore(const int &score) { mWifiConfig.scoretacticsSameBssidScore = score; return 0; } -int WifiSettings::GetscoretacticsSameBssidScore() +int WifiSettings::GetScoretacticsSameBssidScore() { return mWifiConfig.scoretacticsSameBssidScore; } -int WifiSettings::SetscoretacticsSameNetworkScore(const int &score) +int WifiSettings::SetScoretacticsSameNetworkScore(const int &score) { mWifiConfig.scoretacticsSameNetworkScore = score; return 0; } -int WifiSettings::GetscoretacticsSameNetworkScore() +int WifiSettings::GetScoretacticsSameNetworkScore() { return mWifiConfig.scoretacticsSameNetworkScore; } -int WifiSettings::SetscoretacticsFrequency5GHzScore(const int &score) +int WifiSettings::SetScoretacticsFrequency5GHzScore(const int &score) { mWifiConfig.scoretacticsFrequency5GHzScore = score; return 0; } -int WifiSettings::GetscoretacticsFrequency5GHzScore() +int WifiSettings::GetScoretacticsFrequency5GHzScore() { return mWifiConfig.scoretacticsFrequency5GHzScore; } -int WifiSettings::SetscoretacticsLastSelectionScore(const int &score) +int WifiSettings::SetScoretacticsLastSelectionScore(const int &score) { mWifiConfig.scoretacticsLastSelectionScore = score; return 0; } -int WifiSettings::GetscoretacticsLastSelectionScore() +int WifiSettings::GetScoretacticsLastSelectionScore() { return mWifiConfig.scoretacticsLastSelectionScore; } -int WifiSettings::SetscoretacticsSecurityScore(const int &score) +int WifiSettings::SetScoretacticsSecurityScore(const int &score) { mWifiConfig.scoretacticsSecurityScore = score; return 0; } -int WifiSettings::GetscoretacticsSecurityScore() +int WifiSettings::GetScoretacticsSecurityScore() { return mWifiConfig.scoretacticsSecurityScore; } -int WifiSettings::SetsavedDeviceAppraisalPriority(const int &priority) +int WifiSettings::SetSavedDeviceAppraisalPriority(const int &priority) { mWifiConfig.savedDeviceAppraisalPriority = priority; return 0; } -int WifiSettings::GetsavedDeviceAppraisalPriority() +int WifiSettings::GetSavedDeviceAppraisalPriority() { return mWifiConfig.savedDeviceAppraisalPriority; } diff --git a/services/wifi_standard/wifi_framework/common/config/wifi_settings.h b/services/wifi_standard/wifi_framework/common/config/wifi_settings.h index ba7a65ff9..54a5015b3 100644 --- a/services/wifi_standard/wifi_framework/common/config/wifi_settings.h +++ b/services/wifi_standard/wifi_framework/common/config/wifi_settings.h @@ -739,14 +739,14 @@ public: * @param score - score * @return int - 0 success */ - int SetscoretacticsScoreSlope(const int &score); + int SetScoretacticsScoreSlope(const int &score); /** * @Description Get the policy score slope * * @return int - score */ - int GetscoretacticsScoreSlope(); + int GetScoretacticsScoreSlope(); /** * @Description Initial score of the set strategy @@ -754,14 +754,14 @@ public: * @param score - score * @return int - 0 success */ - int SetscoretacticsInitScore(const int &score); + int SetScoretacticsInitScore(const int &score); /** * @Description Obtain the initial score of the tactic * * @return int - score */ - int GetscoretacticsInitScore(); + int GetScoretacticsInitScore(); /** * @Description Set the scoring policy to the same BSSID score @@ -769,14 +769,14 @@ public: * @param score - score * @return int - 0 success */ - int SetscoretacticsSameBssidScore(const int &score); + int SetScoretacticsSameBssidScore(const int &score); /** * @Description Get the scoring policy to the same BSSID score * * @return int - score */ - int GetscoretacticsSameBssidScore(); + int GetScoretacticsSameBssidScore(); /** * @Description Set the score policy for the same network @@ -784,14 +784,14 @@ public: * @param score - score * @return int - 0 success */ - int SetscoretacticsSameNetworkScore(const int &score); + int SetScoretacticsSameNetworkScore(const int &score); /** * @Description Get the score policy for the same network * * @return int - score */ - int GetscoretacticsSameNetworkScore(); + int GetScoretacticsSameNetworkScore(); /** * @Description Set the 5 GHz score of the policy frequency @@ -799,14 +799,14 @@ public: * @param score - score * @return int - 0 success */ - int SetscoretacticsFrequency5GHzScore(const int &score); + int SetScoretacticsFrequency5GHzScore(const int &score); /** * @Description Get the 5 GHz score of the policy frequency * * @return int - score */ - int GetscoretacticsFrequency5GHzScore(); + int GetScoretacticsFrequency5GHzScore(); /** * @Description Set the score policy. last select score @@ -814,14 +814,14 @@ public: * @param score - score * @return int - 0 success */ - int SetscoretacticsLastSelectionScore(const int &score); + int SetScoretacticsLastSelectionScore(const int &score); /** * @Description Get the score policy, last select score * * @return int - score */ - int GetscoretacticsLastSelectionScore(); + int GetScoretacticsLastSelectionScore(); /** * @Description Setting the Score Policy Security Score @@ -829,14 +829,14 @@ public: * @param score - score * @return int - 0 success */ - int SetscoretacticsSecurityScore(const int &score); + int SetScoretacticsSecurityScore(const int &score); /** * @Description Get the Score Policy Security Score * * @return int - priority */ - int GetscoretacticsSecurityScore(); + int GetScoretacticsSecurityScore(); /** * @Description Set the saved device appraisal priority @@ -844,14 +844,14 @@ public: * @param priority - priority * @return int - 0 success */ - int SetsavedDeviceAppraisalPriority(const int &priority); + int SetSavedDeviceAppraisalPriority(const int &priority); /** * @Description Get the saved device appraisal priority * * @return int - priority */ - int GetsavedDeviceAppraisalPriority(); + int GetSavedDeviceAppraisalPriority(); /** * @Description Judge the Module need preloaded or not diff --git a/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp b/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp index 8869f1e79..2b87117ce 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp +++ b/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp @@ -24,7 +24,7 @@ namespace OHOS { namespace Wifi { const int MAX_IPV4_PREFIX_LENGTH = 32; const int MAX_IPV4_STRING_LENGTH = 64; -const Ipv4Address Ipv4Address::INVALID_INET_ADDRESS = Ipv4Address::Create("255.255.255.255", MAX_IPV4_PREFIX_LENGTH); +const Ipv4Address Ipv4Address::INVALID_INET_ADDRESS("255.255.255.255", MAX_IPV4_PREFIX_LENGTH); bool Ipv4Address::IsValidIPv4(const std::string &ipv4) { struct in_addr ipv4Addr = {INADDR_ANY}; diff --git a/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp b/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp index fca408e81..3fadae955 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp +++ b/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp @@ -32,8 +32,8 @@ constexpr int MAX_HEX = 16; constexpr int BUFFER_SIZE = 32; constexpr int HALF_PREFIX_LENGTH = 64; -const Ipv6Address Ipv6Address::INVALID_INET6_ADDRESS = - Ipv6Address::Create(std::string("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), MAX_IPV6_PREFIX_LENGTH); +const Ipv6Address Ipv6Address::INVALID_INET6_ADDRESS(std::string("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), + MAX_IPV6_PREFIX_LENGTH); bool Ipv6Address::IsValidIPv6(const std::string &ipv6) { @@ -313,22 +313,6 @@ std::string Ipv6Address::HexToBin(const std::string &strHex) return addrBin; } -int Ipv6Address::CalcPrefixLen(struct in6_addr &mask) -{ - int i = 0; - int len = 0; - int u = 0; - for (i = 0; i < MAX_IPV6_PREFIX_LENGTH / CHAR_BIT; i++) { - u = mask.s6_addr[i]; - if (ffs(u) > 0) { - len += CHAR_BIT + 1 - ffs(u); - } else { - break; - } - } - return len; -} - std::string Ipv6Address::MacToEui64addr(MacAddress &mac) { struct sockaddr macSockaddr = mac.GetMacAddressWifiSockaddr(); diff --git a/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.h b/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.h index 55ce365ed..add175d1d 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.h +++ b/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.h @@ -209,13 +209,6 @@ private: * @return string of EUI-64 address */ static std::string MacToEui64addr(MacAddress &mac); - /** - * @Description Calculate the prefix length of the mask. - * - * @param mask - in6_addr structure of the mask [input] - * @return int - prefix length - */ - static int CalcPrefixLen(struct in6_addr &mask); }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp b/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp index 19edc077f..c527ee2b0 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp +++ b/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp @@ -29,7 +29,7 @@ constexpr int HEX_BASE = 16; namespace OHOS { namespace Wifi { -const MacAddress MacAddress::INVALID_MAC_ADDRESS = MacAddress::Create(INVALID_MAC); +const MacAddress MacAddress::INVALID_MAC_ADDRESS = MacAddress(INVALID_MAC); bool MacAddress::IsValidMac(const std::string &mac) { diff --git a/services/wifi_standard/wifi_framework/common/net_helper/network_interface.h b/services/wifi_standard/wifi_framework/common/net_helper/network_interface.h index 9563a4fc6..8f55eb11c 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/network_interface.h +++ b/services/wifi_standard/wifi_framework/common/net_helper/network_interface.h @@ -35,31 +35,6 @@ namespace NetworkInterface { */ bool IsValidInterfaceName(const std::string &interfaceName); -/** - * @Description Check whether the interface is UP. - * - * @param interfaceName - Network Interface Name - * @return true - yes false - no - */ -bool IsInterfaceUp(const std::string &interfaceName); - -/** - * @Description Set the interface UP. - * - * @param interfaceName - Network Interface Name - * @param state - 1 up / 0 down. - * @return true - yes false - no - */ -bool SetInterfaceState(const std::string &interfaceName, int state); - -/** - * @Description Enable ipv6. - * - * @param interfaceName - Network Interface Name[in] - * @return true - yes false - no - */ -bool EnableIpv6(const std::string& interfaceName); - /** * @Description Print all members in an object * diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/BUILD.gn b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/BUILD.gn index c6cddb576..111d95e4e 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/BUILD.gn +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/BUILD.gn @@ -19,6 +19,7 @@ ohos_executable("dhcp_server") { "src/address_utils.c", "src/common_util.c", "src/dhcp_address_pool.c", + "src/dhcp_argument.c", "src/dhcp_binding.c", "src/dhcp_config.c", "src/dhcp_dhcpd.c", diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_argument.h b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_argument.h new file mode 100644 index 000000000..5741ea5af --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_argument.h @@ -0,0 +1,69 @@ +/* + * 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_DHCP_ARGUMENT_H +#define OHOS_DHCP_ARGUMENT_H + +#include "hash_table.h" +#include "dhcp_define.h" +#ifdef __cplusplus +extern "C" { +#endif + +#define ARGUMENT_NAME_SIZE 32 +#define ARGUMENT_VALUE_SIZE 256 +#define INIT_ARGS_SIZE 4 + +#define NO_ARG 0 +#define REQUIRED_ARG 1 +#define OPTIONAL_ARG 2 + +#define USAGE_DESC_MAX_LENGTH 32 + +typedef struct DhcpUsage DhcpUsage; +struct DhcpUsage { + struct option *opt; + const char *params; + const char *desc; + const char *example; + int required; + int (*dealOption)(const char *, const char *); +}; + + +typedef struct ArgumentInfo ArgumentInfo; +struct ArgumentInfo { + char name[ARGUMENT_NAME_SIZE]; + char value[ARGUMENT_VALUE_SIZE]; +}; + +int InitArguments(void); +int HasArgument(const char *argument); +ArgumentInfo *GetArgument(const char *name); +int PutArgument(const char *argument, const char *val); + +int ParseArguments(int argc, char *argv[]); + +void FreeArguments(void); + +void ShowHelp(int argc); + +void PrintRequiredArguments(void); + +#ifdef __cplusplus +} +#endif + +#endif // OHOS_DHCP_ARGUMENT_H \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_argument.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_argument.c new file mode 100644 index 000000000..a692d6fd8 --- /dev/null +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_argument.c @@ -0,0 +1,318 @@ +/* + * 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 "dhcp_argument.h" +#include "dhcp_option.h" +#include "dhcp_config.h" +#include "address_utils.h" +#include "securec.h" +#include "dhcp_logger.h" +#include +#undef LOG_TAG +#define LOG_TAG "DhcpArgument" + +static HashTable g_argumentsTable; + +static int PutIpArgument(const char *argument, const char *val) +{ + if (!ParseIpAddr(val)) { + LOGE("%s format error.", argument); + return RET_FAILED; + } + return PutArgument(argument, val); +} + +static int PutPoolArgument(const char *argument, const char *val) +{ + if (!val) { + return 0; + } + if (strchr(val, ',') == NULL) { + LOGE("too few pool option arguments."); + return RET_FAILED; + } + return PutArgument(argument, val); +} + +static int ShowVersion(const char *argument, const char *val) +{ + if (argument && PutArgument(argument, val) != RET_SUCCESS) { + LOGD("failed to put argument 'version'."); + } + printf("version:%s\n", DHCPD_VERSION); + return RET_BREAK; +} + +static int DefaultArgument(const char *argument, const char *val) +{ + LOGD("Input argument is: [%s], value is [%s]", (argument == NULL) ? "" : argument, + (val == NULL) ? "" : val); + return RET_SUCCESS; +} + +const char *optionString = "i:c:d:g:s:n:P:S:Bp:o:lb:rvhD"; + +static struct option longOptions[] = { + {"ifname", REQUIRED_ARG, 0, 'i'}, + {"conf", REQUIRED_ARG, 0, 'c'}, + {"dns", REQUIRED_ARG, 0, 'd'}, + {"gateway", REQUIRED_ARG, 0, 'g'}, + {"server", REQUIRED_ARG, 0, 's'}, + {"netmask", REQUIRED_ARG, 0, 'n'}, + {"pool", REQUIRED_ARG, 0, 'P'}, + {"lease", REQUIRED_ARG, 0, 0}, + {"renewal", REQUIRED_ARG, 0, 0}, + {"rebinding", REQUIRED_ARG, 0, 0}, + {"version", NO_ARG, 0, 'v'}, + {"help", NO_ARG, 0, 'h'}, + {0, 0, 0, 0}, +}; + +static DhcpUsage usages[] = { + {&longOptions[NUM_ZERO], "", "network interface name.", "--ifname eth0", 1, PutArgument}, + {&longOptions[NUM_ONE], "", "configure file name.", "--conf /etc/conf/dhcp_server.conf", 0, PutArgument}, + {&longOptions[NUM_TWO], "[,dns2][,dns3][...]", "domain name server IP address list.", "", 0, PutArgument}, + {&longOptions[NUM_THREE], "", "gateway option.", "", 0, PutIpArgument}, + {&longOptions[NUM_FOUR], "", "server identifier.", "", 1, PutIpArgument}, + {&longOptions[NUM_FIVE], "", "default subnet mask.", "", 1, PutIpArgument}, + {&longOptions[NUM_SIX], ",", "pool address range.", "", 0, + PutPoolArgument}, + {&longOptions[NUM_SEVEN], "", "set lease time value, the value is in units of seconds.", "", 0, + PutArgument}, + {&longOptions[NUM_EIGHT], "", "set renewal time value, the value is in units of seconds.", "", 0, + PutArgument}, + {&longOptions[NUM_NINE], "", "set rebinding time value, the value is in units of seconds.", "", 0, + PutArgument}, + {&longOptions[NUM_TEN], "", "show version information.", "", 0, ShowVersion}, + {&longOptions[NUM_ELEVEN], "", "show help information.", "", 0, DefaultArgument}, + {0, "", "", ""}, +}; + +int HasArgument(const char *argument) +{ + char name[ARGUMENT_NAME_SIZE] = {'\0'}; + if (!argument) { + return 0; + } + size_t ssize = strlen(argument); + if (ssize > ARGUMENT_NAME_SIZE) { + ssize = ARGUMENT_NAME_SIZE; + } + if (memcpy_s(name, ARGUMENT_NAME_SIZE, argument, ssize) != EOK) { + LOGE("failed to set argument name."); + return 0; + } + if (ContainsKey(&g_argumentsTable, (uintptr_t)name)) { + return 1; + } + return 0; +} + +static void ShowUsage(const DhcpUsage *usage) +{ + if (!usage) { + return; + } + if (usage->opt->val) { + printf("-%c,--%s ", usage->opt->val, usage->opt->name); + } else { + printf(" --%s ", usage->opt->name); + } + if (usage->params[0] == '\0') { + printf("\t%s\n", usage->desc); + } else { + int plen = strlen(usage->params) + strlen(usage->params); + if (plen < USAGE_DESC_MAX_LENGTH) { + printf("\t\t%s\t\t%s\n", usage->params, usage->desc); + } else { + printf("\t\t%s\n", usage->params); + printf("\t\t\t%s\n\n", usage->desc); + } + } +} + +void PrintRequiredArguments(void) +{ + size_t argc = sizeof(usages) / sizeof(DhcpUsage); + printf("required parameters:"); + int idx = 0; + for (size_t i = 0; i < argc; i++) { + DhcpUsage usage = usages[i]; + if (!usage.opt) { + break; + } + if (usage.required) { + if (idx == 0) { + printf("\"%s\"", usage.opt->name); + } else { + printf(", \"%s\"", usage.opt->name); + } + idx++; + } + } + printf(".\n\n"); + printf("Usage: dhcp_server [options] \n"); + printf("e.g: dhcp_server -i eth0 -c /data/dhcp/dhcp_server.conf \n"); + printf(" dhcp_server --help \n\n"); +} + +static void PrintUsage(void) +{ + printf("Usage: dhcp_server [options] \n\n"); + + size_t argc = sizeof(usages) / sizeof(DhcpUsage); + for (size_t i = 0; i < argc; i++) { + DhcpUsage usage = usages[i]; + if (!usage.opt) { + break; + } + ShowUsage(&usage); + } + printf("\n"); +} + +void ShowHelp(int argc) +{ + if (argc == NUM_TWO) { + PrintUsage(); + return; + } +} + +int InitArguments(void) +{ + if (CreateHashTable(&g_argumentsTable, ARGUMENT_NAME_SIZE, sizeof(ArgumentInfo), INIT_ARGS_SIZE) != HASH_SUCCESS) { + return RET_FAILED; + } + return RET_SUCCESS; +} + +ArgumentInfo *GetArgument(const char *name) +{ + char argName[ARGUMENT_NAME_SIZE] = {'\0'}; + size_t ssize = strlen(name); + if (ssize > ARGUMENT_NAME_SIZE) { + ssize = ARGUMENT_NAME_SIZE; + } + if (memcpy_s(argName, ARGUMENT_NAME_SIZE, name, ssize) != EOK) { + LOGE("failed to set argument name."); + return NULL; + } + if (ContainsKey(&g_argumentsTable, (uintptr_t)argName)) { + ArgumentInfo *arg = (ArgumentInfo *)At(&g_argumentsTable, (uintptr_t)argName); + return arg; + } + return NULL; +} + +int PutArgument(const char *argument, const char *val) +{ + if (!argument) { + return RET_FAILED; + } + if (!val) { + return RET_FAILED; + } + + if (HasArgument(argument)) { + return RET_FAILED; + } + + ArgumentInfo arg; + size_t ssize = strlen(argument); + if (ssize >= ARGUMENT_NAME_SIZE) { + ssize = ARGUMENT_NAME_SIZE -1; + } + size_t vlen = strlen(val); + if (memset_s(arg.name, ARGUMENT_NAME_SIZE, '\0', ARGUMENT_NAME_SIZE) != EOK) { + LOGE("failed to reset argument name."); + return RET_ERROR; + } + if (memcpy_s(arg.name, ARGUMENT_NAME_SIZE, argument, ssize) != EOK) { + LOGE("failed to set argument name."); + return RET_ERROR; + } + if (vlen < 0) { + return RET_ERROR; + } + if (vlen >= ARGUMENT_VALUE_SIZE) { + LOGE("value string too long."); + return RET_ERROR; + } + if (memset_s(arg.value, ARGUMENT_VALUE_SIZE, '\0', ARGUMENT_NAME_SIZE) != EOK) { + LOGE("failed to reset argument value."); + return RET_ERROR; + } + if (memcpy_s(arg.value, ARGUMENT_VALUE_SIZE, val, vlen) != EOK) { + LOGE("failed to set argument value."); + return RET_ERROR; + } + int ret = Insert(&g_argumentsTable, (uintptr_t)arg.name, (uintptr_t)&arg); + if (ret == HASH_INSERTED) { + return RET_SUCCESS; + } + return RET_FAILED; +} + +static int findIndex(int c) +{ + int size = sizeof(longOptions) / sizeof(longOptions[0]); + for (int i = 0; i < size; ++i) { + if (longOptions[i].val == c) { + return i; + } + } + return -1; +} + +int ParseArguments(int argc, char *argv[]) +{ + int ret; + opterr = 0; + size_t optsc = sizeof(usages) / sizeof(DhcpUsage); + int index = -1; + int rst = RET_SUCCESS; + while ((ret = getopt_long(argc, argv, optionString, longOptions, &index)) != -1) { + if (ret == '?') { + LOGW("unknown input arguments! ret = ?"); + index = -1; + continue; + } + if (index < 0) { + index = findIndex(ret); + } + if (index < 0 || index >= (int)optsc) { + LOGD("unknown input arguments! ret = %c, index = %d", ret, index); + index = -1; + continue; + } + DhcpUsage *usage = &usages[index]; + rst = usage->dealOption(usage->opt->name, optarg); + if (rst != RET_SUCCESS) { + break; + } + index = -1; + } + + return rst; +} + +void FreeArguments(void) +{ + if (!Initialized(&g_argumentsTable)) { + return; + } + DestroyHashTable(&g_argumentsTable); +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c index 6b16a4882..12fb966de 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c @@ -34,40 +34,17 @@ #include "address_utils.h" #include "securec.h" #include "dhcp_config.h" +#include "dhcp_argument.h" #undef LOG_TAG #define LOG_TAG "DhcpServerMain" -#define NO_ARG 0 -#define REQUIRED_ARG 1 -#define OPTIONAL_ARG 2 - -#define ARGUMENT_NAME_SIZE 32 -#define ARGUMENT_VALUE_SIZE 256 -#define INIT_ARGS_SIZE 4 -#define USAGE_DESC_MAX_LENGTH 32 #define DEFAUTL_NET_MASK "255.255.255.0" -static HashTable g_argumentsTable; static DhcpConfig g_dhcpConfig; static PDhcpServerContext g_dhcpServer = 0; -typedef struct DhcpUsage DhcpUsage; -struct DhcpUsage { - struct option *opt; - const char *params; - const char *desc; - const char *example; - int required; - int (*dealOption)(const char *, const char *); -}; - -typedef struct ArgumentInfo ArgumentInfo; -struct ArgumentInfo { - char name[ARGUMENT_NAME_SIZE]; - char value[ARGUMENT_VALUE_SIZE]; -}; enum SignalEvent { EXIT = 0, @@ -75,22 +52,6 @@ enum SignalEvent { RESTART, }; -static struct option longOptions[] = { - {"ifname", REQUIRED_ARG, 0, 'i'}, - {"conf", REQUIRED_ARG, 0, 'c'}, - {"dns", REQUIRED_ARG, 0, 'd'}, - {"gateway", REQUIRED_ARG, 0, 'g'}, - {"server", REQUIRED_ARG, 0, 's'}, - {"netmask", REQUIRED_ARG, 0, 'n'}, - {"pool", REQUIRED_ARG, 0, 'P'}, - {"lease", REQUIRED_ARG, 0, 0}, - {"renewal", REQUIRED_ARG, 0, 0}, - {"rebinding", REQUIRED_ARG, 0, 0}, - {"version", NO_ARG, 0, 'v'}, - {"help", NO_ARG, 0, 'h'}, - {0, 0, 0, 0}, -}; - typedef struct DhcpOptionField { const char *field; int code; @@ -101,283 +62,6 @@ typedef struct DhcpOptionField { } DhcpOptionField; -static int InitArguments(void) -{ - if (CreateHashTable(&g_argumentsTable, ARGUMENT_NAME_SIZE, sizeof(ArgumentInfo), INIT_ARGS_SIZE) != HASH_SUCCESS) { - return RET_FAILED; - } - return RET_SUCCESS; -} - -static void FreeArguments(void) -{ - if (!Initialized(&g_argumentsTable)) { - return; - } - DestroyHashTable(&g_argumentsTable); -} - -static int HasArgument(const char *argument) -{ - char name[ARGUMENT_NAME_SIZE] = {'\0', 0}; - if (!argument) { - return 0; - } - size_t ssize = strlen(argument); - if (ssize > ARGUMENT_NAME_SIZE) { - ssize = ARGUMENT_NAME_SIZE; - } - if (memcpy_s(name, ARGUMENT_NAME_SIZE, argument, ssize) != EOK) { - LOGE("failed to set argument name."); - return 0; - } - if (ContainsKey(&g_argumentsTable, (uintptr_t)name)) { - return 1; - } - return 0; -} - -static ArgumentInfo *GetArgument(const char *name) -{ - char argName[ARGUMENT_NAME_SIZE] = {'\0'}; - size_t ssize = strlen(name); - if (ssize > ARGUMENT_NAME_SIZE) { - ssize = ARGUMENT_NAME_SIZE; - } - if (memcpy_s(argName, ARGUMENT_NAME_SIZE, name, ssize) != EOK) { - LOGE("failed to set argument name."); - return NULL; - } - if (ContainsKey(&g_argumentsTable, (uintptr_t)argName)) { - ArgumentInfo *arg = (ArgumentInfo *)At(&g_argumentsTable, (uintptr_t)argName); - return arg; - } - return NULL; -} - -static int DefaultArgument(const char *argument, const char *val) -{ - LOGD("Input argument is: [%s], value is [%s]", (argument == NULL) ? "" : argument, - (val == NULL) ? "" : val); - return RET_SUCCESS; -} - -static int PutArgument(const char *argument, const char *val) -{ - if (!argument) { - return 0; - } - if (!val) { - return RET_FAILED; - } - - if (HasArgument(argument)) { - return RET_FAILED; - } - - ArgumentInfo arg; - size_t ssize = strlen(argument); - if (ssize >= ARGUMENT_NAME_SIZE) { - ssize = ARGUMENT_NAME_SIZE -1; - } - size_t vlen = strlen(val); - if (memset_s(arg.name, ARGUMENT_NAME_SIZE, '\0', ARGUMENT_NAME_SIZE) != EOK) { - LOGE("failed to reset argument name."); - return RET_ERROR; - } - if (memcpy_s(arg.name, ARGUMENT_NAME_SIZE, argument, ssize) != EOK) { - LOGE("failed to set argument name."); - return RET_ERROR; - } - if (vlen < 0) { - return RET_ERROR; - } - if (vlen >= ARGUMENT_VALUE_SIZE) { - LOGE("value string too long."); - return RET_ERROR; - } - if (memset_s(arg.value, ARGUMENT_VALUE_SIZE, '\0', ARGUMENT_NAME_SIZE) != EOK) { - LOGE("failed to reset argument value."); - return RET_ERROR; - } - if (memcpy_s(arg.value, ARGUMENT_VALUE_SIZE, val, vlen) != EOK) { - LOGE("failed to set argument value."); - return RET_ERROR; - } - int ret = Insert(&g_argumentsTable, (uintptr_t)arg.name, (uintptr_t)&arg); - if (ret == HASH_INSERTED) { - return RET_SUCCESS; - } - return RET_FAILED; -} - -static int PutIpArgument(const char *argument, const char *val) -{ - if (!ParseIpAddr(val)) { - LOGE("%s format error.", argument); - return RET_FAILED; - } - return PutArgument(argument, val); -} - -static int PutPoolArgument(const char *argument, const char *val) -{ - if (!val) { - return 0; - } - if (strchr(val, ',') == NULL) { - LOGE("too few pool option arguments."); - return RET_FAILED; - } - return PutArgument(argument, val); -} - -static int ShowVersion(const char *argument, const char *val) -{ - if (argument && PutArgument(argument, val) != RET_SUCCESS) { - LOGD("failed to put argument 'version'."); - } - printf("version:%s\n", DHCPD_VERSION); - return RET_BREAK; -} - -const char *optionString = "i:c:d:g:s:n:P:S:Bp:o:lb:rvhD"; -static DhcpUsage usages[] = { - {&longOptions[NUM_ZERO], "", "network interface name.", "--ifname eth0", 1, PutArgument}, - {&longOptions[NUM_ONE], "", "configure file name.", "--conf /etc/conf/dhcp_server.conf", 0, PutArgument}, - {&longOptions[NUM_TWO], "[,dns2][,dns3][...]", "domain name server IP address list.", "", 0, PutArgument}, - {&longOptions[NUM_THREE], "", "gateway option.", "", 0, PutIpArgument}, - {&longOptions[NUM_FOUR], "", "server identifier.", "", 1, PutIpArgument}, - {&longOptions[NUM_FIVE], "", "default subnet mask.", "", 1, PutIpArgument}, - {&longOptions[NUM_SIX], ",", "pool address range.", "", 0, - PutPoolArgument}, - {&longOptions[NUM_SEVEN], "", "set lease time value, the value is in units of seconds.", "", 0, - PutArgument}, - {&longOptions[NUM_EIGHT], "", "set renewal time value, the value is in units of seconds.", "", 0, - PutArgument}, - {&longOptions[NUM_NINE], "", "set rebinding time value, the value is in units of seconds.", "", 0, - PutArgument}, - {&longOptions[NUM_TEN], "", "show version information.", "", 0, ShowVersion}, - {&longOptions[NUM_ELEVEN], "", "show help information.", "", 0, DefaultArgument}, - {0, "", "", ""}, -}; - -int findIndex(int c) -{ - int size = sizeof(longOptions) / sizeof(longOptions[0]); - for (int i = 0; i < size; ++i) { - if (longOptions[i].val == c) { - return i; - } - } - return -1; -} - -void ShowUsage(const DhcpUsage *usage) -{ - if (!usage) { - return; - } - if (usage->opt->val) { - printf("-%c,--%s ", usage->opt->val, usage->opt->name); - } else { - printf(" --%s ", usage->opt->name); - } - if (usage->params[0] == '\0') { - printf("\t%s\n", usage->desc); - } else { - int plen = strlen(usage->params) + strlen(usage->params); - if (plen < USAGE_DESC_MAX_LENGTH) { - printf("\t\t%s\t\t%s\n", usage->params, usage->desc); - } else { - printf("\t\t%s\n", usage->params); - printf("\t\t\t%s\n\n", usage->desc); - } - } -} - -void PrintRequiredArguments(void) -{ - size_t argc = sizeof(usages) / sizeof(DhcpUsage); - printf("required parameters:"); - int idx = 0; - for (size_t i = 0; i < argc; i++) { - DhcpUsage usage = usages[i]; - if (!usage.opt) { - break; - } - if (usage.required) { - if (idx == 0) { - printf("\"%s\"", usage.opt->name); - } else { - printf(", \"%s\"", usage.opt->name); - } - idx++; - } - } - printf(".\n\n"); - printf("Usage: dhcp_server [options] \n"); - printf("e.g: dhcp_server -i eth0 -c /data/dhcp/dhcp_server.conf \n"); - printf(" dhcp_server --help \n\n"); -} - -void PrintUsage(void) -{ - printf("Usage: dhcp_server [options] \n\n"); - - size_t argc = sizeof(usages) / sizeof(DhcpUsage); - for (size_t i = 0; i < argc; i++) { - DhcpUsage usage = usages[i]; - if (!usage.opt) { - break; - } - ShowUsage(&usage); - } - printf("\n"); -} - -void ShowHelp(int argc) -{ - if (argc == NUM_TWO) { - PrintUsage(); - return; - } -} - -int ParseArguments(int argc, char *argv[]) -{ - int ret; - opterr = 0; - size_t optsc = sizeof(usages) / sizeof(DhcpUsage); - int index = -1; - int rst = RET_SUCCESS; - - while ((ret = getopt_long(argc, argv, optionString, longOptions, &index)) != -1) { - if (ret == '?') { - LOGW("unknown input arguments! ret = ?"); - index = -1; - continue; - } - if (index < 0) { - index = findIndex(ret); - } - if (index < 0 || index >= (int)optsc) { - LOGD("unknown input arguments! ret = %c, index = %d", ret, index); - index = -1; - continue; - } - DhcpUsage *usage = &usages[index]; - rst = usage->dealOption(usage->opt->name, optarg); - if (rst != RET_SUCCESS) { - break; - } - index = -1; - } - - - return rst; -} - void LoadLocalConfig(DhcpAddressPool *pool) { LOGD("loading local configure ..."); @@ -691,6 +375,7 @@ void FreeSeverResources(void) FreeLocalConfig(); FreeServerContex(g_dhcpServer); } + int main(int argc, char *argv[]) { if (argc == 1) { diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_option.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_option.c index 0ef32a0b6..1bfb4674a 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_option.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_option.c @@ -30,10 +30,6 @@ PDhcpOptionNode CreateOptionNode(PDhcpOption opt) LOGE("input parameter is null."); return NULL; } - if ((int)opt->length > DHCP_OPTION_SIZE) { - LOGE("input parameter length error. length:%hhu", opt->length); - return NULL; - } DhcpOptionNode *pNode = (DhcpOptionNode *)calloc(1, sizeof(DhcpOptionNode)); if (pNode == NULL) { LOGE("failed to create dhcp option node!"); diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c index a91adfffb..8493a5a2f 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c +++ b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c @@ -306,7 +306,6 @@ void InitReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply reply->packet.htype = ETHERNET; reply->packet.hlen = OPT_MAC_ADDR_LENGTH; reply->packet.secs = 0; - reply->packet.secs = 0; reply->packet.ciaddr = 0; if (memset_s(reply->packet.sname, sizeof(reply->packet.sname), '\0', sizeof(reply->packet.sname)) != EOK) { LOGE("failed to reset message packet[sname]!"); @@ -721,8 +720,8 @@ static int FillReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo LOGE("failed to reset message packet[chaddr]!"); return RET_ERROR; } - if (memcpy_s(reply->packet.chaddr, received->packet.hlen, - received->packet.chaddr, received->packet.hlen) != EOK) { + if (memcpy_s(reply->packet.chaddr, sizeof(reply->packet.chaddr), + received->packet.chaddr, sizeof(received->packet.chaddr)) != EOK) { LOGE("failed to copy message packet[chaddr]!"); return RET_ERROR; } @@ -1456,14 +1455,13 @@ static int ParseMessageOptions(PDhcpMsgInfo msg) return RET_FAILED; } current = (DhcpOption *)(((uint8_t *)current) + MAGIC_COOKIE_LENGTH); - int pos = (int)(((uint8_t *)current) + MAGIC_COOKIE_LENGTH); - + uint8_t *pos = (((uint8_t *)current) + MAGIC_COOKIE_LENGTH); + uint8_t *maxPos = (((uint8_t *)current) + (DHCP_OPTION_SIZE - MAGIC_COOKIE_LENGTH - OPT_HEADER_LENGTH -1)); int optTotal = 0; - int optionLength = msg->length - DHCP_MSG_HEADER_SIZE; while (current < end && current->code != END_OPTION) { - pos += OPT_HEADER_LENGTH + current->length; - if (pos >= optionLength) { - LOGD("out of option max size."); + pos += (OPT_HEADER_LENGTH + current->length); + if (pos >= maxPos) { + LOGD("out of option max pos."); return RET_FAILED; } if (PushBackOption(&msg->options, current) != RET_SUCCESS) { @@ -1472,7 +1470,6 @@ static int ParseMessageOptions(PDhcpMsgInfo msg) current = (DhcpOption *)(((uint8_t *)current) + OPT_HEADER_LENGTH + current->length); optTotal++; } - if (current < end && current->code == END_OPTION) { LOGD("option list size:%zu xid:%u", msg->options.size, msg->packet.xid); return RET_SUCCESS; @@ -1526,7 +1523,7 @@ static int ParseReplyOptions(PDhcpMsgInfo reply) return ret; } PDhcpOptionNode pNode = reply->options.first->next; - DhcpOption endOpt = {END_OPTION, 0}; + DhcpOption endOpt = {END_OPTION, 0, {0}}; PushBackOption(&reply->options, &endOpt); int replyOptsLength = 0; uint8_t *current = reply->packet.options, olen = MAGIC_COOKIE_LENGTH; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.h b/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.h index 4429a41bd..69e901898 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.h @@ -73,14 +73,14 @@ public: * @param timerName - Timer Name.[in] * @param interval - Timer duration, in milliseconds.[in] */ - void StartTimer(int timerName, int64_t interval); + virtual void StartTimer(int timerName, int64_t interval); /** * @Description : Stop the timer. * * @param timerName - Timer Name.[in] */ - void StopTimer(int timerName); + virtual void StopTimer(int timerName); /** * @Description : Construct internal messages. @@ -151,7 +151,7 @@ public: * * @param msgName - Message name.[in] */ - void SendMessage(int msgName); + virtual void SendMessage(int msgName); /** * @Description : Constructs internal messages and places the messages @@ -160,7 +160,7 @@ public: * @param msgName - Message name.[in] * @param param1 - Message parameter.[in] */ - void SendMessage(int msgName, int param1); + virtual void SendMessage(int msgName, int param1); /** * @Description : Constructs internal messages and places the messages @@ -170,21 +170,22 @@ public: * @param param1 - Message parameter.[in] * @param param2 - Message parameter.[in] */ - void SendMessage(int msgName, int param1, int param2); + virtual void SendMessage(int msgName, int param1, int param2); /** * @Description : Puts messages into the message queue of the state machine. * * @param msg - Message to be sent.[in] */ - void SendMessage(InternalMessage *msg); + virtual void SendMessage(InternalMessage *msg); + /** * @Description : Puts messages into the message queue of the state machine. * * @param msgName - Message Name.[in] * @param messageObj - User-defined data */ - void SendMessage(int msgName, const std::any &messageObj); + virtual void SendMessage(int msgName, const std::any &messageObj); /** * @Description : Puts messages into the message queue of the state machine. @@ -194,7 +195,7 @@ public: * @param param2 - Message parameters.[in] * @param messageObj - User-defined data */ - void SendMessage(int msgName, int param1, int param2, const std::any &messageObj); + virtual void SendMessage(int msgName, int param1, int param2, const std::any &messageObj); /** * @Description Constructs internal messages and places them in the diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp index 0bd247b3d..e1dfabd96 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp @@ -1135,7 +1135,10 @@ WifiErrorNo WifiIdlClient::ReqP2pListNetworks(std::map &m if (ret != WIFI_IDL_OPT_OK) { return ret; } - for (int i = 0; i < infoList.infoNum; i++) { + if (infoList.infos == nullptr) { + return ret; + } + for (int i = 0; i < infoList.infoNum; ++i) { WifiP2pGroupInfo groupInfo; groupInfo.SetNetworkId(infoList.infos[i].id); groupInfo.SetGroupName(infoList.infos[i].ssid); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp index c14d11c4d..9a99fa226 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp @@ -74,7 +74,7 @@ bool ApStationsManager::EnableAllBlockList() const bool ret = true; for (std::vector::iterator iter = results.begin(); iter != results.end(); iter++) { if (WifiApHalInterface::GetInstance().AddBlockByMac(iter->bssid) != WifiErrorNo::WIFI_IDL_OPT_OK) { - WIFI_LOGE("error:Failed to add block mac:%s.", iter->bssid.c_str()); + WIFI_LOGE("error:Failed to add block bssid is:%{private}s.", iter->bssid.c_str()); ret = false; } } @@ -83,7 +83,6 @@ bool ApStationsManager::EnableAllBlockList() const void ApStationsManager::StationLeave(const std::string &mac) const { - WIFI_LOGD("StationLeave mac:%s.", mac.c_str()); StationInfo staInfo; std::vector results; if (WifiSettings::GetInstance().GetStationList(results)) { @@ -110,10 +109,6 @@ void ApStationsManager::StationLeave(const std::string &mac) const void ApStationsManager::StationJoin(const StationInfo &staInfo) const { StationInfo staInfoTemp = staInfo; - WIFI_LOGD("enter ApStationManager::StationJoin Name:%s mac:%s ip:%s.", - staInfo.deviceName.c_str(), - staInfo.bssid.c_str(), - staInfo.ipAddr.c_str()); std::vector results; if (WifiSettings::GetInstance().GetStationList(results)) { WIFI_LOGE("failed to GetStationList."); @@ -147,16 +142,12 @@ bool ApStationsManager::DisConnectStation(const StationInfo &staInfo) const std::string mac = staInfo.bssid; int ret = static_cast(WifiApHalInterface::GetInstance().DisconnectStaByMac(mac)); if (ret != WifiErrorNo::WIFI_IDL_OPT_OK) { - WIFI_LOGE("failed to DisConnectStation staInfo bssid:%s, address:%s, name:%s.", + WIFI_LOGE("failed to DisConnectStation staInfo bssid:%{private}s, address:%{private}s, name:%{private}s.", staInfo.bssid.c_str(), staInfo.ipAddr.c_str(), staInfo.deviceName.c_str()); return false; } - WIFI_LOGD("DisConnectStation staInfo bssid:%s, address:%s, name:%s ok.", - staInfo.bssid.c_str(), - staInfo.ipAddr.c_str(), - staInfo.deviceName.c_str()); return true; } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h index 0d4bbff2a..39cb9f0e7 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h @@ -23,6 +23,7 @@ namespace OHOS { namespace Wifi { +#define FRIEND_GTEST(test_typename) friend class test_typename##Test static const int MIN_SYSTEM_SCAN_INTERVAL = 20; static const int MAX_SYSTEM_SCAN_INTERVAL = 160; static const int MAX_SCAN_CONFIG_STORE_INDEX = 10000; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h index 0f5331dbb..06da44c94 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h @@ -22,6 +22,7 @@ namespace OHOS { namespace Wifi { class ScanInterface : public IScanService { + FRIEND_GTEST(ScanInterface); public: ScanInterface(); ~ScanInterface(); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.h index 9ee323db6..373caec33 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.h @@ -25,6 +25,7 @@ namespace OHOS { namespace Wifi { class ScanMonitor { + FRIEND_GTEST(ScanMonitor); public: ScanMonitor(); ~ScanMonitor(); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp index 5e1e69638..d1eb516b3 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp @@ -15,6 +15,8 @@ #include #include "scan_service.h" #include "wifi_logger.h" +#include "wifi_settings.h" +#include "wifi_sta_hal_interface.h" DEFINE_WIFILOG_SCAN_LABEL("ScanService"); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h index 608aa2e29..04c2d04ab 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h @@ -20,9 +20,7 @@ #include #include "iscan_service_callbacks.h" #include "wifi_log.h" -#include "wifi_settings.h" #include "wifi_error_no.h" -#include "wifi_sta_hal_interface.h" #include "define.h" #include "scan_common.h" #include "scan_monitor.h" @@ -51,35 +49,36 @@ const int SYS_FOREGROUND_SCAN = 2; const int SYS_BACKGROUND_SCAN = 3; class ScanService { + FRIEND_GTEST(ScanService); public: ScanService(); - ~ScanService(); + virtual ~ScanService(); /** * @Description Initializing the Scan Service. * * @param scanSerivceCallbacks Callback function registered with the wifiManager[in]. * @return success: true, failed: false */ - bool InitScanService(const IScanSerivceCallbacks &scanSerivceCallbacks); + virtual bool InitScanService(const IScanSerivceCallbacks &scanSerivceCallbacks); /** * @Description Stopping the Scan Service. * */ - void UnInitScanService(); + virtual void UnInitScanService(); /** * @Description Start a complete Wi-Fi scan. * * @param externFlag - Externally initiated scanning[in] * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - ErrCode Scan(bool externFlag); + virtual ErrCode Scan(bool externFlag); /** * @Description Start Wi-Fi scanning based on specified parameters. * * @param params - Scan specified parameters[in] * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - ErrCode ScanWithParam(const WifiScanParams ¶ms); + virtual ErrCode ScanWithParam(const WifiScanParams ¶ms); /** * @Description Starting a Single Scan. * @@ -107,13 +106,13 @@ public: * * @param scanAtOnce - Whether to start scanning immediately[in] */ - void SystemScanProcess(bool scanAtOnce); + virtual void SystemScanProcess(bool scanAtOnce); /** * @Description Status reported by the state machine. * * @param scanStatusReport - Structure of the reported status.[in] */ - void HandleScanStatusReport(ScanStatusReport &scanStatusReport); + virtual void HandleScanStatusReport(ScanStatusReport &scanStatusReport); /** * @Description Internal event reporting and processing. * @@ -125,38 +124,38 @@ public: * * @param screenOn - screen state[in] */ - void HandleScreenStatusChanged(bool screenOn); + virtual void HandleScreenStatusChanged(bool screenOn); /** * @Description STA status change processing * * @param state - STA state[in] */ - void HandleStaStatusChanged(int status); + virtual void HandleStaStatusChanged(int status); /** * @Description custom scene status change processing * * @param customScene custom scene[in] * @param customSceneStatus custom scene status[in] */ - void HandleCustomStatusChanged(int customScene, int customSceneStatus); + virtual void HandleCustomStatusChanged(int customScene, int customSceneStatus); /** * @Description Sets the type of the app to be operated. * * @param appMode - Type of the app to be scanned. */ - void SetOperateAppMode(int appMode); + virtual void SetOperateAppMode(int appMode); /** * @Description Query and save the scan control policy. * */ - void GetScanControlInfo(); + virtual void GetScanControlInfo(); /** * @Description Obtain the scenario set by the customer through changeState. * * @param scene - Scenario value corresponding to the scenario */ - void SetCustomScene(int scene, time_t currentTime); + virtual void SetCustomScene(int scene, time_t currentTime); /** * @Description When scanning control changes, the count data needs to be cleared. * @@ -166,7 +165,7 @@ public: * @Description When scanning control changes, the count data needs to be cleared. * */ - void SetStaCurrentTime(); + virtual void SetStaCurrentTime(); private: using ScanConfigMap = std::map; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.cpp index 3fa4fb0f2..776a5b779 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.cpp @@ -1528,7 +1528,7 @@ bool ScanStateMachine::GetScanInfos(std::vector &scanInfos) WIFI_LOGI("Begin: QueryScanInfos."); if (WifiStaHalInterface::GetInstance().QueryScanInfos(scanInfos) != WIFI_IDL_OPT_OK) { - WIFI_LOGE("WifiStaHalInterface::GetInstance().QueryScanResults failed."); + WIFI_LOGE("WifiStaHalInterface::GetInstance().GetScanInfos failed."); return false; } WIFI_LOGI("End: QueryScanInfos."); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.h index 2e514d582..9c12e00d7 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.h @@ -41,6 +41,7 @@ const int SCAN_24GHZ_BAND = 1; const int SCAN_5GHZ_BAND = 2; class ScanStateMachine : public StateMachine { + FRIEND_GTEST(ScanStateMachine); public: ScanStateMachine(); ~ScanStateMachine(); @@ -60,6 +61,7 @@ public: bool EnrollScanStatusListener(ScanStatusReportHandler handler); class InitState : public State { + FRIEND_GTEST(ScanStateMachine); public: /** * @Description Initial state of the scanning state machine diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp index 1cae43236..b640c4c83 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp @@ -14,6 +14,8 @@ */ #include "sta_auto_connect_service.h" #include "wifi_logger.h" +#include "wifi_sta_hal_interface.h" +#include "wifi_settings.h" DEFINE_WIFILOG_LABEL("StaAutoConnectService"); @@ -52,7 +54,7 @@ ErrCode StaAutoConnectService::InitAutoConnectService() return WIFI_OPT_FAILED; } - int savedPriority = WifiSettings::GetInstance().GetsavedDeviceAppraisalPriority(); + int savedPriority = WifiSettings::GetInstance().GetSavedDeviceAppraisalPriority(); if (RegisterDeviceAppraisal(pSavedDeviceAppraisal, savedPriority)) { WIFI_LOGI("RegisterSavedDeviceAppraisal succeeded.\n"); } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h index 2f65d02e7..b4936c6b4 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h @@ -21,7 +21,6 @@ #include #include #include "wifi_log.h" -#include "wifi_settings.h" #include "wifi_errcode.h" #include "wifi_msg.h" #include "log_helper.h" @@ -46,20 +45,21 @@ static const int MIN_RSSI_VALUE_5G = -80; static const int TIME_FROM_LAST_SELECTION = 60; static const int MIN_ROAM_RSSI_DIFF = 6; class StaAutoConnectService { + FRIEND_GTEST(StaAutoConnectService); public: explicit StaAutoConnectService(StaStateMachine *staStateMachine); - ~StaAutoConnectService(); + virtual ~StaAutoConnectService(); /** * @Description Initialize StaAutoConnectService * */ - ErrCode InitAutoConnectService(); + virtual ErrCode InitAutoConnectService(); /** * @Description Processing scan results * * @param scanInfos - The list of scanning results(in) */ - void OnScanInfosReadyHandler(const std::vector &scanInfos); + virtual void OnScanInfosReadyHandler(const std::vector &scanInfos); /** * @Description Whether tracking should enable or disable scanned BSSIDs * @@ -68,7 +68,7 @@ public: * @param reason - Enable/Disable reason code.(in) * @Return success: true. failed: false. */ - bool EnableOrDisableBssid(std::string bssid, bool enable, int reason); + virtual bool EnableOrDisableBssid(std::string bssid, bool enable, int reason); /** * @Description Select the best device from the range. * @@ -78,7 +78,7 @@ public: * @param electedDevice - Elected Device(out) * @Return success : WIFI_OPT_SUCCESS failed : WIFI_OPT_FAILED */ - ErrCode AutoSelectDevice(WifiDeviceConfig &electedDevice, const std::vector &scanInfos, + virtual ErrCode AutoSelectDevice(WifiDeviceConfig &electedDevice, const std::vector &scanInfos, std::vector &blockedBssids, WifiLinkedInfo &info); /** * @Description Registering the Device Appraisal @@ -87,7 +87,7 @@ public: * @param priority - Value between 0 and (SCORER_MIN_PRIORITY – 1)(in) * @Return success : true failed : false */ - bool RegisterDeviceAppraisal(StaDeviceAppraisal *appraisal, int priority); + virtual bool RegisterDeviceAppraisal(StaDeviceAppraisal *appraisal, int priority); private: StaStateMachine *pStaStateMachine; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h index 93a74daae..4ecebb028 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h @@ -20,6 +20,8 @@ namespace OHOS { namespace Wifi { +#define FRIEND_GTEST(test_typename) friend class test_typename##Test + #define WIFI_SVR_CMD_STA_ENABLE_WIFI 0x2001 #define WIFI_SVR_CMD_STA_DISABLE_WIFI 0x2002 #define WIFI_SVR_CMD_STA_START_SUPPLICANT 0x2003 @@ -59,15 +61,20 @@ namespace Wifi { #define WIFI_SVR_CMD_STA_CONFIG_MULTIPLE_PBC_DETECTED 0x3015 #define WIFI_SVR_CMD_STA_WPA_STATE_CHANGE_EVENT 0x3016 #define WIFI_SVR_CMD_STA_WPA_PASSWD_WRONG_EVENT 0x3017 + +#define WPA_BLOCK_LIST_CLEAR_EVENT 0x4001 + #define BSSID_LEN 17 #define KEY_LEN 128 #define SSID_LEN 30 #define VALUE_LIMIT_MIN_RSSI (-100) #define VALUE_LIMIT_MAX_RSSI (-55) -#define WPA_BLOCK_LIST_CLEAR_EVENT 0x4001 + #define NETWORK_SELECTED_BY_THE_USER 1 #define NETWORK_SELECTED_FOR_CONNECTION_MANAGEMENT 0 +const int NETWORK_24G_BAND = 1; +const int NETWORK_5G_BAND = 2; #define BAND_2_G 1 #define BAND_5_G 2 diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_device_appraisal.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_device_appraisal.h index ec80ced8e..71a59c0c7 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_device_appraisal.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_device_appraisal.h @@ -20,6 +20,7 @@ #include "wifi_msg.h" #include "log_helper.h" #include "sta_define.h" +#include "wifi_internal_msg.h" namespace OHOS { namespace Wifi { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp index 744a46afc..d4a64ec59 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ #include "sta_interface.h" -#include "wifi_log.h" +#include "sta_service.h" #include "wifi_logger.h" DEFINE_WIFILOG_LABEL("StaInterface"); @@ -44,10 +44,12 @@ extern "C" void Destroy(IStaService *pservice) ErrCode StaInterface::EnableWifi() { WIFI_LOGD("Enter StaInterface::EnableWifi.\n"); - pStaService = new (std::nothrow) StaService(); - if (pStaService == nullptr) { - WIFI_LOGE("New StaService failed.\n"); - return WIFI_OPT_FAILED; + if(pStaService == nullptr) { + pStaService = new (std::nothrow) StaService(); + if (pStaService == nullptr) { + WIFI_LOGE("New StaService failed.\n"); + return WIFI_OPT_FAILED; + } } if (pStaService->InitStaService(staCallback) != WIFI_OPT_SUCCESS) { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h index 77bfd1147..df405d4f1 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h @@ -16,12 +16,15 @@ #ifndef OHOS_WIFI_STA_INTERFACE_H #define OHOS_WIFI_STA_INTERFACE_H +#include "sta_define.h" #include "ista_service.h" -#include "sta_service.h" +#include "wifi_errcode.h" namespace OHOS { namespace Wifi { +class StaService; class StaInterface : public IStaService { + FRIEND_GTEST(StaInterface); public: StaInterface(); virtual ~StaInterface() override; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.cpp index eb4b97eb5..368f7fb0c 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.cpp @@ -16,6 +16,7 @@ #include "wifi_idl_define.h" #include "sta_define.h" #include "wifi_logger.h" +#include "wifi_supplicant_hal_interface.h" #include "wifi_sta_hal_interface.h" DEFINE_WIFILOG_LABEL("StaMonitor"); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.h index 81fb0fbf2..1c717141a 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.h @@ -15,13 +15,12 @@ #ifndef OHOS_STA_MONITOR_H #define OHOS_STA_MONITOR_H -#include "wifi_supplicant_hal_interface.h" -#include "wifi_sta_hal_interface.h" #include "sta_state_machine.h" namespace OHOS { namespace Wifi { class StaMonitor { + FRIEND_GTEST(StaMonitor); public: /** * @Description : Construct a new Sta Monitor object. @@ -33,7 +32,7 @@ public: * @Description Destroy the Sta Monitor object. * */ - ~StaMonitor(); + virtual ~StaMonitor(); /** * @Description : Initialize the sta monitor. diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.h index 7bc323a95..577e15be4 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.h @@ -33,26 +33,27 @@ namespace OHOS { namespace Wifi { class StaNetworkCheck { + FRIEND_GTEST(StaNetworkCheck); public: explicit StaNetworkCheck(NetStateHandler handle); - ~StaNetworkCheck(); + virtual ~StaNetworkCheck(); /** * @Description : Start NetCheck thread * * @Return success : WIFI_OPT_SUCCESS failed : WIFI_OPT_FAILED */ - ErrCode InitNetCheckThread(); + virtual ErrCode InitNetCheckThread(); /** * @Description : wake up the DHCP processing thread. * * @param ipType - Type of IP to be obtained [in] */ - void SignalNetCheckThread(); + virtual void SignalNetCheckThread(); /** * @Description : stop the NetCheck processing thread. * */ - void StopNetCheckThread(); + virtual void StopNetCheckThread(); private: std::thread *pDealNetCheckThread; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp index 2dc005d6c..3b2db99a4 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp @@ -14,6 +14,7 @@ */ #include "sta_saved_device_appraisal.h" #include "wifi_logger.h" +#include "wifi_settings.h" DEFINE_WIFILOG_LABEL("StaSavedDeviceAppraisal"); @@ -23,13 +24,13 @@ DEFINE_WIFILOG_LABEL("StaSavedDeviceAppraisal"); namespace OHOS { namespace Wifi { StaSavedDeviceAppraisal::StaSavedDeviceAppraisal(bool supportFmRoamingFlag) - : signalScorePerLevel(WifiSettings::GetInstance().GetscoretacticsScoreSlope()), - signalBaseScore(WifiSettings::GetInstance().GetscoretacticsInitScore()), - sameBssidScore(WifiSettings::GetInstance().GetscoretacticsSameBssidScore()), - sameDeviceScore(WifiSettings::GetInstance().GetscoretacticsSameNetworkScore()), - frequency5GHzScore(WifiSettings::GetInstance().GetscoretacticsFrequency5GHzScore()), - userSelectedDeviceScore(WifiSettings::GetInstance().GetscoretacticsLastSelectionScore()), - safetyDeviceScore(WifiSettings::GetInstance().GetscoretacticsSecurityScore()), + : signalScorePerLevel(WifiSettings::GetInstance().GetScoretacticsScoreSlope()), + signalBaseScore(WifiSettings::GetInstance().GetScoretacticsInitScore()), + sameBssidScore(WifiSettings::GetInstance().GetScoretacticsSameBssidScore()), + sameDeviceScore(WifiSettings::GetInstance().GetScoretacticsSameNetworkScore()), + frequency5GHzScore(WifiSettings::GetInstance().GetScoretacticsFrequency5GHzScore()), + userSelectedDeviceScore(WifiSettings::GetInstance().GetScoretacticsLastSelectionScore()), + safetyDeviceScore(WifiSettings::GetInstance().GetScoretacticsSecurityScore()), firmwareRoamFlag(supportFmRoamingFlag) {} StaSavedDeviceAppraisal::~StaSavedDeviceAppraisal() diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h index 456eae924..6e0cb1a62 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h @@ -17,12 +17,13 @@ #define OHOS_WIFI_SAVEDDEVICEAPPRAISAL_H #include "wifi_log.h" -#include "wifi_settings.h" #include "sta_device_appraisal.h" +#include "wifi_internal_msg.h" namespace OHOS { namespace Wifi { class StaSavedDeviceAppraisal : public StaDeviceAppraisal { + FRIEND_GTEST(StaSavedDeviceAppraisal); public: explicit StaSavedDeviceAppraisal(bool supportFmRoamingFlag); ~StaSavedDeviceAppraisal() override; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp index f9299f737..ed43bac48 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp @@ -16,6 +16,9 @@ #include "wifi_logger.h" #include "sta_define.h" #include "sta_service_callback.h" +#include "wifi_sta_hal_interface.h" +#include "wifi_supplicant_hal_interface.h" +#include "wifi_settings.h" DEFINE_WIFILOG_LABEL("StaService"); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h index 2009c7382..c7bc5d209 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h @@ -24,15 +24,16 @@ namespace OHOS { namespace Wifi { class StaService { + FRIEND_GTEST(StaService); public: StaService(); - ~StaService(); + virtual ~StaService(); /** * @Description Initialize StaService module. * * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode InitStaService(const StaServiceCallback &callbacks); + virtual ErrCode InitStaService(const StaServiceCallback &callbacks); /** * @Description Enable wifi * @@ -41,7 +42,7 @@ public: result immediately. * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode EnableWifi() const; + virtual ErrCode EnableWifi() const; /** * @Description Disable wifi * @@ -50,7 +51,7 @@ public: result immediately. * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode DisableWifi() const; + virtual ErrCode DisableWifi() const; /** * @Description Connect to a new network * @@ -60,7 +61,7 @@ public: result immediately. * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode ConnectToDevice(const WifiDeviceConfig &config) const; + virtual ErrCode ConnectToDevice(const WifiDeviceConfig &config) const; /** * @Description Connecting to a specified network. * @@ -70,7 +71,7 @@ public: result immediately. * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode ConnectToNetwork(int networkId) const; + virtual ErrCode ConnectToNetwork(int networkId) const; /** * @Description Disconnect to the network * @@ -79,13 +80,13 @@ public: result immediately. * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode Disconnect() const; + virtual ErrCode Disconnect() const; /** * @Description ReAssociate network * * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode ReAssociate() const; + virtual ErrCode ReAssociate() const; /** * @Description Update a network to config @@ -93,27 +94,27 @@ public: * @param config -The Network info(in) * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - int AddDeviceConfig(const WifiDeviceConfig &config) const; + virtual int AddDeviceConfig(const WifiDeviceConfig &config) const; /** * @Description Update a network to config. * * @param config -The Network info(in) * @Return success: networkId fail: -1 */ - int UpdateDeviceConfig(const WifiDeviceConfig &config) const; + virtual int UpdateDeviceConfig(const WifiDeviceConfig &config) const; /** * @Description Remove network config. * * @param networkId -The NetworkId is going to be removed.(in) * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode RemoveDevice(int networkId) const; + virtual ErrCode RemoveDevice(int networkId) const; /** * @Description Remove all network configs. * * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode RemoveAllDevice() const; + virtual ErrCode RemoveAllDevice() const; /** * @Description Enable WI-FI device Configuration. * @@ -121,14 +122,14 @@ public: * @param networkId - if set true, disable other device config (in) * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode EnableDeviceConfig(int networkId, bool attemptEnable) const; + virtual ErrCode EnableDeviceConfig(int networkId, bool attemptEnable) const; /** * @Description Disable WI-FI device Configuration. * * @param networkId - device Configuration's network id * @return ErrCode - success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode DisableDeviceConfig(int networkId) const; + virtual ErrCode DisableDeviceConfig(int networkId) const; /** * @Description Start WPS Connection * @@ -137,7 +138,7 @@ public: result immediately. * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode StartWps(const WpsConfig &config) const; + virtual ErrCode StartWps(const WpsConfig &config) const; /** * @Description Close WPS Connection * @@ -146,13 +147,13 @@ public: result immediately. * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode CancelWps() const; + virtual ErrCode CancelWps() const; /** * @Description Set country code * * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode SetCountryCode(const std::string &countryCode) const; + virtual ErrCode SetCountryCode(const std::string &countryCode) const; /** * @Description ConnectivityManager process scan results. * @@ -161,13 +162,13 @@ public: result immediately. * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - ErrCode AutoConnectService(const std::vector &scanInfos); + virtual ErrCode AutoConnectService(const std::vector &scanInfos); /** * @Description Register sta callback function * * @param callbacks - Callback function pointer storage structure */ - void RegisterStaServiceCallback(const StaServiceCallback &callbacks) const; + virtual void RegisterStaServiceCallback(const StaServiceCallback &callbacks) const; private: diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp index 36444d8e5..b984f65db 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp @@ -14,13 +14,19 @@ */ #include "sta_state_machine.h" #include -#include -#include "http_request.h" #include "log_helper.h" -#include "if_config.h" #include "sta_monitor.h" #include "wifi_logger.h" #include "wifi_sta_hal_interface.h" +#include "wifi_settings.h" +#include "if_config.h" +#include "wifi_supplicant_hal_interface.h" + +#ifndef OHOS_WIFI_STA_TEST +#include "dhcp_service.h" +#else +#include "mock_dhcp_service.h" +#endif DEFINE_WIFILOG_LABEL("StaStateMachine"); #define PBC_ANY_BSSID "any" diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h index 263c3ca6a..4eaf829a4 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h @@ -21,16 +21,14 @@ #include #include "wifi_internal_msg.h" #include "wifi_log.h" -#include "wifi_settings.h" #include "wifi_errcode.h" #include "wifi_msg.h" #include "state_machine.h" -#include "wifi_sta_hal_interface.h" #include "sta_network_speed.h" #include "sta_network_check.h" -#include "dhcp_service.h" #include "i_dhcp_result_notify.h" #include "sta_service_callback.h" +#include "i_dhcp_service.h" #include "sta_define.h" namespace OHOS { @@ -64,6 +62,7 @@ static const int MAX_LEVEL = 4; const std::string WPA_BSSID_ANY = "any"; class StaStateMachine : public StateMachine { + FRIEND_GTEST(StaStateMachine); public: StaStateMachine(); ~StaStateMachine(); diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c b/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c index 9eeeb5232..bbe5158f8 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c +++ b/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c @@ -192,6 +192,10 @@ static void DealServiceDiscRespEvent(char *buf) free(info.tlvs); return; } + if (info.tlvs != NULL) { + free(info.tlvs); + info.tlvs = NULL; + } info.tlvs = (char *)calloc(len, sizeof(char)); if (info.tlvs == NULL || strncpy_s(info.tlvs, len, token, len - 1) != EOK) { free(info.tlvs); @@ -439,6 +443,10 @@ static void DealP2pServDiscReqEvent(char *buf) free(info.tlvs); return; } + if (info.tlvs != NULL) { + free(info.tlvs); + info.tlvs = NULL; + } info.tlvs = (char *)calloc(len, sizeof(char)); if (info.tlvs == NULL || strncpy_s(info.tlvs, len, token, len - 1) != EOK) { free(info.tlvs); diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/BUILD.gn b/tests/wifi_standard/ipc_framework/cRPC/unittest/BUILD.gn new file mode 100644 index 000000000..696728043 --- /dev/null +++ b/tests/wifi_standard/ipc_framework/cRPC/unittest/BUILD.gn @@ -0,0 +1,65 @@ +# 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. + +import("//build/test.gni") +SUBSYSTEM_DIR = "//foundation/communication/wifi" +module_output_path = "wifi_standard/crpc_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/tests/wifi_standard/ipc_framework/cRPC/unittest", + ] +} + +ohos_unittest("crpc_unittest") { + module_out_path = module_output_path + sources = [ + "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/src/context.c", + "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/src/hash_table.c", + "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/src/net.c", + "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/src/serial.c", + "context_test.cpp", + "hash_table_test.cpp", + "net_test.cpp", + "rpc_test_main.cpp", + "serial_test.cpp", + ] + + include_dirs = [ + "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + + deps = [ "//utils/native/base:utils" ] + + ldflags = [ + "-fPIC", + "-Wl,--wrap=write", + "-Wl,--wrap=read", + "--coverage", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + configs = [ ":module_private_config" ] + + part_name = "wifi_standard" + subsystem_name = "communication" + testonly = true +} + +group("unittest") { + testonly = true + deps = [ ":crpc_unittest" ] +} diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/context_test.cpp b/tests/wifi_standard/ipc_framework/cRPC/unittest/context_test.cpp new file mode 100644 index 000000000..d7be628ed --- /dev/null +++ b/tests/wifi_standard/ipc_framework/cRPC/unittest/context_test.cpp @@ -0,0 +1,200 @@ +/* + * 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 "context_test.h" +#include "securec.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +static int CalculateLeft(const Context *ctx) +{ + int left = + (ctx->wBegin <= ctx->wEnd) ? (ctx->wCapacity - 1 - ctx->wEnd + ctx->wBegin) : (ctx->wBegin - ctx->wEnd - 1); + return left; +} + +HWTEST_F(ContextTest, CreateContextTest, TestSize.Level1) +{ + ctx = CreateContext(100); + ASSERT_TRUE(ctx != nullptr); + ASSERT_TRUE(ctx->wCapacity == CONTEXT_BUFFER_MIN_SIZE); + ReleaseContext(ctx); + ctx = CreateContext(102400000); + ASSERT_TRUE(ctx != nullptr); + ASSERT_TRUE(ctx->wCapacity == CONTEXT_BUFFER_MAX_SIZE); +} + +HWTEST_F(ContextTest, AppendCacheTest, TestSize.Level1) +{ + ctx = CreateContext(1024); + ASSERT_TRUE(ctx != nullptr) << "capacity :" << ctx->wCapacity; + /* capacity size 1024 */ + ASSERT_TRUE(ctx->wCapacity == 1024); + ASSERT_TRUE(ctx->wEnd == 0); + + /* calculate left capacity test */ + ctx->wBegin = ctx->wEnd = 0; + ASSERT_TRUE(CalculateLeft(ctx) == 1023); /* capacity, use a space define endpos */ + ctx->wEnd = 1023; /* pos [0,1023], max pos 1023 */ + ASSERT_TRUE(CalculateLeft(ctx) == 0); + ctx->wBegin = 1023; + ctx->wEnd = 0; + ASSERT_TRUE(CalculateLeft(ctx) == 1022); /* wEnd max num can be 1022, so from 0 - 1021 = 1022 */ + ctx->wEnd = 1022; + ASSERT_TRUE(CalculateLeft(ctx) == 0); + ctx->wBegin = ctx->wEnd = 0; + + char buff[] = "123456789 123456789 123456789 12"; + for (unsigned i = 0; i < 1024 / 32 - 1; ++i) { + ContextAppendWrite(ctx, buff, strlen(buff)); + ASSERT_TRUE(ctx->wEnd == (i + 1) * 32); + } + ASSERT_TRUE(strcpy_s(buff, sizeof(buff), "123456789 123456789 123456789 1") == EOK); + ContextAppendWrite(ctx, buff, strlen(buff)); + ASSERT_TRUE(ctx->wEnd == 1023); + ASSERT_TRUE(CalculateLeft(ctx) == 0); + ctx->wBegin = 1023; + ASSERT_TRUE(strcpy_s(buff, sizeof(buff), "123456789 123456789 123456789 12") == EOK); + for (unsigned i = 0; i < 1024 / 32 - 1; ++i) { + ContextAppendWrite(ctx, buff, strlen(buff)); + ASSERT_TRUE(ctx->wEnd == (i + 1) * 32 - 1); + } + ASSERT_TRUE(CalculateLeft(ctx) == 31); + ContextAppendWrite(ctx, buff, strlen(buff)); + ASSERT_TRUE(ctx->wCapacity == 2048); + ASSERT_TRUE(ctx->wEnd == (1023 + 1024)); +} + +static int ExpandReadCache(Context *context, int len) +{ + int left = (context->rBegin <= context->rEnd) ? (context->rCapacity - 1 - context->rEnd + context->rBegin) + : (context->rBegin - context->rEnd - 1); + if (left < len) { + int capacity = context->rCapacity; + while (left < len) { + capacity += context->rCapacity; + left += context->rCapacity; + } + char *p = (char *)calloc(capacity, sizeof(char)); + if (p == nullptr) { + return -1; + } + if (memmove_s(p, capacity, context->szRead, context->rCapacity) != EOK) { + free(p); + return -1; + } + if (context->rBegin > context->rEnd && + memmove_s(p + context->rCapacity, context->rCapacity, p, context->rEnd) != EOK) { + free(p); + return -1; + } + char *pFree = context->szRead; + context->szRead = p; + if (context->rBegin > context->rEnd) { + context->rEnd += context->rCapacity; + } + context->rCapacity = capacity; + free(pFree); + } + return 0; +} + +static int ContextAppendRead(Context *context, const char *buf, int len) +{ + if (ExpandReadCache(context, len) < 0) { + return -1; + } + if (context->rEnd + len < context->rCapacity) { + if (memmove_s(context->szRead + context->rEnd, context->rCapacity - context->rEnd, buf, len) != EOK) { + return -1; + } + context->rEnd += len; + } else { + int tmp = context->rCapacity - context->rEnd; + if (tmp > 0 && memmove_s(context->szRead + context->rEnd, tmp, buf, tmp) != EOK) { + return -1; + } + if (tmp < len && memmove_s(context->szRead, len - tmp, buf + tmp, len - tmp) != EOK) { + return -1; + } + context->rEnd = len - tmp; + } + return 0; +} + +HWTEST_F(ContextTest, ContextGetReadRecordTest, TestSize.Level1) +{ + ctx = CreateContext(1024); + ASSERT_TRUE(ctx != nullptr); + ASSERT_TRUE(ctx->rCapacity == 1024); + char *p = ContextGetReadRecord(ctx); + ASSERT_TRUE(p == nullptr); + + int ret = ContextAppendRead(ctx, "hello", strlen("hello")); + ASSERT_TRUE(ret == 0); + p = ContextGetReadRecord(ctx); + ASSERT_TRUE(p == nullptr); + ret = ContextAppendRead(ctx, ctx->cMsgEnd, strlen(ctx->cMsgEnd)); + ASSERT_TRUE(ret == 0); + p = ContextGetReadRecord(ctx); + ASSERT_TRUE(p != nullptr); + EXPECT_TRUE(strcmp(p, "hello") == 0); + free(p); + ctx->rBegin = ctx->rEnd = 1024 - 5; // set end pos + ret = ContextAppendRead(ctx, "hello, welcome", strlen("hello, welcome")); + ASSERT_TRUE(ret == 0); + p = ContextGetReadRecord(ctx); + ASSERT_TRUE(p == nullptr); + ret = ContextAppendRead(ctx, ctx->cMsgEnd, strlen(ctx->cMsgEnd)); + ASSERT_TRUE(ret == 0); + p = ContextGetReadRecord(ctx); + ASSERT_TRUE(p != nullptr); + EXPECT_TRUE(strcmp(p, "hello, welcome") == 0); + free(p); +} + +HWTEST_F(ContextTest, ContextReadNetTest, TestSize.Level1) +{ + ctx = CreateContext(1024); + ASSERT_TRUE(ctx != nullptr); + int ret = ContextReadNet(ctx); + EXPECT_TRUE(ret == MAX_ONE_LINE_SIZE - 1); + ctx->rBegin = 1024 - 5; + ret = ContextReadNet(ctx); + EXPECT_TRUE(ret == MAX_ONE_LINE_SIZE - 1); + EXPECT_TRUE(ctx->rCapacity == 2048); +} + +HWTEST_F(ContextTest, ContextWriteNetTest, TestSize.Level1) +{ + ASSERT_TRUE(ContextWriteNet(nullptr) == -1); + ctx = CreateContext(1024); + ASSERT_TRUE(ctx != nullptr); + int ret = ContextWriteNet(ctx); + EXPECT_TRUE(ret == 0); + char buff[] = "123456789 123456789 123456789 12"; + int size = strlen(buff); + ContextAppendWrite(ctx, buff, size); + ret = ContextWriteNet(ctx); + EXPECT_TRUE(ret == size); + ctx->wBegin = ctx->wEnd = 1023; + ContextAppendWrite(ctx, buff, size); + ret = ContextWriteNet(ctx); + EXPECT_TRUE(ret == size - 1); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/context_test.h b/tests/wifi_standard/ipc_framework/cRPC/unittest/context_test.h new file mode 100644 index 000000000..bae6a4a6e --- /dev/null +++ b/tests/wifi_standard/ipc_framework/cRPC/unittest/context_test.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_WIFI_CRPC_CONTEXT_TEST_H +#define OHOS_WIFI_CRPC_CONTEXT_TEST_H + +#include +#include "context.h" + +namespace OHOS { +namespace Wifi { +class ContextTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + { + if (ctx != nullptr) { + ReleaseContext(ctx); + ctx = nullptr; + } + } + +public: + Context *ctx; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.cpp b/tests/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.cpp new file mode 100644 index 000000000..f151c1e0c --- /dev/null +++ b/tests/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.cpp @@ -0,0 +1,73 @@ +/* + * 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 "hash_table_test.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +static unsigned g_pNum[] = { + 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}; +static unsigned FindNextNum(unsigned num) +{ + for (unsigned i = 0; i < sizeof(g_pNum) / sizeof(g_pNum[0]); ++i) { + if (g_pNum[i] >= num) { + return g_pNum[i]; + } + } + return 0; +} + +HWTEST_F(HashTableTest, InitHashTableTest, TestSize.Level1) +{ + unsigned slots = 13; + table = InitHashTable(slots); + EXPECT_TRUE(table != nullptr); + EXPECT_TRUE(table->list != nullptr); + EXPECT_TRUE(table->slots == FindNextNum(slots)); + for (unsigned i = 0; i < table->slots; ++i) { + EXPECT_TRUE(table->list[i] == nullptr); + } +} + +HWTEST_F(HashTableTest, UseHashTableTest, TestSize.Level1) +{ + table = InitHashTable(3); + ASSERT_NE(table, nullptr); + for (int fd = 1; fd <= 100; ++fd) { + Context *ctx = (Context *)calloc(1, sizeof(Context)); + ctx->fd = fd; + ASSERT_EQ(InsertHashTable(table, ctx), 0); + } + ASSERT_EQ(table->size, 100); + Context *ctx = (Context *)calloc(1, sizeof(Context)); + ctx->fd = 1; + EXPECT_EQ(InsertHashTable(table, ctx), -2); + free(ctx); + int del = 0; + for (int fd = 1; fd <= 100; ++fd) { + Context *pCtx = FindContext(table, fd); + EXPECT_NE(pCtx, nullptr); + EXPECT_EQ(pCtx->fd, fd); + if (fd % 10 == 0) { + ++del; + DeleteHashTable(table, pCtx); + } + } + EXPECT_EQ(table->size, 100 - del); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.h b/tests/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.h new file mode 100644 index 000000000..a64b98f48 --- /dev/null +++ b/tests/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.h @@ -0,0 +1,46 @@ +/* + * 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_WIFI_CRPC_HASH_TABLE_TEST_H +#define OHOS_WIFI_CRPC_HASH_TABLE_TEST_H + +#include +#include "hash_table.h" + +namespace OHOS { +namespace Wifi { +class HashTableTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + table = nullptr; + } + virtual void TearDown() + { + if (table != nullptr) { + DestroyHashTable(table); + table = nullptr; + } + } + +public: + HashTable *table; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/net_test.cpp b/tests/wifi_standard/ipc_framework/cRPC/unittest/net_test.cpp new file mode 100644 index 000000000..7b818f377 --- /dev/null +++ b/tests/wifi_standard/ipc_framework/cRPC/unittest/net_test.cpp @@ -0,0 +1,95 @@ +/* + * 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 "net_test.h" +#include "net.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(RpcNetTest, SetNonBlockTest, TestSize.Level1) +{ + int fd = socket(AF_INET, SOCK_STREAM, 0); + ASSERT_TRUE(fd >= 0); + EXPECT_TRUE(SetNonBlock(fd, 0) == 0); + int flags = fcntl(fd, F_GETFL, 0); + EXPECT_TRUE((flags & O_NONBLOCK) == 0); + EXPECT_TRUE(SetNonBlock(fd, 1) == 0); + flags = fcntl(fd, F_GETFL, 0); + EXPECT_TRUE((flags & O_NONBLOCK) > 0); + close(fd); +} + +static constexpr int MAX_SIZE = 10240; +HWTEST_F(RpcNetTest, MyReadTest, TestSize.Level1) +{ + int fd = 0; + char buff[MAX_SIZE] = {0}; + EXPECT_TRUE(MyRead(fd, buff, 0) == 0); + EXPECT_TRUE(MyRead(fd, buff, MAX_SIZE) == 0); + EXPECT_TRUE(MyRead(fd, buff, MAX_SIZE + 1) == SOCK_ERR); + EXPECT_TRUE(MyRead(fd, buff, 10) == 10); +} + +HWTEST_F(RpcNetTest, MyWriteTest, TestSize.Level1) +{ + int fd = 0; + char buff[MAX_SIZE] = {0}; + EXPECT_TRUE(MyWrite(fd, buff, 0) == 0); + EXPECT_TRUE(MyWrite(fd, buff, MAX_SIZE) == 0); + EXPECT_TRUE(MyWrite(fd, buff, MAX_SIZE + 1) == SOCK_ERR); + EXPECT_TRUE(MyWrite(fd, buff, 10) == 10); +} + +HWTEST_F(RpcNetTest, CreateUnixServerTest, TestSize.Level1) +{ + int fd = CreateUnixServer("./rpc_test.sock", 1); + EXPECT_TRUE(fd >= 0); + close(fd); + if (access("./rpc_test.sock", 0) == 0) { + unlink("./rpc_test.sock"); + } +} + +HWTEST_F(RpcNetTest, ConnectUnixServerTest, TestSize.Level1) +{ + EXPECT_TRUE(ConnectUnixServer("./rpc_test.sock") < 0); + int servFd = CreateUnixServer("./rpc_test.sock", 1); + EXPECT_TRUE(servFd >= 0); + int cliFd = ConnectUnixServer("./rpc_test.sock"); + EXPECT_TRUE(cliFd >= 0); + close(cliFd); + close(servFd); + if (access("./rpc_test.sock", 0) == 0) { + unlink("./rpc_test.sock"); + } +} + +HWTEST_F(RpcNetTest, WaitFdEventTest, TestSize.Level1) +{ + int servFd = CreateUnixServer("./rpc_test.sock", 1); + EXPECT_TRUE(servFd >= 0); + EXPECT_TRUE(WaitFdEvent(servFd, READ_EVENT, 100) == 0); + int cliFd = ConnectUnixServer("./rpc_test.sock"); + EXPECT_TRUE(cliFd >= 0); + EXPECT_TRUE(WaitFdEvent(servFd, READ_EVENT, 100) == 1); + close(cliFd); + close(servFd); + if (access("./rpc_test.sock", 0) == 0) { + unlink("./rpc_test.sock"); + } +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/net_test.h b/tests/wifi_standard/ipc_framework/cRPC/unittest/net_test.h new file mode 100644 index 000000000..6d8007bf2 --- /dev/null +++ b/tests/wifi_standard/ipc_framework/cRPC/unittest/net_test.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_WIFI_CRPC_NET_TEST_H +#define OHOS_WIFI_CRPC_NET_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class RpcNetTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/rpc_test_main.cpp b/tests/wifi_standard/ipc_framework/cRPC/unittest/rpc_test_main.cpp new file mode 100644 index 000000000..6b29b2cf0 --- /dev/null +++ b/tests/wifi_standard/ipc_framework/cRPC/unittest/rpc_test_main.cpp @@ -0,0 +1,61 @@ +/* + * 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 + +static constexpr int MAX_SIZE = 10240; +extern "C" int __wrap_read(int fd, void *buf, unsigned int size) +{ + const int letterSize = 26; + errno = 0; + fd = 0; + if (size == 0) { + return 0; + } else if (size == MAX_SIZE) { + errno = EWOULDBLOCK; + return -1; + } else if (size > MAX_SIZE) { + return -1; + } else { + for (unsigned int i = 0; i < size; ++i) { + ((char *)buf)[i] = 'a' + (i % letterSize); + } + return size; + } +} + +extern "C" int __wrap_write(int fd, const void *buf, unsigned int size) +{ + errno = 0; + fd = 0; + if (buf == NULL) { + return 0; + } + if (size == 0) { + return 0; + } else if (size == MAX_SIZE) { + errno = EWOULDBLOCK; + return -1; + } else if (size > MAX_SIZE) { + return -1; + } else { + return size; + } +} + +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/serial_test.cpp b/tests/wifi_standard/ipc_framework/cRPC/unittest/serial_test.cpp new file mode 100644 index 000000000..45e9e45dc --- /dev/null +++ b/tests/wifi_standard/ipc_framework/cRPC/unittest/serial_test.cpp @@ -0,0 +1,68 @@ +/* + * 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 "serial_test.h" +#include "serial.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(SerialTest, SerialTest, TestSize.Level1) +{ + ctx = CreateContext(1024); + WriteBegin(ctx, 0); + WriteFunc(ctx, "SerialTest"); + WriteInt(ctx, 100); + WriteLong(ctx, 1234567890L); + WriteInt64(ctx, 12345678909832323LL); + WriteDouble(ctx, 3.14159); + WriteChar(ctx, 'a'); + WriteStr(ctx, "Hello, world"); + int count = strlen("2c:f0:xx:xx:xx:be"); + WriteUStr(ctx, (const unsigned char *)"2c:f0:xx:xx:xx:be", count); + WriteEnd(ctx); + + ctx->oneProcess = ctx->szWrite; + ctx->nSize = ctx->wEnd; + + EXPECT_TRUE(strncmp(ctx->oneProcess, "N|", 2) == 0); + ctx->nPos = 2; + char str[1024] = {0}; + ASSERT_EQ(ReadFunc(ctx, str, 1024), 0); + EXPECT_TRUE(strcmp(str, "SerialTest") == 0); + int i = 0; + ASSERT_EQ(ReadInt(ctx, &i), 0); + EXPECT_TRUE(i == 100); + long l = 0; + ASSERT_EQ(ReadLong(ctx, &l), 0); + EXPECT_TRUE(l == 1234567890L); + int64_t t = 0; + ASSERT_EQ(ReadInt64(ctx, &t), 0); + EXPECT_TRUE(t == 12345678909832323LL); + double d = 0.0; + ASSERT_EQ(ReadDouble(ctx, &d), 0); + EXPECT_TRUE(d - 3.14159 < 0.000001 && d - 3.14159 > -0.000001); + char c = ' '; + ASSERT_EQ(ReadChar(ctx, &c), 0); + EXPECT_TRUE(c == 'a'); + ASSERT_EQ(ReadStr(ctx, str, 1024), 0); + EXPECT_TRUE(strcmp(str, "Hello, world") == 0); + ASSERT_EQ(ReadUStr(ctx, (unsigned char *)str, count + 1), 0); + EXPECT_TRUE(strcmp(str, "2c:f0:xx:xx:xx:be") == 0); + EXPECT_TRUE(strncmp(ctx->oneProcess + ctx->nPos, "$$$$$$", 6) == 0); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/serial_test.h b/tests/wifi_standard/ipc_framework/cRPC/unittest/serial_test.h new file mode 100644 index 000000000..03976c8d5 --- /dev/null +++ b/tests/wifi_standard/ipc_framework/cRPC/unittest/serial_test.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_WIFI_CRPC_SERIAL_TEST_H +#define OHOS_WIFI_CRPC_SERIAL_TEST_H + +#include +#include "context.h" + +namespace OHOS { +namespace Wifi { +class SerialTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + { + if (ctx != nullptr) { + ReleaseContext(ctx); + ctx = nullptr; + } + } + +public: + Context *ctx; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/common/unittest/BUILD.gn b/tests/wifi_standard/wifi_framework/common/unittest/BUILD.gn new file mode 100644 index 000000000..81d472a37 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/common/unittest/BUILD.gn @@ -0,0 +1,75 @@ +# 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. + +import("//build/test.gni") +SUBSYSTEM_DIR = "//foundation/communication/wifi" +module_output_path = "wifi_standard/common_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/tests/wifi_standard/wifi_framework/common/unittest", + ] +} + +ohos_unittest("common_unittest") { + module_out_path = module_output_path + sources = [ + "$SUBSYSTEM_DIR/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/log/log_helper.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp", + "common_test.cpp", + "wifi_config_file_test.cpp", + "wifi_global_func_test.cpp", + "wifi_ip_tools_test.cpp", + "wifi_log_helper_test.cpp", + "wifi_network_interface_test.cpp", + ] + + include_dirs = [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/include", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/utils", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/log", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/config", + "$SUBSYSTEM_DIR/interfaces/innerkits/native_cpp/wifi_standard/interfaces", + ] + + deps = [ "//utils/native/base:utils" ] + + ldflags = [ + "-fPIC", + "--coverage", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + configs = [ ":module_private_config" ] + + part_name = "wifi_standard" + subsystem_name = "communication" + testonly = true +} + +group("unittest") { + testonly = true + deps = [ ":common_unittest" ] +} diff --git a/tests/wifi_standard/wifi_framework/common/unittest/common_test.cpp b/tests/wifi_standard/wifi_framework/common/unittest/common_test.cpp new file mode 100644 index 000000000..3319c1428 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/common/unittest/common_test.cpp @@ -0,0 +1,22 @@ +/* + * 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 + +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_config_file_test.cpp b/tests/wifi_standard/wifi_framework/common/unittest/wifi_config_file_test.cpp new file mode 100644 index 000000000..c08b5668a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/common/unittest/wifi_config_file_test.cpp @@ -0,0 +1,325 @@ +/* + * 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 "wifi_config_file_test.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiConfigFileTest, LoadConfig, TestSize.Level1) +{ + int ret = mWifiCfg.LoadConfig(); + if (ret < 0) { + mWifiCfg.SaveConfig(); + ret = mWifiCfg.LoadConfig(); + } + EXPECT_EQ(ret, 0); +} + +HWTEST_F(WifiConfigFileTest, SaveConfig, TestSize.Level1) +{ + EXPECT_EQ(mWifiCfg.SaveConfig(), 0); +} + +HWTEST_F(WifiConfigFileTest, SaveValueCheck, TestSize.Level1) +{ + WifiConfig tmp; + tmp.defaultWifiInterface = "abcd"; + tmp.scanAlwaysSwitch = true; + tmp.staAirplaneMode = true; + tmp.staLastState = true; + tmp.savedDeviceAppraisalPriority = PRIORITY_1; + tmp.scoretacticsScoreSlope = SCORE_SLOPE; + tmp.scoretacticsInitScore = INIT_SCORE; + tmp.scoretacticsSameBssidScore = SAME_BSSID_SCORE; + tmp.scoretacticsSameNetworkScore = SAME_NETWORK_SCORE; + tmp.scoretacticsFrequency5GHzScore = FREQUENCY_5_GHZ_SCORE; + tmp.scoretacticsLastSelectionScore = LAST_SELECTION_SCORE; + tmp.scoretacticsSecurityScore = SECURITY_SCORE; + tmp.dhcpIpType = static_cast(DhcpIpType::DHCP_IPTYPE_IPV4); + std::vector vec; + vec.push_back(tmp); + mWifiCfg.SetValue(vec); + mWifiCfg.SaveConfig(); + mWifiCfg.LoadConfig(); + vec.clear(); + mWifiCfg.GetValue(vec); + EXPECT_TRUE(vec.size() == 1); + WifiConfig ldCfg = vec[0]; + EXPECT_EQ(tmp.defaultWifiInterface, ldCfg.defaultWifiInterface); + EXPECT_EQ(tmp.scanAlwaysSwitch, ldCfg.scanAlwaysSwitch); + EXPECT_EQ(tmp.staAirplaneMode, ldCfg.staAirplaneMode); + EXPECT_EQ(tmp.staLastState, ldCfg.staLastState); + EXPECT_EQ(tmp.savedDeviceAppraisalPriority, ldCfg.savedDeviceAppraisalPriority); + EXPECT_EQ(tmp.scoretacticsScoreSlope, ldCfg.scoretacticsScoreSlope); + EXPECT_EQ(tmp.scoretacticsInitScore, ldCfg.scoretacticsInitScore); + EXPECT_EQ(tmp.scoretacticsSameBssidScore, ldCfg.scoretacticsSameBssidScore); + EXPECT_EQ(tmp.scoretacticsSameNetworkScore, ldCfg.scoretacticsSameNetworkScore); + EXPECT_EQ(tmp.scoretacticsFrequency5GHzScore, ldCfg.scoretacticsFrequency5GHzScore); + EXPECT_EQ(tmp.scoretacticsLastSelectionScore, ldCfg.scoretacticsLastSelectionScore); + EXPECT_EQ(tmp.scoretacticsSecurityScore, ldCfg.scoretacticsSecurityScore); + EXPECT_EQ(tmp.dhcpIpType, ldCfg.dhcpIpType); +} + +HWTEST_F(WifiConfigFileTest, LoadDeviceConfig, TestSize.Level1) +{ + int ret = mDeviceCfg.LoadConfig(); + if (ret < 0) { + mDeviceCfg.SaveConfig(); + ret = mDeviceCfg.LoadConfig(); + } + EXPECT_EQ(ret, 0); +} + +HWTEST_F(WifiConfigFileTest, SaveDeviceConfig, TestSize.Level1) +{ + EXPECT_EQ(mDeviceCfg.SaveConfig(), 0); +} + +HWTEST_F(WifiConfigFileTest, SaveDeviceValueCheck, TestSize.Level1) +{ + WifiDeviceConfig tmp; + tmp.status = static_cast(WifiDeviceConfigStatus::ENABLED); + tmp.bssid = "01:xx:xx:xx:xx:06"; + tmp.ssid = "my wifi"; + tmp.band = static_cast(BandType::BAND_2GHZ); + tmp.channel = 1; + tmp.isPasspoint = true; + tmp.isEphemeral = true; + tmp.preSharedKey = "12345678"; + tmp.keyMgmt = "NONE"; + tmp.wepKeys[0] = "12345678"; + tmp.wepKeys[1] = "12345679"; + tmp.wepKeys[1 + 1] = "abcdefgh"; + tmp.wepKeys[1 + 1 + 1] = "0000abcd"; + tmp.wepTxKeyIndex = 1; + tmp.priority = 1; + tmp.hiddenSSID = true; + std::vector vec; + vec.push_back(tmp); + mDeviceCfg.SetValue(vec); + mDeviceCfg.SaveConfig(); + mDeviceCfg.LoadConfig(); + vec.clear(); + mDeviceCfg.GetValue(vec); + EXPECT_TRUE(vec.size() == 1); + WifiDeviceConfig ldCfg = vec[0]; + EXPECT_TRUE(tmp.status == ldCfg.status); + EXPECT_TRUE(tmp.bssid == ldCfg.bssid); + EXPECT_TRUE(tmp.ssid == ldCfg.ssid); + EXPECT_TRUE(tmp.band == ldCfg.band); + EXPECT_TRUE(tmp.channel == ldCfg.channel); + EXPECT_TRUE(tmp.isPasspoint == ldCfg.isPasspoint); + EXPECT_TRUE(tmp.isEphemeral == ldCfg.isEphemeral); + EXPECT_TRUE(tmp.preSharedKey == ldCfg.preSharedKey); + EXPECT_TRUE(tmp.keyMgmt == ldCfg.keyMgmt); + EXPECT_TRUE(tmp.wepTxKeyIndex == ldCfg.wepTxKeyIndex); + EXPECT_TRUE(tmp.priority == ldCfg.priority); + EXPECT_TRUE(tmp.hiddenSSID == ldCfg.hiddenSSID); + for (int i = 0; i < WEPKEYS_SIZE; ++i) { + EXPECT_TRUE(tmp.wepKeys[i] == ldCfg.wepKeys[i]); + } +} + +HWTEST_F(WifiConfigFileTest, LoadHotspotConfig, TestSize.Level1) +{ + int ret = mHotspotCfg.LoadConfig(); + if (ret < 0) { + mHotspotCfg.SaveConfig(); + ret = mHotspotCfg.LoadConfig(); + } + EXPECT_EQ(ret, 0); +} + +HWTEST_F(WifiConfigFileTest, SaveHotspotConfig, TestSize.Level1) +{ + EXPECT_EQ(mHotspotCfg.SaveConfig(), 0); +} + +HWTEST_F(WifiConfigFileTest, SaveHotspotValueCheck, TestSize.Level1) +{ + HotspotConfig tmp; + tmp.SetSsid("my wifi"); + tmp.SetPreSharedKey("12345678"); + tmp.SetSecurityType(KeyMgmt::WPA_PSK); + tmp.SetBand(BandType::BAND_5GHZ); + tmp.SetChannel(1); + tmp.SetMaxConn(1); + std::vector vec; + vec.push_back(tmp); + mHotspotCfg.SetValue(vec); + mHotspotCfg.SaveConfig(); + mHotspotCfg.LoadConfig(); + vec.clear(); + mHotspotCfg.GetValue(vec); + EXPECT_TRUE(vec.size() == 1); + HotspotConfig ldCfg = vec[0]; + EXPECT_TRUE(tmp.GetSsid() == ldCfg.GetSsid()); + EXPECT_TRUE(tmp.GetPreSharedKey() == ldCfg.GetPreSharedKey()); + EXPECT_TRUE(tmp.GetSecurityType() == ldCfg.GetSecurityType()); + EXPECT_TRUE(tmp.GetBand() == ldCfg.GetBand()); + EXPECT_TRUE(tmp.GetChannel() == ldCfg.GetChannel()); + EXPECT_TRUE(tmp.GetMaxConn() == ldCfg.GetMaxConn()); +} + +HWTEST_F(WifiConfigFileTest, LoadBlockConfig, TestSize.Level1) +{ + int ret = mBlockCfg.LoadConfig(); + if (ret < 0) { + mBlockCfg.SaveConfig(); + ret = mBlockCfg.LoadConfig(); + } + EXPECT_EQ(ret, 0); +} + +HWTEST_F(WifiConfigFileTest, SaveBlockConfig, TestSize.Level1) +{ + EXPECT_EQ(mBlockCfg.SaveConfig(), 0); +} + +HWTEST_F(WifiConfigFileTest, SaveBlockValueCheck, TestSize.Level1) +{ + StationInfo tmp; + tmp.deviceName = "my wifi"; + tmp.bssid = "01:xx:xx:xx:xx:06"; + tmp.ipAddr = "192.xxx.x.1"; + std::vector vec; + vec.push_back(tmp); + tmp.deviceName = "my wifi 2"; + tmp.bssid = "01:xx:xx:xx:xx:07"; + tmp.ipAddr = "192.xxx.x.2"; + vec.push_back(tmp); + mBlockCfg.SetValue(vec); + mBlockCfg.SaveConfig(); + mBlockCfg.LoadConfig(); + vec.clear(); + mBlockCfg.GetValue(vec); + EXPECT_TRUE(vec.size() == 2); + StationInfo ldCfg = vec[1]; + EXPECT_TRUE(tmp.deviceName == ldCfg.deviceName); + EXPECT_TRUE(tmp.bssid == ldCfg.bssid); + EXPECT_TRUE(tmp.ipAddr == ldCfg.ipAddr); +} + +static void AddWifiP2pGroupInfoTestFirst(std::vector &vec) +{ + WifiP2pGroupInfo item; + item.SetGroupName("net_1"); + item.SetIsGroupOwner(true); + WifiP2pDevice device; + device.SetDeviceName("device_1"); + device.SetDeviceAddress("devAddr_1"); + device.SetPrimaryDeviceType("priDevType_1"); + device.SetSecondaryDeviceType("secDevType_1"); + device.SetP2pDeviceStatus(P2pDeviceStatus::PDS_CONNECTED); + device.SetWpsConfigMethod((int)WpsConfigMethod::WPS_CFG_PUSHBUTTON); + device.SetDeviceCapabilitys((int)P2pDeviceCapability::PDC_CLIENT_DISCOVERABILITY); + device.SetGroupCapabilitys((int)P2pGroupCapability::PGC_INTRA_BSS_DIST); + item.SetOwner(device); + item.SetPassphrase("passphrase_1"); + item.SetInterface("interface_1"); + item.SetGroupName("name_1"); + item.SetFrequency(0); + item.SetIsPersistent(true); + item.SetP2pGroupStatus(P2pGroupStatus::GS_CREATED); + item.SetNetworkId(0); + WifiP2pDevice client; + client.SetDeviceName("device_2"); + client.SetDeviceAddress("devAddr_2"); + client.SetPrimaryDeviceType("priDevType_2"); + client.SetSecondaryDeviceType("secDevType_2"); + client.SetP2pDeviceStatus(P2pDeviceStatus::PDS_CONNECTED); + client.SetWpsConfigMethod((int)WpsConfigMethod::WPS_CFG_KEYPAD); + client.SetDeviceCapabilitys((int)P2pDeviceCapability::PDC_CLIENT_DISCOVERABILITY); + client.SetGroupCapabilitys((int)P2pGroupCapability::PGC_GROUP_OWNER); + WifiP2pDevice clientSecond; + clientSecond.SetDeviceName("device_3"); + clientSecond.SetDeviceAddress("devAddr_3"); + clientSecond.SetPrimaryDeviceType("priDevType_3"); + clientSecond.SetSecondaryDeviceType("secDevType_3"); + clientSecond.SetP2pDeviceStatus(P2pDeviceStatus::PDS_CONNECTED); + clientSecond.SetWpsConfigMethod((int)WpsConfigMethod::WPS_CFG_INVALID); + clientSecond.SetDeviceCapabilitys((int)P2pDeviceCapability::PDC_STARTED_CONCURRENT_OPER); + clientSecond.SetGroupCapabilitys((int)P2pGroupCapability::PGC_GROUP_OWNER); + item.AddClientDevice(client); + item.AddClientDevice(clientSecond); + vec.push_back(item); + return; +} + +static void AddWifiP2pGroupInfoTestSecond(std::vector &vec) +{ + WifiP2pGroupInfo item; + item.SetGroupName("net_2"); + item.SetIsGroupOwner(false); + WifiP2pDevice device; + device.SetDeviceName("device_4"); + device.SetDeviceAddress("devAddr_4"); + device.SetPrimaryDeviceType("priDevType_4"); + device.SetSecondaryDeviceType("secDevType_4"); + device.SetP2pDeviceStatus(P2pDeviceStatus::PDS_INVITED); + device.SetWpsConfigMethod((int)WpsConfigMethod::WPS_CFG_DISPLAY); + device.SetDeviceCapabilitys((int)P2pDeviceCapability::PDC_CLIENT_DISCOVERABILITY); + device.SetGroupCapabilitys((int)P2pGroupCapability::PGC_INTRA_BSS_DIST); + item.SetOwner(device); + item.SetPassphrase("passphrase_2"); + item.SetInterface("interface_2"); + item.SetGroupName("name_2"); + item.SetFrequency(1); + item.SetIsPersistent(false); + item.SetP2pGroupStatus(P2pGroupStatus::GS_STARTED); + item.SetNetworkId(1); + WifiP2pDevice client; + client.SetDeviceName("device_5"); + client.SetDeviceAddress("devAddr_5"); + client.SetPrimaryDeviceType("priDevType_5"); + client.SetSecondaryDeviceType("secDevType_5"); + client.SetP2pDeviceStatus(P2pDeviceStatus::PDS_CONNECTED); + client.SetWpsConfigMethod((int)WpsConfigMethod::WPS_CFG_KEYPAD); + client.SetDeviceCapabilitys((int)P2pDeviceCapability::PDC_SERVICE_DISCOVERY); + client.SetGroupCapabilitys((int)P2pGroupCapability::PGC_INTRA_BSS_DIST); + WifiP2pDevice clientSecond; + clientSecond.SetDeviceName("device_6"); + clientSecond.SetDeviceAddress("devAddr_6"); + clientSecond.SetPrimaryDeviceType("priDevType_6"); + clientSecond.SetSecondaryDeviceType("secDevType_6"); + clientSecond.SetP2pDeviceStatus(P2pDeviceStatus::PDS_CONNECTED); + clientSecond.SetWpsConfigMethod((int)WpsConfigMethod::WPS_CFG_INVALID); + clientSecond.SetDeviceCapabilitys((int)P2pDeviceCapability::PDC_REMOVING_INFRA_MANAGED); + clientSecond.SetGroupCapabilitys((int)P2pGroupCapability::PGC_GROUP_OWNER); + item.AddClientDevice(client); + item.AddClientDevice(clientSecond); + vec.push_back(item); + return; +} + +HWTEST_F(WifiConfigFileTest, SaveLoadWifiP2pGroupInfo_SUCCESS, TestSize.Level1) +{ + std::vector vec; + AddWifiP2pGroupInfoTestFirst(vec); + AddWifiP2pGroupInfoTestSecond(vec); + mWifiP2pGroupInfo.SetValue(vec); + mWifiP2pGroupInfo.SaveConfig(); + mWifiP2pGroupInfo.LoadConfig(); + unsigned orgSize = vec.size(); + vec.clear(); + mWifiP2pGroupInfo.GetValue(vec); + EXPECT_TRUE(vec.size() == orgSize); + EXPECT_EQ(true, (strcmp(vec.at(1).GetClientDevices().at(1).GetDeviceName().c_str(), "device_6") == 0)); + EXPECT_EQ(P2pGroupCapability::PGC_GROUP_OWNER, + static_cast(vec.at(1).GetClientDevices().at(1).GetGroupCapabilitys())); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_config_file_test.h b/tests/wifi_standard/wifi_framework/common/unittest/wifi_config_file_test.h new file mode 100644 index 000000000..7f80f82a6 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/common/unittest/wifi_config_file_test.h @@ -0,0 +1,49 @@ +/* + * 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_WIFI_CONFIG_FILE_TEST_H +#define OHOS_WIFI_CONFIG_FILE_TEST_H + +#include +#include "wifi_config_file_impl.h" + +namespace OHOS { +namespace Wifi { +class WifiConfigFileTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + mWifiCfg.SetConfigFilePath("./wifi_config_test.conf"); + mDeviceCfg.SetConfigFilePath("./device_config_test.conf"); + mHotspotCfg.SetConfigFilePath("./hotspot_config_test.conf"); + mBlockCfg.SetConfigFilePath("./block_list_test.conf"); + mWifiP2pGroupInfo.SetConfigFilePath("./wifi_p2p_groups_test.conf"); + } + virtual void TearDown() + {} + +public: + WifiConfigFileImpl mWifiCfg; + WifiConfigFileImpl mDeviceCfg; + WifiConfigFileImpl mHotspotCfg; + WifiConfigFileImpl mBlockCfg; + WifiConfigFileImpl mWifiP2pGroupInfo; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_global_func_test.cpp b/tests/wifi_standard/wifi_framework/common/unittest/wifi_global_func_test.cpp new file mode 100644 index 000000000..f5e715ae1 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/common/unittest/wifi_global_func_test.cpp @@ -0,0 +1,200 @@ +/* + * 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 "wifi_global_func_test.h" +#include "wifi_global_func.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiGlobalFuncTest, CfgCheckSsid, TestSize.Level1) +{ + HotspotConfig config; + EXPECT_TRUE(CfgCheckSsid(config) != ErrCode::WIFI_OPT_SUCCESS); + config.SetSsid("1"); + EXPECT_TRUE(CfgCheckSsid(config) == ErrCode::WIFI_OPT_SUCCESS); + config.SetSsid("12"); + EXPECT_TRUE(CfgCheckSsid(config) == ErrCode::WIFI_OPT_SUCCESS); + config.SetSsid("123456789 123456789 123456789 1"); + EXPECT_TRUE(CfgCheckSsid(config) == ErrCode::WIFI_OPT_SUCCESS); + config.SetSsid("123456789 123456789 123456789 12"); + EXPECT_TRUE(CfgCheckSsid(config) == ErrCode::WIFI_OPT_SUCCESS); + config.SetSsid("123456789 123456789 123456789 123"); + EXPECT_TRUE(CfgCheckSsid(config) != ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiGlobalFuncTest, CfgCheckPsk, TestSize.Level1) +{ + HotspotConfig config; + EXPECT_TRUE(CfgCheckPsk(config) != ErrCode::WIFI_OPT_SUCCESS); + config.SetPreSharedKey("1234567"); + EXPECT_TRUE(CfgCheckPsk(config) != ErrCode::WIFI_OPT_SUCCESS); + config.SetPreSharedKey("12345678"); + EXPECT_TRUE(CfgCheckPsk(config) == ErrCode::WIFI_OPT_SUCCESS); + config.SetPreSharedKey("123456789"); + EXPECT_TRUE(CfgCheckPsk(config) == ErrCode::WIFI_OPT_SUCCESS); + config.SetPreSharedKey("123456789 123456789 123456789 123456789 123456789 123456789 123"); + EXPECT_TRUE(CfgCheckPsk(config) == ErrCode::WIFI_OPT_SUCCESS); + config.SetPreSharedKey("123456789 123456789 123456789 123456789 123456789 123456789 1234"); + EXPECT_TRUE(CfgCheckPsk(config) != ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiGlobalFuncTest, CfgCheckBand, TestSize.Level1) +{ + HotspotConfig config; + std::vector bands; + EXPECT_TRUE(CfgCheckBand(config, bands) != ErrCode::WIFI_OPT_SUCCESS); + bands.push_back(BandType::BAND_2GHZ); + config.SetBand(BandType::BAND_2GHZ); + EXPECT_TRUE(CfgCheckBand(config, bands) == ErrCode::WIFI_OPT_SUCCESS); + config.SetBand(BandType::BAND_NONE); + EXPECT_TRUE(CfgCheckBand(config, bands) != ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiGlobalFuncTest, CfgCheckChannel, TestSize.Level1) +{ + HotspotConfig config; + ChannelsTable table; + table[BandType::BAND_2GHZ].push_back(1); + EXPECT_TRUE(CfgCheckChannel(config, table) != ErrCode::WIFI_OPT_SUCCESS); + config.SetBand(BandType::BAND_2GHZ); + config.SetChannel(1); + EXPECT_TRUE(CfgCheckChannel(config, table) == ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiGlobalFuncTest, IsValidHotspotConfig, TestSize.Level1) +{ + HotspotConfig config, centerConfig; + std::vector bands; + ChannelsTable table; + EXPECT_TRUE(IsValidHotspotConfig(config, centerConfig, bands, table) == ErrCode::WIFI_OPT_INVALID_PARAM); + config.SetSsid("123456"); + config.SetSecurityType(KeyMgmt::NONE); + config.SetPreSharedKey("12345678"); + EXPECT_TRUE(IsValidHotspotConfig(config, centerConfig, bands, table) == ErrCode::WIFI_OPT_INVALID_PARAM); + config.SetSecurityType(KeyMgmt::FT_EAP); + EXPECT_TRUE(IsValidHotspotConfig(config, centerConfig, bands, table) == ErrCode::WIFI_OPT_INVALID_PARAM); + config.SetSecurityType(KeyMgmt::WPA_EAP); + EXPECT_TRUE(IsValidHotspotConfig(config, centerConfig, bands, table) == ErrCode::WIFI_OPT_INVALID_PARAM); + config.SetSecurityType(KeyMgmt::IEEE8021X); + EXPECT_TRUE(IsValidHotspotConfig(config, centerConfig, bands, table) == ErrCode::WIFI_OPT_INVALID_PARAM); + config.SetSecurityType(KeyMgmt::OSEN); + EXPECT_TRUE(IsValidHotspotConfig(config, centerConfig, bands, table) == ErrCode::WIFI_OPT_INVALID_PARAM); + config.SetSecurityType(KeyMgmt::FT_PSK); + EXPECT_TRUE(IsValidHotspotConfig(config, centerConfig, bands, table) == ErrCode::WIFI_OPT_INVALID_PARAM); + config.SetSecurityType(KeyMgmt::WPA2_PSK); + config.SetPreSharedKey(""); + EXPECT_TRUE(IsValidHotspotConfig(config, centerConfig, bands, table) == ErrCode::WIFI_OPT_INVALID_PARAM); + config.SetPreSharedKey("12345678"); + centerConfig.SetChannel(1024); + EXPECT_TRUE(IsValidHotspotConfig(config, centerConfig, bands, table) == ErrCode::WIFI_OPT_INVALID_PARAM); + config.SetChannel(1024); + EXPECT_TRUE(IsValidHotspotConfig(config, centerConfig, bands, table) == ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiGlobalFuncTest, GetRandomStr, TestSize.Level1) +{ + std::string str = GetRandomStr(0); + EXPECT_TRUE(str.length() == 0); + str = GetRandomStr(1); + EXPECT_TRUE(str.length() == 1); + str = GetRandomStr(MAX_PSK_LEN); + EXPECT_TRUE(str.length() == MAX_PSK_LEN); + str = GetRandomStr(MAX_PSK_LEN + 1); + EXPECT_TRUE(str.length() == MAX_PSK_LEN); +} + +HWTEST_F(WifiGlobalFuncTest, CheckMacIsValid, TestSize.Level1) +{ + std::string str; + EXPECT_TRUE(CheckMacIsValid(str) == -1); + str = "00:00:00:00:00:00"; + EXPECT_TRUE(CheckMacIsValid(str) == 0); + str = "ah:00:00:00:00:00"; + EXPECT_TRUE(CheckMacIsValid(str) == -1); + str = "AH:00:00:00:00:00"; + EXPECT_TRUE(CheckMacIsValid(str) == -1); + str = "00.00.00.00.00.00"; + EXPECT_TRUE(CheckMacIsValid(str) == -1); +} + +HWTEST_F(WifiGlobalFuncTest, ConvertConnStateInternalTest, TestSize.Level1) +{ + EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_CONNECTING) == ConnectionState::CONNECT_CONNECTING); + EXPECT_TRUE( + ConvertConnStateInternal(OperateResState::CONNECT_AP_CONNECTED) == ConnectionState::CONNECT_AP_CONNECTED); + EXPECT_TRUE( + ConvertConnStateInternal(OperateResState::CONNECT_CHECK_PORTAL) == ConnectionState::CONNECT_CHECK_PORTAL); + EXPECT_TRUE( + ConvertConnStateInternal(OperateResState::CONNECT_NETWORK_ENABLED) == ConnectionState::CONNECT_NETWORK_ENABLED); + EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_NETWORK_DISABLED) == + ConnectionState::CONNECT_NETWORK_DISABLED); + EXPECT_TRUE(ConvertConnStateInternal(OperateResState::DISCONNECT_DISCONNECTING) == + ConnectionState::DISCONNECT_DISCONNECTING); + EXPECT_TRUE(ConvertConnStateInternal(OperateResState::DISCONNECT_DISCONNECT_FAILED) == + ConnectionState::DISCONNECT_DISCONNECT_FAILED); + EXPECT_TRUE( + ConvertConnStateInternal(OperateResState::DISCONNECT_DISCONNECTED) == ConnectionState::DISCONNECT_DISCONNECTED); + EXPECT_TRUE( + ConvertConnStateInternal(OperateResState::CONNECT_PASSWORD_WRONG) == ConnectionState::CONNECT_PASSWORD_WRONG); + EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_CONNECTING_TIMEOUT) == + ConnectionState::CONNECT_CONNECTING_TIMEOUT); + EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_OBTAINING_IP_FAILED) == + ConnectionState::CONNECT_OBTAINING_IP_FAILED); + EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_ASSOCIATING) == ConnectionState::CONNECT_ASSOCIATING); + EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_ASSOCIATED) == ConnectionState::CONNECT_ASSOCIATED); + EXPECT_TRUE(ConvertConnStateInternal(OperateResState::OPEN_WIFI_SUCCEED) == ConnectionState::UNKNOWN); + EXPECT_TRUE( + ConvertConnStateInternal(OperateResState::CONNECT_OBTAINING_IP) == ConnectionState::CONNECT_OBTAINING_IP); + EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_SELECT_NETWORK_FAILED) == ConnectionState::UNKNOWN); +} + +HWTEST_F(WifiGlobalFuncTest, SplitStringTest, TestSize.Level1) +{ + std::string str = "upnp 10 uuid:xxxxxxxxxxxxx-xxxxx"; + std::vector vec; + OHOS::Wifi::SplitString(str, "", vec); + ASSERT_TRUE(vec.size() == 1); + EXPECT_TRUE(vec[0] == str); + vec.clear(); + OHOS::Wifi::SplitString(str, " ", vec); + ASSERT_TRUE(vec.size() == 3); + EXPECT_TRUE(vec[0] == "upnp"); + EXPECT_TRUE(vec[1] == "10"); + EXPECT_TRUE(vec[2] == "uuid:xxxxxxxxxxxxx-xxxxx"); +} + +HWTEST_F(WifiGlobalFuncTest, Vec2StreamTest, TestSize.Level1) +{ + std::string prefix = "head|"; + std::vector vecChar; + std::string sufffix = "|tail"; + std::string result = OHOS::Wifi::Vec2Stream(prefix, vecChar, sufffix); + std::string expect = "head||tail"; + EXPECT_TRUE(result == expect); + char tmp = (char)255; + vecChar.push_back(tmp); + result = OHOS::Wifi::Vec2Stream(prefix, vecChar, sufffix); + expect = "head|FF |tail"; + EXPECT_TRUE(result == expect); + tmp = (char)0; + vecChar.push_back(tmp); + result = OHOS::Wifi::Vec2Stream(prefix, vecChar, sufffix); + expect = "head|FF 00 |tail"; + EXPECT_TRUE(result == expect); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_global_func_test.h b/tests/wifi_standard/wifi_framework/common/unittest/wifi_global_func_test.h new file mode 100644 index 000000000..07fd8d3b3 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/common/unittest/wifi_global_func_test.h @@ -0,0 +1,37 @@ +/* + * 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_WIFI_GLOBAL_FUNC_TEST_H +#define OHOS_WIFI_GLOBAL_FUNC_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiGlobalFuncTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_ip_tools_test.cpp b/tests/wifi_standard/wifi_framework/common/unittest/wifi_ip_tools_test.cpp new file mode 100644 index 000000000..8496eaad3 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/common/unittest/wifi_ip_tools_test.cpp @@ -0,0 +1,110 @@ +/* + * 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 "wifi_ip_tools_test.h" +#include +#include "securec.h" +#include "ip_tools.h" +#include "network_interface.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiIpToolsTest, ConvertIpv4AddressTest, TestSize.Level1) +{ + EXPECT_TRUE(IpTools::ConvertIpv4Address(0) == ""); + EXPECT_TRUE(IpTools::ConvertIpv4Address(0xc0a80001) == "192.168.0.1"); + EXPECT_TRUE(IpTools::ConvertIpv4Address("") == 0); + EXPECT_TRUE(IpTools::ConvertIpv4Address("192:168:0:1") == 0); + EXPECT_TRUE(IpTools::ConvertIpv4Address("192.168:0.1") == 0); + EXPECT_TRUE(IpTools::ConvertIpv4Address("289.168.0.1") == 0); + EXPECT_TRUE(IpTools::ConvertIpv4Address("-1.168.0.1") == 0); + EXPECT_TRUE(IpTools::ConvertIpv4Address("192.168.0.1") == 0xc0a80001); +} + +HWTEST_F(WifiIpToolsTest, ConvertIpv6AddressTest, TestSize.Level1) +{ + std::vector tmp; + EXPECT_TRUE(IpTools::ConvertIpv6Address(tmp) == ""); + // 2001:0db8:3c4d:0015:0000:0000:1a2f:1a2b + tmp.push_back(0x20); + tmp.push_back(0x01); + tmp.push_back(0x0d); + tmp.push_back(0xb8); + tmp.push_back(0x3c); + tmp.push_back(0x4d); + tmp.push_back(0x00); + tmp.push_back(0x15); + tmp.push_back(0x00); + tmp.push_back(0x00); + tmp.push_back(0x00); + tmp.push_back(0x00); + tmp.push_back(0x1a); + tmp.push_back(0x2f); + tmp.push_back(0x1a); + EXPECT_TRUE(IpTools::ConvertIpv6Address(tmp) == ""); + tmp.push_back(0x2b); + EXPECT_TRUE(IpTools::ConvertIpv6Address(tmp) == "2001:0db8:3c4d:0015:0000:0000:1a2f:1a2b"); + + std::vector addr; + IpTools::ConvertIpv6Address("", addr); + EXPECT_TRUE(addr.size() == 0); + std::string ipv6Str = "2001:0db8:3c4d:15:0000:0000:1a2f:1a2b"; + IpTools::ConvertIpv6Address(ipv6Str, addr); + EXPECT_TRUE(addr.size() == 0); + ipv6Str = "2001:0db8:3c4d:0000:0000:1a2f:1a2b"; + IpTools::ConvertIpv6Address(ipv6Str, addr); + EXPECT_TRUE(addr.size() == 0); + ipv6Str = "2001:0db8:3c4d:0015:0000:0000:1a2f:1a2b"; + IpTools::ConvertIpv6Address(ipv6Str, addr); + EXPECT_TRUE(addr == tmp); +} + +HWTEST_F(WifiIpToolsTest, ConvertIpv4MaskTest, TestSize.Level1) +{ + EXPECT_TRUE(IpTools::ConvertIpv4Mask(-1) == ""); + EXPECT_TRUE(IpTools::ConvertIpv4Mask(33) == ""); + EXPECT_TRUE(IpTools::ConvertIpv4Mask(0) == "0.0.0.0"); + EXPECT_TRUE(IpTools::ConvertIpv4Mask(32) == "255.255.255.255"); + EXPECT_TRUE(IpTools::ConvertIpv4Mask(11) == "255.224.0.0"); +} + +HWTEST_F(WifiIpToolsTest, ConvertIpv6MaskTest, TestSize.Level1) +{ + EXPECT_TRUE(IpTools::ConvertIpv6Mask(-1) == ""); + EXPECT_TRUE(IpTools::ConvertIpv6Mask(129) == ""); + EXPECT_TRUE(IpTools::ConvertIpv6Mask(0) == "0"); + EXPECT_TRUE(IpTools::ConvertIpv6Mask(128) == "128"); +} + +HWTEST_F(WifiIpToolsTest, GetMaskLengthTest, TestSize.Level1) +{ + EXPECT_EQ(IpTools::GetMaskLength("255.0.0.0"), 8); +} + +HWTEST_F(WifiIpToolsTest, GetExclusionObjectListTest, TestSize.Level1) +{ + std::string str = "a,b,c"; + std::vector vec; + IpTools::GetExclusionObjectList(str, vec); + EXPECT_TRUE(vec.size() == 3); + str = "abc"; + vec.clear(); + IpTools::GetExclusionObjectList(str, vec); + EXPECT_TRUE(vec.size() == 1); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_ip_tools_test.h b/tests/wifi_standard/wifi_framework/common/unittest/wifi_ip_tools_test.h new file mode 100644 index 000000000..65071679e --- /dev/null +++ b/tests/wifi_standard/wifi_framework/common/unittest/wifi_ip_tools_test.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_WIFI_IP_TOOLS_TEST_H +#define OHOS_WIFI_IP_TOOLS_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiIpToolsTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_log_helper_test.cpp b/tests/wifi_standard/wifi_framework/common/unittest/wifi_log_helper_test.cpp new file mode 100644 index 000000000..e5e77f81a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/common/unittest/wifi_log_helper_test.cpp @@ -0,0 +1,49 @@ +/* + * 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 "wifi_log_helper_test.h" +#include "log_helper.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiLogHelperTest, EncryptLogMsgTest, TestSize.Level1) +{ + char msg[32] = {0}; + EncryptLogMsg("", msg, sizeof(msg)); + EXPECT_TRUE(msg == std::string("")); + EncryptLogMsg("a", msg, sizeof(msg)); + EXPECT_TRUE(msg == std::string("*")); + EncryptLogMsg("ab", msg, sizeof(msg)); + EXPECT_TRUE(msg == std::string("**")); + EncryptLogMsg("abc", msg, sizeof(msg)); + EXPECT_TRUE(msg == std::string("a*c")); + EncryptLogMsg("abcd", msg, sizeof(msg)); + EXPECT_TRUE(msg == std::string("a**d")); + EncryptLogMsg("abcde", msg, sizeof(msg)); + EXPECT_TRUE(msg == std::string("ab*de")); + EncryptLogMsg("abcdef", msg, sizeof(msg)); + EXPECT_TRUE(msg == std::string("ab**ef")); + EncryptLogMsg("abcdefg", msg, sizeof(msg)); + EXPECT_TRUE(msg == std::string("abc*efg")); + EncryptLogMsg("abcdefgh", msg, sizeof(msg)); + EXPECT_TRUE(msg == std::string("abc**fgh")); + EncryptLogMsg("abcdefghi", msg, sizeof(msg)); + EXPECT_TRUE(msg == std::string("abc***ghi")); + EncryptLogMsg("abcdefghij", msg, sizeof(msg)); + EXPECT_TRUE(msg == std::string("abc****hij")); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_log_helper_test.h b/tests/wifi_standard/wifi_framework/common/unittest/wifi_log_helper_test.h new file mode 100644 index 000000000..514c110bd --- /dev/null +++ b/tests/wifi_standard/wifi_framework/common/unittest/wifi_log_helper_test.h @@ -0,0 +1,37 @@ +/* + * 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_WIFI_LOG_HELPER_TEST_H +#define OHOS_WIFI_LOG_HELPER_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiLogHelperTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_network_interface_test.cpp b/tests/wifi_standard/wifi_framework/common/unittest/wifi_network_interface_test.cpp new file mode 100644 index 000000000..4679688ce --- /dev/null +++ b/tests/wifi_standard/wifi_framework/common/unittest/wifi_network_interface_test.cpp @@ -0,0 +1,60 @@ +/* + * 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 "wifi_network_interface_test.h" +#include "network_interface.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiNetworkInterfaceTest, IsValidInterfaceNameTest, TestSize.Level1) +{ + std::string ifaceName; + EXPECT_TRUE(NetworkInterface::IsValidInterfaceName(ifaceName) == false); + ifaceName = "01234567890123450"; + EXPECT_TRUE(NetworkInterface::IsValidInterfaceName(ifaceName) == false); + ifaceName = "0123456789012345"; + EXPECT_TRUE(NetworkInterface::IsValidInterfaceName(ifaceName) == true); + ifaceName = "_123456789012345"; + EXPECT_TRUE(NetworkInterface::IsValidInterfaceName(ifaceName) == false); + ifaceName = "012345678901234?"; + EXPECT_TRUE(NetworkInterface::IsValidInterfaceName(ifaceName) == false); +} + +HWTEST_F(WifiNetworkInterfaceTest, FetchInterfaceConfigTest, TestSize.Level1) +{ + std::vector vecIPv4; + std::vector vecIPv6; + EXPECT_TRUE(NetworkInterface::FetchInterfaceConfig("wlan0", vecIPv4, vecIPv6) == true); + NetworkInterface::Dump("wlan0"); +} + +HWTEST_F(WifiNetworkInterfaceTest, AddDelIpAddressTest, TestSize.Level1) +{ + Ipv4Address ip = Ipv4Address::Create("10.0.0.1", "255.255.255.0"); + EXPECT_TRUE(NetworkInterface::AddIpAddress("wlan0", ip) == true); + EXPECT_TRUE(NetworkInterface::IsExistAddressForInterface("wlan0", ip) == true); + Ipv4Address ip2 = Ipv4Address::Create("10.0.0.2", "255.255.255.0"); + EXPECT_TRUE(NetworkInterface::IsExistAddressForInterface("wlan0", ip2) == false); + std::vector vecIpv4; + EXPECT_TRUE(NetworkInterface::GetIpv4Address("wlan0", vecIpv4) == true); + Ipv6Address ipv6 = Ipv6Address::Create("fe80::47b1:fa81:b33e:ea6b/64"); + EXPECT_TRUE(ipv6.IsValid() == true); + std::vector vecIpv6; + EXPECT_TRUE(NetworkInterface::GetAllIpv6Address("wlan0", vecIpv6) == true); + EXPECT_TRUE(NetworkInterface::ClearAllIpAddress("wlan0") == true); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_network_interface_test.h b/tests/wifi_standard/wifi_framework/common/unittest/wifi_network_interface_test.h new file mode 100644 index 000000000..73a89c2df --- /dev/null +++ b/tests/wifi_standard/wifi_framework/common/unittest/wifi_network_interface_test.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_WIFI_NETWORK_INTERFACE_TEST_H +#define OHOS_WIFI_NETWORK_INTERFACE_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiNetworkInterfaceTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/BUILD.gn b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/BUILD.gn new file mode 100644 index 000000000..ee7b983a9 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/BUILD.gn @@ -0,0 +1,105 @@ +# 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. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +################################################################################ + +SUBSYSTEM_DIR = "//foundation/communication" +module_output_path = "wifi_standard/dhcp_client_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/test", + ] +} + +ohos_unittest("dhcp_client_unittest") { + module_out_path = module_output_path + sources = [ + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_api.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_client.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_function.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_ipv4.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_options.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_socket.c", + "dhcp_client_test.cpp", + "dhcp_function_test.cpp", + "dhcp_ipv4_test.cpp", + "dhcp_main_test.cpp", + "dhcp_options_test.cpp", + "dhcp_socket_test.cpp", + "global_test.cpp", + "mock_custom_func.cpp", + "mock_system_func.cpp", + ] + + include_dirs = [ + "//third_party/googletest/googlemock/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/test", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", + "//utils/native/base/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//third_party/openssl/include", + ] + + deps = [ + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "//third_party/googletest:gmock_main", + "//third_party/openssl:libcrypto_static", + "//utils/native/base:utils", + ] + + ldflags = [ + "-fPIC", + "-Wl,-E", + "--coverage", + "-Wl,-rpath=/vendor/lib64/hw", + "-Wl,--wrap=open", + "-Wl,--wrap=close", + "-Wl,--wrap=write", + "-Wl,--wrap=read", + "-Wl,--wrap=socket", + "-Wl,--wrap=setsockopt", + "-Wl,--wrap=ioctl", + "-Wl,--wrap=bind", + "-Wl,--wrap=listen", + "-Wl,--wrap=connect", + "-Wl,--wrap=select", + "-Wl,--wrap=sendto", + "-Wl,--wrap=GetDhcpRawPacket", + "-Wl,--wrap=GetDhcpKernelPacket", + "-Wl,--wrap=GetSelectRet", + ] + + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + ] + configs = [ ":module_private_config" ] + + part_name = "wifi_standard" + subsystem_name = "communication" + testonly = true +} + +group("unittest") { + testonly = true + deps = [ ":dhcp_client_unittest" ] +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_client_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_client_test.cpp new file mode 100644 index 000000000..2c2a51ca8 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_client_test.cpp @@ -0,0 +1,100 @@ +/* + * 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 "wifi_log.h" +#include "dhcp_client.h" +#include "dhcp_function.h" +#include "securec.h" + +using namespace testing::ext; + +namespace OHOS { +class DhcpClientFuncTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; + +HWTEST_F(DhcpClientFuncTest, StartProcess_SUCCESS, TestSize.Level1) +{ + struct DhcpClientCfg *pCfg = GetDhcpClientCfg(); + ASSERT_TRUE(strncpy_s(pCfg->workDir, DIR_MAX_LEN, "./", DIR_MAX_LEN - 1) == EOK); + ASSERT_TRUE(strncpy_s(pCfg->ifaceName, INFNAME_SIZE, "wlan0", INFNAME_SIZE - 1) == EOK); + ASSERT_TRUE(snprintf_s(pCfg->confFile, DIR_MAX_LEN, DIR_MAX_LEN - 1, "%s%s", pCfg->workDir, DHCPC_CONF) >= 0); + ASSERT_TRUE( + snprintf_s(pCfg->pidFile, DIR_MAX_LEN, DIR_MAX_LEN - 1, "%s%s.pid", pCfg->workDir, pCfg->ifaceName) >= 0); + ASSERT_TRUE( + snprintf_s(pCfg->resultFile, DIR_MAX_LEN, DIR_MAX_LEN - 1, "%s%s.result", pCfg->workDir, pCfg->ifaceName) >= 0); + ASSERT_TRUE( + snprintf_s(pCfg->result6File, DIR_MAX_LEN, DIR_MAX_LEN - 1, "%s%s.result6", pCfg->workDir, pCfg->ifaceName) >= 0); + ASSERT_TRUE( + snprintf_s(pCfg->leaseFile, DIR_MAX_LEN, DIR_MAX_LEN - 1, "%s%s.lease", pCfg->workDir, pCfg->ifaceName) >= 0); + pCfg->getMode = DHCP_IP_TYPE_ALL; + + EXPECT_EQ(DHCP_OPT_SUCCESS, GetLocalInterface(pCfg->ifaceName, &pCfg->ifaceIndex, pCfg->ifaceMac, NULL)); + + /* Generate format: 1 + ifaceMac. */ + if (pCfg->pOptClientId != NULL) { + free(pCfg->pOptClientId); + pCfg->pOptClientId = NULL; + } + pCfg->pOptClientId = (unsigned char *)malloc(DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + MAC_ADDR_LEN + 1); + ASSERT_TRUE(pCfg->pOptClientId != NULL); + pCfg->pOptClientId[DHCP_OPT_CODE_INDEX] = CLIENT_IDENTIFIER_OPTION; + pCfg->pOptClientId[DHCP_OPT_LEN_INDEX] = MAC_ADDR_LEN + 1; + pCfg->pOptClientId[DHCP_OPT_DATA_INDEX] = NUMBER_ONE; + ASSERT_TRUE( + memcpy_s(pCfg->pOptClientId + DHCP_OPT_DATA_INDEX + 1, MAC_ADDR_LEN, pCfg->ifaceMac, MAC_ADDR_LEN) == EOK); + pCfg->timeoutExit = true; + + EXPECT_EQ(DHCP_OPT_SUCCESS, StartProcess()); +} + +HWTEST_F(DhcpClientFuncTest, GetProStatus_SUCCESS, TestSize.Level1) +{ + char workDir[DIR_MAX_LEN] = "./"; + char pidFile[DIR_MAX_LEN] = "./wlan0.pid"; + ASSERT_EQ(DHCP_OPT_SUCCESS, InitPidfile(workDir, pidFile, getpid())); + + EXPECT_EQ(1, GetProStatus(pidFile)); + unlink(pidFile); +} + +HWTEST_F(DhcpClientFuncTest, GetProStatus_FAILED, TestSize.Level1) +{ + char pidFile[DIR_MAX_LEN] = "./wlan0.pid"; + EXPECT_EQ(0, GetProStatus(pidFile)); +} + +HWTEST_F(DhcpClientFuncTest, StopProcess_SUCCESS, TestSize.Level1) +{ + char pidFile[DIR_MAX_LEN] = "./wlan0.pid"; + EXPECT_EQ(DHCP_OPT_SUCCESS, StopProcess(pidFile)); + + char workDir[DIR_MAX_LEN] = "./"; + pid_t testPid = 12345; + ASSERT_EQ(DHCP_OPT_SUCCESS, InitPidfile(workDir, pidFile, testPid)); + + EXPECT_EQ(DHCP_OPT_SUCCESS, StopProcess(pidFile)); + unlink(pidFile); +} +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_function_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_function_test.cpp new file mode 100644 index 000000000..3925c1150 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_function_test.cpp @@ -0,0 +1,191 @@ +/* + * 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 "wifi_log.h" +#include "dhcp_function.h" +#include "dhcp_client.h" +#include "mock_system_func.h" + +using namespace testing::ext; + +namespace OHOS { +class DhcpFunctionTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; + +HWTEST_F(DhcpFunctionTest, Ip4StrConToInt_SUCCESS, TestSize.Level1) +{ + char serIp[INET_ADDRSTRLEN] = "192.77.1.231"; + uint32_t uSerIp = 0; + EXPECT_EQ(true, Ip4StrConToInt(serIp, &uSerIp, true)); +} + +HWTEST_F(DhcpFunctionTest, Ip4StrConToInt_FAILED, TestSize.Level1) +{ + char serIp[INET_ADDRSTRLEN] = {0}; + uint32_t uSerIp = 0; + EXPECT_EQ(false, Ip4StrConToInt(serIp, &uSerIp, true)); + + char serIp1[INET_ADDRSTRLEN] = "192.77.231"; + uint32_t uSerIp1 = 0; + EXPECT_EQ(false, Ip4StrConToInt(serIp1, &uSerIp1, true)); +} + +HWTEST_F(DhcpFunctionTest, Ip4IntConToStr_SUCCESS, TestSize.Level1) +{ + uint32_t uSerIp = 3226272231; + char *pSerIp = Ip4IntConToStr(uSerIp, true); + ASSERT_NE(pSerIp, nullptr); + free(pSerIp); +} + +HWTEST_F(DhcpFunctionTest, Ip6StrConToChar_SUCCESS, TestSize.Level1) +{ + char serIp[INET6_ADDRSTRLEN] = "2001:db8:0:1::231"; + uint8_t addr6[sizeof(struct in6_addr)] = {0}; + EXPECT_EQ(true, Ip6StrConToChar(serIp, addr6, sizeof(addr6))); +} + +HWTEST_F(DhcpFunctionTest, Ip6StrConToChar_FAILED, TestSize.Level1) +{ + char serIp[INET6_ADDRSTRLEN] = {0}; + uint8_t addr6[sizeof(struct in6_addr)] = {0}; + EXPECT_EQ(false, Ip6StrConToChar(serIp, addr6, sizeof(addr6))); + + char serIp1[INET6_ADDRSTRLEN] = "231"; + uint8_t addr61[sizeof(struct in6_addr)] = {0}; + EXPECT_EQ(false, Ip6StrConToChar(serIp1, addr61, sizeof(addr61))); +} + +HWTEST_F(DhcpFunctionTest, MacChConToMacStr_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(nullptr, MacChConToMacStr(NULL, 0, NULL, 0)); + + char interface[INFNAME_SIZE] = "wlan0"; + int ifindex; + unsigned char hwaddr[MAC_ADDR_LEN]; + ASSERT_EQ(GetLocalInterface(interface, &ifindex, hwaddr, NULL), DHCP_OPT_SUCCESS); + EXPECT_EQ(nullptr, MacChConToMacStr(hwaddr, MAC_ADDR_LEN, NULL, 0)); + + char buf[MAC_ADDR_LEN * MAC_ADDR_CHAR_NUM] = {0}; + EXPECT_NE(nullptr, MacChConToMacStr(hwaddr, MAC_ADDR_LEN, buf, sizeof(buf))); +} + +HWTEST_F(DhcpFunctionTest, GetLocalInterface_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(GetLocalInterface(NULL, NULL, NULL, NULL), DHCP_OPT_FAILED); + + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), ioctl(_, _, _)) + .WillOnce(Return(-1)) + .WillOnce(Return(0)).WillOnce(Return(-1)) + .WillOnce(Return(0)).WillOnce(Return(0)).WillOnce(Return(-1)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + + char interface[INFNAME_SIZE] = "wlan0"; + EXPECT_EQ(GetLocalInterface(interface, NULL, NULL, NULL), DHCP_OPT_FAILED); + int ifindex = 0; + EXPECT_EQ(GetLocalInterface(interface, &ifindex, NULL, NULL), DHCP_OPT_FAILED); + unsigned char hwaddr[MAC_ADDR_LEN]; + EXPECT_EQ(GetLocalInterface(interface, &ifindex, hwaddr, NULL), DHCP_OPT_FAILED); + uint32_t ifaddr4; + EXPECT_EQ(GetLocalInterface(interface, &ifindex, hwaddr, &ifaddr4), DHCP_OPT_FAILED); + EXPECT_EQ(GetLocalInterface(interface, &ifindex, hwaddr, &ifaddr4), DHCP_OPT_SUCCESS); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpFunctionTest, GetLocalIp_SUCCESS, TestSize.Level1) +{ + char interface[INFNAME_SIZE] = "wlan0"; + uint32_t ipaddr4; + EXPECT_EQ(DHCP_OPT_SUCCESS, GetLocalIp(interface, &ipaddr4)); +} + +HWTEST_F(DhcpFunctionTest, GetLocalIp_FAILED, TestSize.Level1) +{ + char interface[INFNAME_SIZE] = {0}; + uint32_t ipaddr4; + EXPECT_EQ(DHCP_OPT_FAILED, GetLocalIp(interface, &ipaddr4)); +} + +HWTEST_F(DhcpFunctionTest, SetLocalInterface_SUCCESS, TestSize.Level1) +{ + char interface[INFNAME_SIZE] = "wlan0"; + uint32_t ipaddr4 = 3226272231; + EXPECT_EQ(DHCP_OPT_SUCCESS, SetLocalInterface(interface, ipaddr4)); +} + +HWTEST_F(DhcpFunctionTest, SetLocalInterface_FAILED, TestSize.Level1) +{ + char interface[INFNAME_SIZE] = {0}; + uint32_t ipaddr4 = 0; + EXPECT_EQ(DHCP_OPT_FAILED, SetLocalInterface(interface, ipaddr4)); + + EXPECT_EQ(DHCP_OPT_FAILED, SetLocalInterface("wlan", ipaddr4)); +} + +HWTEST_F(DhcpFunctionTest, InitPidfile_SUCCESS, TestSize.Level1) +{ + char workDir[DIR_MAX_LEN] = "./"; + char pidFile[DIR_MAX_LEN] = "./wlan0.pid"; + + EXPECT_EQ(DHCP_OPT_SUCCESS, InitPidfile(workDir, pidFile, getpid())); + unlink(pidFile); + usleep(SLEEP_TIME_200_MS); +} + +HWTEST_F(DhcpFunctionTest, InitPidfile_FAILED, TestSize.Level1) +{ + char workDir[DIR_MAX_LEN] = {0}; + char pidFile[DIR_MAX_LEN] = {0}; + EXPECT_EQ(DHCP_OPT_FAILED, InitPidfile(workDir, pidFile, getpid())); + + EXPECT_EQ(DHCP_OPT_FAILED, InitPidfile("./", "./test/wlan0.pid", getpid())); + + EXPECT_EQ(DHCP_OPT_FAILED, InitPidfile("./test/", "./wlan0.pid", getpid())); +} + +HWTEST_F(DhcpFunctionTest, GetPID_SUCCESS, TestSize.Level1) +{ + char workDir[DIR_MAX_LEN] = "./"; + char pidFile[DIR_MAX_LEN] = "./wlan0.pid"; + + EXPECT_EQ(DHCP_OPT_SUCCESS, InitPidfile(workDir, pidFile, getpid())); + EXPECT_GT(GetPID(pidFile), 0); + unlink(pidFile); +} + +HWTEST_F(DhcpFunctionTest, CreateDirs_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(DHCP_OPT_FAILED, CreateDirs(NULL, 0)); + + const char *path = "test"; + EXPECT_EQ(DHCP_OPT_SUCCESS, CreateDirs(path, S_IRWXU)); + rmdir(path); +} +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_ipv4_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_ipv4_test.cpp new file mode 100644 index 000000000..95797fc9a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_ipv4_test.cpp @@ -0,0 +1,180 @@ +/* + * 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 "mock_system_func.h" +#include "mock_custom_func.h" +#include "wifi_log.h" +#include "dhcp_ipv4.h" +#include "dhcp_client.h" +#include "dhcp_function.h" + +using namespace testing::ext; + +namespace OHOS { +class DhcpIpv4Test : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; +#if 0 +HWTEST_F(DhcpIpv4Test, StartIpv4_Mock1, TestSize.Level1) +{ + MockSystemFunc::SetMockFlag(true); + MockCustomFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), setsockopt(_, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), bind(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), select(_, _, _, _, _)) + .WillOnce(Return(-1)).WillOnce(Return(1)) + .WillOnce(Return(0)).WillOnce(Return(1)).WillOnce(Return(1)) + .WillOnce(Return(0)).WillOnce(Return(1)) + .WillOnce(Return(0)).WillOnce(Return(1)) + .WillOnce(Return(3)).WillOnce(Return(1)).WillOnce(Return(2)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), sendto(_, _, _, _, _, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), read(_, _, _)).WillRepeatedly(Return(500)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), open(_, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), ioctl(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), connect(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), write(_, _, _)).WillRepeatedly(Return(1)); + + EXPECT_CALL(MockCustomFunc::GetInstance(), GetDhcpRawPacket(_, _)) + .WillOnce(Return(SOCKET_OPT_ERROR)) + .WillOnce(Return(1)) + .WillOnce(Return(2)) + .WillRepeatedly(Return(SOCKET_OPT_SUCCESS)); + EXPECT_CALL(MockCustomFunc::GetInstance(), GetDhcpKernelPacket(_, _)) + .WillOnce(Return(2)) + .WillOnce(Return(3)) + .WillRepeatedly(Return(SOCKET_OPT_SUCCESS)); + + struct DhcpClientCfg *pCfg = GetDhcpClientCfg(); + pCfg->timeoutExit = false; + EXPECT_EQ(DHCP_OPT_SUCCESS, StartIpv4()); + + MockSystemFunc::SetMockFlag(false); + MockCustomFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpIpv4Test, StartIpv4_Mock2, TestSize.Level1) +{ + MockSystemFunc::SetMockFlag(true); + MockCustomFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), setsockopt(_, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), bind(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), select(_, _, _, _, _)) + .WillOnce(Return(0)).WillOnce(Return(1)) + .WillOnce(Return(0)).WillOnce(Return(1)).WillOnce(Return(1)) + .WillOnce(Return(0)).WillOnce(Return(1)) + .WillOnce(Return(0)).WillOnce(Return(1)).WillOnce(Return(0)).WillOnce(Return(0)) + .WillOnce(Return(2)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), sendto(_, _, _, _, _, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), read(_, _, _)).WillRepeatedly(Return(500)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), open(_, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), ioctl(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), connect(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), write(_, _, _)).WillRepeatedly(Return(1)); + + EXPECT_CALL(MockCustomFunc::GetInstance(), GetDhcpRawPacket(_, _)) + .WillOnce(Return(3)) + .WillOnce(Return(1)).WillOnce(Return(4)) + .WillRepeatedly(Return(SOCKET_OPT_SUCCESS)); + EXPECT_CALL(MockCustomFunc::GetInstance(), GetDhcpKernelPacket(_, _)) + .WillOnce(Return(1)) + .WillOnce(Return(2)) + .WillRepeatedly(Return(SOCKET_OPT_SUCCESS)); + + struct DhcpClientCfg *pCfg = GetDhcpClientCfg(); + pCfg->timeoutExit = false; + EXPECT_EQ(DHCP_OPT_SUCCESS, StartIpv4()); + + MockSystemFunc::SetMockFlag(false); + MockCustomFunc::SetMockFlag(false); +} +#endif +HWTEST_F(DhcpIpv4Test, ExecDhcpRenew_SUCCESS, TestSize.Level1) +{ + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + + SetIpv4State(DHCP_STATE_INIT); + EXPECT_EQ(DHCP_OPT_SUCCESS, ExecDhcpRenew()); + SetIpv4State(DHCP_STATE_REQUESTING); + EXPECT_EQ(DHCP_OPT_SUCCESS, ExecDhcpRenew()); + SetIpv4State(DHCP_STATE_BOUND); + EXPECT_EQ(DHCP_OPT_SUCCESS, ExecDhcpRenew()); + SetIpv4State(DHCP_STATE_RENEWING); + EXPECT_EQ(DHCP_OPT_SUCCESS, ExecDhcpRenew()); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpIpv4Test, ExecDhcpRelease_SUCCESS, TestSize.Level1) +{ + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), setsockopt(_, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), bind(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), open(_, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), read(_, _, _)).WillRepeatedly(Return(500)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), connect(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), write(_, _, _)).WillRepeatedly(Return(1)); + + SetIpv4State(DHCP_STATE_BOUND); + EXPECT_EQ(DHCP_OPT_SUCCESS, ExecDhcpRelease()); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpIpv4Test, TEST_FAILED, TestSize.Level1) +{ + EXPECT_EQ(DHCP_OPT_FAILED, SetIpv4State(-1)); + EXPECT_EQ(DHCP_OPT_FAILED, GetPacketHeaderInfo(NULL, 0)); + EXPECT_EQ(DHCP_OPT_FAILED, GetPacketCommonInfo(NULL)); +} + +HWTEST_F(DhcpIpv4Test, TEST_SUCCESS, TestSize.Level1) +{ + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), bind(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), sendto(_, _, _, _, _, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + + EXPECT_EQ(DHCP_OPT_SUCCESS, DhcpDiscover(0, 1)); + EXPECT_EQ(DHCP_OPT_SUCCESS, DhcpRenew(0, 0, 0)); + + MockSystemFunc::SetMockFlag(false); +} +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_main_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_main_test.cpp new file mode 100644 index 000000000..37c317ffd --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_main_test.cpp @@ -0,0 +1,27 @@ +/* + * 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 "global_test.h" + +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + testing::InitGoogleMock(&argc, argv); + testing::Environment *env = new GlobalTest(); + testing::AddGlobalTestEnvironment(env); + return RUN_ALL_TESTS(); +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_options_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_options_test.cpp new file mode 100644 index 000000000..4a1ea8035 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_options_test.cpp @@ -0,0 +1,378 @@ +/* + * 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 "wifi_log.h" +#include "dhcp_options.h" +#include "dhcp_client.h" +#include "securec.h" + +#include +#include +#include + +using namespace testing::ext; + +namespace OHOS { +class DhcpOptionsTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; + +HWTEST_F(DhcpOptionsTest, GetDhcpOptionDataLen_SUCCESS, TestSize.Level1) +{ + EXPECT_GT(GetDhcpOptionDataLen(DHCP_MESSAGE_TYPE_OPTION), 0); +} + +HWTEST_F(DhcpOptionsTest, GetDhcpOptionDataLen_FAILED, TestSize.Level1) +{ + EXPECT_EQ(GetDhcpOptionDataLen(PAD_OPTION), 0); + EXPECT_EQ(GetDhcpOptionDataLen(CLIENT_IDENTIFIER_OPTION), 0); + EXPECT_EQ(GetDhcpOptionDataLen(DOMAIN_NAME_SERVER_OPTION), 0); +} + +HWTEST_F(DhcpOptionsTest, GetDhcpOption_SUCCESS, TestSize.Level1) +{ + struct DhcpPacket packet; + ASSERT_TRUE(memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) == EOK); + + int endIndex = 0; + uint8_t *pOption = packet.options; + pOption[endIndex + DHCP_OPT_CODE_INDEX] = PAD_OPTION; + endIndex += DHCP_OPT_CODE_BYTES; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = SUBNET_MASK_OPTION; + pOption[endIndex + DHCP_OPT_LEN_INDEX] = DHCP_UINT32_BYTES; + uint32_t u32Data = 3226272231; + ASSERT_TRUE( + memcpy_s(pOption + endIndex + DHCP_OPT_DATA_INDEX, DHCP_UINT32_BYTES, &u32Data, DHCP_UINT32_BYTES) == EOK); + endIndex += DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[endIndex + DHCP_OPT_LEN_INDEX]; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = DHCP_MESSAGE_TYPE_OPTION; + pOption[endIndex + DHCP_OPT_LEN_INDEX] = DHCP_UINT8_BYTES; + uint8_t uData = DHCP_DISCOVER; + ASSERT_TRUE(memcpy_s(pOption + endIndex + DHCP_OPT_DATA_INDEX, DHCP_UINT8_BYTES, &uData, DHCP_UINT8_BYTES) == EOK); + endIndex += DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[endIndex + DHCP_OPT_LEN_INDEX]; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = END_OPTION; + + size_t len = 0; + EXPECT_NE(GetDhcpOption(&packet, DHCP_MESSAGE_TYPE_OPTION, &len), nullptr); +} + +HWTEST_F(DhcpOptionsTest, GetDhcpOption_FAILED, TestSize.Level1) +{ + size_t len = 0; + EXPECT_EQ(GetDhcpOption(nullptr, DHCP_MESSAGE_TYPE_OPTION, &len), nullptr); + + struct DhcpPacket packet; + ASSERT_TRUE(memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) == EOK); + + int endIndex = 0; + uint8_t *pOption = packet.options; + pOption[endIndex + DHCP_OPT_CODE_INDEX] = PAD_OPTION; + endIndex += DHCP_OPT_CODE_BYTES; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = SUBNET_MASK_OPTION; + pOption[endIndex + DHCP_OPT_LEN_INDEX] = DHCP_UINT32_BYTES; + uint32_t u32Data = 3226272231; + ASSERT_TRUE( + memcpy_s(pOption + endIndex + DHCP_OPT_DATA_INDEX, DHCP_UINT32_BYTES, &u32Data, DHCP_UINT32_BYTES) == EOK); + endIndex += DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[endIndex + DHCP_OPT_LEN_INDEX]; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = OPTION_OVERLOAD_OPTION; + pOption[endIndex + DHCP_OPT_LEN_INDEX] = DHCP_UINT8_BYTES; + uint8_t uData = FILE_FIELD | SNAME_FIELD; + ASSERT_TRUE(memcpy_s(pOption + endIndex + DHCP_OPT_DATA_INDEX, DHCP_UINT8_BYTES, &uData, DHCP_UINT8_BYTES) == EOK); + endIndex += DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[endIndex + DHCP_OPT_LEN_INDEX]; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = END_OPTION; + + len = 0; + EXPECT_EQ(GetDhcpOption(&packet, DHCP_MESSAGE_TYPE_OPTION, &len), nullptr); +} + +HWTEST_F(DhcpOptionsTest, GetDhcpOptionUint8_SUCCESS, TestSize.Level1) +{ + struct DhcpPacket packet; + ASSERT_TRUE(memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) == EOK); + + uint8_t *pOption = packet.options; + pOption[DHCP_OPT_CODE_INDEX] = DHCP_MESSAGE_TYPE_OPTION; + pOption[DHCP_OPT_LEN_INDEX] = DHCP_UINT8_BYTES; + uint8_t uData = DHCP_DISCOVER; + ASSERT_TRUE(memcpy_s(pOption + DHCP_OPT_DATA_INDEX, DHCP_UINT8_BYTES, &uData, DHCP_UINT8_BYTES) == EOK); + + int endIndex = DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[DHCP_OPT_LEN_INDEX]; + pOption[endIndex] = END_OPTION; + + uint8_t u8Message = 0; + EXPECT_EQ(true, GetDhcpOptionUint8(&packet, DHCP_MESSAGE_TYPE_OPTION, &u8Message)); +} + +HWTEST_F(DhcpOptionsTest, GetDhcpOptionUint8_FAILED, TestSize.Level1) +{ + uint8_t u8Message = 0; + EXPECT_EQ(false, GetDhcpOptionUint8(nullptr, DHCP_MESSAGE_TYPE_OPTION, &u8Message)); +} + +HWTEST_F(DhcpOptionsTest, GetDhcpOptionUint32_SUCCESS, TestSize.Level1) +{ + struct DhcpPacket packet; + ASSERT_TRUE(memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) == EOK); + + int endIndex = 0; + uint8_t *pOption = packet.options; + pOption[endIndex + DHCP_OPT_CODE_INDEX] = PAD_OPTION; + endIndex += DHCP_OPT_CODE_BYTES; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = DHCP_MESSAGE_TYPE_OPTION; + pOption[endIndex + DHCP_OPT_LEN_INDEX] = DHCP_UINT8_BYTES; + uint8_t uData = DHCP_DISCOVER; + ASSERT_TRUE(memcpy_s(pOption + endIndex + DHCP_OPT_DATA_INDEX, DHCP_UINT8_BYTES, &uData, DHCP_UINT8_BYTES) == EOK); + endIndex += DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[endIndex + DHCP_OPT_LEN_INDEX]; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = IP_ADDRESS_LEASE_TIME_OPTION; + pOption[endIndex + DHCP_OPT_LEN_INDEX] = DHCP_UINT32_BYTES; + uint32_t u32Data = ONE_HOURS_SEC; + ASSERT_TRUE( + memcpy_s(pOption + endIndex + DHCP_OPT_DATA_INDEX, DHCP_UINT32_BYTES, &u32Data, DHCP_UINT32_BYTES) == EOK); + endIndex += DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[endIndex + DHCP_OPT_LEN_INDEX]; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = END_OPTION; + + u32Data = 0; + EXPECT_EQ(true, GetDhcpOptionUint32(&packet, IP_ADDRESS_LEASE_TIME_OPTION, &u32Data)); +} + +HWTEST_F(DhcpOptionsTest, GetDhcpOptionUint32_FAILED, TestSize.Level1) +{ + uint32_t u32Data = 0; + EXPECT_EQ(false, GetDhcpOptionUint32(nullptr, IP_ADDRESS_LEASE_TIME_OPTION, &u32Data)); + + struct DhcpPacket packet; + ASSERT_TRUE(memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) == EOK); + + int endIndex = 0; + uint8_t *pOption = packet.options; + pOption[endIndex + DHCP_OPT_CODE_INDEX] = PAD_OPTION; + endIndex += DHCP_OPT_CODE_BYTES; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = DHCP_MESSAGE_TYPE_OPTION; + pOption[endIndex + DHCP_OPT_LEN_INDEX] = DHCP_UINT8_BYTES; + uint8_t uData = DHCP_DISCOVER; + ASSERT_TRUE(memcpy_s(pOption + endIndex + DHCP_OPT_DATA_INDEX, DHCP_UINT8_BYTES, &uData, DHCP_UINT8_BYTES) == EOK); + endIndex += DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[endIndex + DHCP_OPT_LEN_INDEX]; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = END_OPTION; + + u32Data = 0; + EXPECT_EQ(false, GetDhcpOptionUint32(&packet, DHCP_MESSAGE_TYPE_OPTION, &u32Data)); + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = OPTION_OVERLOAD_OPTION; + pOption[endIndex + DHCP_OPT_LEN_INDEX] = DHCP_UINT8_BYTES; + uData = FILE_FIELD | SNAME_FIELD; + ASSERT_TRUE(memcpy_s(pOption + endIndex + DHCP_OPT_DATA_INDEX, DHCP_UINT8_BYTES, &uData, DHCP_UINT8_BYTES) == EOK); + endIndex += DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[endIndex + DHCP_OPT_LEN_INDEX]; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = IP_ADDRESS_LEASE_TIME_OPTION; + pOption[endIndex + DHCP_OPT_LEN_INDEX] = DHCP_UINT32_BYTES; + u32Data = ONE_HOURS_SEC; + ASSERT_TRUE( + memcpy_s(pOption + endIndex + DHCP_OPT_DATA_INDEX, DHCP_UINT32_BYTES, &u32Data, DHCP_UINT32_BYTES) == EOK); + endIndex += DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[endIndex + DHCP_OPT_LEN_INDEX]; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = END_OPTION; + + u32Data = 0; + EXPECT_EQ(false, GetDhcpOptionUint32(&packet, IP_ADDRESS_LEASE_TIME_OPTION, &u32Data)); +} + +HWTEST_F(DhcpOptionsTest, GetDhcpOptionUint32n_SUCCESS, TestSize.Level1) +{ + struct DhcpPacket packet; + ASSERT_TRUE(memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) == EOK); + + int endIndex = 0; + uint8_t *pOption = packet.options; + pOption[endIndex + DHCP_OPT_CODE_INDEX] = PAD_OPTION; + endIndex += DHCP_OPT_CODE_BYTES; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = ROUTER_OPTION; + pOption[endIndex + DHCP_OPT_LEN_INDEX] = DHCP_UINT32_BYTES + DHCP_UINT32_BYTES; + uint32_t u32Data1 = 3226272231; + uint32_t u32Data2 = 3226272232; + ASSERT_TRUE( + memcpy_s(pOption + endIndex + DHCP_OPT_DATA_INDEX, DHCP_UINT32_BYTES, &u32Data1, DHCP_UINT32_BYTES) == EOK); + ASSERT_TRUE(memcpy_s(pOption + endIndex + DHCP_OPT_DATA_INDEX + DHCP_UINT32_BYTES, + DHCP_UINT32_BYTES, + &u32Data2, + DHCP_UINT32_BYTES) == EOK); + endIndex += DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[endIndex + DHCP_OPT_LEN_INDEX]; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = END_OPTION; + + uint32_t uData1 = 0; + uint32_t uData2 = 0; + EXPECT_EQ(true, GetDhcpOptionUint32n(&packet, ROUTER_OPTION, &uData1, &uData2)); +} + +HWTEST_F(DhcpOptionsTest, GetDhcpOptionUint32n_FAILED, TestSize.Level1) +{ + uint32_t uData1 = 0; + uint32_t uData2 = 0; + EXPECT_EQ(false, GetDhcpOptionUint32n(nullptr, ROUTER_OPTION, &uData1, &uData2)); + + struct DhcpPacket packet; + ASSERT_TRUE(memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) == EOK); + + int endIndex = 0; + uint8_t *pOption = packet.options; + pOption[endIndex + DHCP_OPT_CODE_INDEX] = PAD_OPTION; + endIndex += DHCP_OPT_CODE_BYTES; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = DHCP_MESSAGE_TYPE_OPTION; + pOption[endIndex + DHCP_OPT_LEN_INDEX] = DHCP_UINT8_BYTES; + uint8_t uData = DHCP_DISCOVER; + ASSERT_TRUE(memcpy_s(pOption + endIndex + DHCP_OPT_DATA_INDEX, DHCP_UINT8_BYTES, &uData, DHCP_UINT8_BYTES) == EOK); + endIndex += DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[endIndex + DHCP_OPT_LEN_INDEX]; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = END_OPTION; + + EXPECT_EQ(false, GetDhcpOptionUint32n(nullptr, DHCP_MESSAGE_TYPE_OPTION, &uData1, &uData2)); +} + +HWTEST_F(DhcpOptionsTest, GetDhcpOptionString_SUCCESS, TestSize.Level1) +{ + char buf[VENDOR_MAX_LEN - DHCP_OPT_CODE_BYTES - DHCP_OPT_LEN_BYTES] = {0}; + ASSERT_TRUE(snprintf_s(buf, + VENDOR_MAX_LEN - DHCP_OPT_DATA_INDEX, + VENDOR_MAX_LEN - DHCP_OPT_DATA_INDEX - 1, + "%s-%s", + DHCPC_NAME, + DHCPC_VERSION) >= 0); + + struct DhcpPacket packet; + ASSERT_TRUE(memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) == EOK); + + uint8_t *pOption = packet.options; + pOption[DHCP_OPT_CODE_INDEX] = VENDOR_SPECIFIC_INFO_OPTION; + pOption[DHCP_OPT_LEN_INDEX] = strlen(buf); + ASSERT_TRUE(memcpy_s(pOption + DHCP_OPT_DATA_INDEX, + VENDOR_MAX_LEN - DHCP_OPT_CODE_BYTES - DHCP_OPT_LEN_BYTES, + buf, + strlen(buf)) == EOK); + + int endIndex = DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[DHCP_OPT_LEN_INDEX]; + pOption[endIndex] = END_OPTION; + + char *pVendor = GetDhcpOptionString(&packet, VENDOR_SPECIFIC_INFO_OPTION); + ASSERT_TRUE(pVendor != NULL); + free(pVendor); +} + +HWTEST_F(DhcpOptionsTest, GetDhcpOptionString_FAILED, TestSize.Level1) +{ + EXPECT_EQ(nullptr, GetDhcpOptionString(nullptr, VENDOR_SPECIFIC_INFO_OPTION)); +} + +HWTEST_F(DhcpOptionsTest, GetEndOptionIndex_SUCCESS, TestSize.Level1) +{ + struct DhcpPacket packet; + ASSERT_TRUE(memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) == EOK); + + int endIndex = 0; + uint8_t *pOption = packet.options; + pOption[endIndex + DHCP_OPT_CODE_INDEX] = PAD_OPTION; + endIndex += DHCP_OPT_CODE_BYTES; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = SUBNET_MASK_OPTION; + pOption[endIndex + DHCP_OPT_LEN_INDEX] = DHCP_UINT32_BYTES; + uint32_t u32Data = 3226272231; + ASSERT_TRUE( + memcpy_s(pOption + endIndex + DHCP_OPT_DATA_INDEX, DHCP_UINT32_BYTES, &u32Data, DHCP_UINT32_BYTES) == EOK); + endIndex += DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + pOption[endIndex + DHCP_OPT_LEN_INDEX]; + + pOption[endIndex + DHCP_OPT_CODE_INDEX] = END_OPTION; + + EXPECT_GE(GetEndOptionIndex(packet.options), 0); +} + +HWTEST_F(DhcpOptionsTest, AddOptStrToOpts_SUCCESS, TestSize.Level1) +{ + struct DhcpPacket packet; + ASSERT_TRUE(memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) == EOK); + packet.options[DHCP_OPT_CODE_INDEX] = END_OPTION; + + uint8_t option[DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + DHCP_UINT32_BYTES]; + option[DHCP_OPT_CODE_INDEX] = IP_ADDRESS_LEASE_TIME_OPTION; + option[DHCP_OPT_LEN_INDEX] = DHCP_UINT32_BYTES; + uint32_t uData = ONE_HOURS_SEC; + ASSERT_TRUE(memcpy_s(option + DHCP_OPT_DATA_INDEX, DHCP_UINT32_BYTES, &uData, DHCP_UINT32_BYTES) == EOK); + int nLen = DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + option[DHCP_OPT_LEN_INDEX]; + + EXPECT_GT(AddOptStrToOpts(packet.options, option, nLen), 0); +} + +HWTEST_F(DhcpOptionsTest, AddOptStrToOpts_FAILED, TestSize.Level1) +{ + struct DhcpPacket packet; + ASSERT_TRUE(memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) == EOK); + + int endIndex = 0; + uint8_t *pOption = packet.options; + pOption[endIndex + DHCP_OPT_CODE_INDEX] = END_OPTION; + + uint8_t option[DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + DHCP_UINT32_BYTES]; + option[DHCP_OPT_CODE_INDEX] = IP_ADDRESS_LEASE_TIME_OPTION; + option[DHCP_OPT_LEN_INDEX] = DHCP_UINT32_BYTES; + uint32_t uData = ONE_HOURS_SEC; + ASSERT_TRUE(memcpy_s(option + DHCP_OPT_DATA_INDEX, DHCP_UINT32_BYTES, &uData, DHCP_UINT32_BYTES) == EOK); + EXPECT_EQ(AddOptStrToOpts(pOption, option, DHCP_OPT_CODE_BYTES), 0); + + option[DHCP_OPT_LEN_INDEX] = (uint8_t)(DHCP_OPTIONS_SIZE - DHCP_OPT_CODE_BYTES - DHCP_OPT_LEN_BYTES); + EXPECT_EQ(AddOptStrToOpts(pOption, option, DHCP_OPTIONS_SIZE), 0); +} + +HWTEST_F(DhcpOptionsTest, AddOptValueToOpts_SUCCESS, TestSize.Level1) +{ + struct DhcpPacket packet; + ASSERT_TRUE(memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) == EOK); + packet.options[DHCP_OPT_CODE_INDEX] = END_OPTION; + + uint8_t data1 = DHCP_REQUEST; + uint16_t data2 = 1; + uint32_t data3 = ONE_HOURS_SEC; + EXPECT_GT(AddOptValueToOpts(packet.options, DHCP_MESSAGE_TYPE_OPTION, data1), 0); + EXPECT_GT(AddOptValueToOpts(packet.options, INTERFACE_MTU_OPTION, data2), 0); + EXPECT_GT(AddOptValueToOpts(packet.options, IP_ADDRESS_LEASE_TIME_OPTION, data3), 0); +} + +HWTEST_F(DhcpOptionsTest, AddOptValueToOpts_FAILED, TestSize.Level1) +{ + struct DhcpPacket packet; + ASSERT_TRUE(memset_s(&packet, sizeof(struct DhcpPacket), 0, sizeof(struct DhcpPacket)) == EOK); + packet.options[DHCP_OPT_CODE_INDEX] = END_OPTION; + + EXPECT_EQ(AddOptValueToOpts(packet.options, PAD_OPTION, 0), 0); +} +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_socket_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_socket_test.cpp new file mode 100644 index 000000000..f12809644 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_socket_test.cpp @@ -0,0 +1,261 @@ +/* + * 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 "wifi_log.h" +#include "dhcp_socket.h" +#include "dhcp_function.h" +#include "securec.h" +#include "mock_system_func.h" + +using namespace testing::ext; + +namespace OHOS { +class DhcpSocketTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; + +HWTEST_F(DhcpSocketTest, CreateRawSocket_SUCCESS, TestSize.Level1) +{ + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); + int fd = -1; + EXPECT_EQ(CreateRawSocket(&fd), SOCKET_OPT_FAILED); + EXPECT_EQ(CreateRawSocket(&fd), SOCKET_OPT_SUCCESS); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpSocketTest, CreateKernelSocket_SUCCESS, TestSize.Level1) +{ + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + int fd = -1; + EXPECT_EQ(CreateKernelSocket(&fd), SOCKET_OPT_FAILED); + EXPECT_EQ(CreateKernelSocket(&fd), SOCKET_OPT_SUCCESS); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpSocketTest, BindRawSocket_SUCCESS, TestSize.Level1) +{ + int fd = -1; + int ifaceIndex = 1; + EXPECT_EQ(BindRawSocket(fd, ifaceIndex, NULL), SOCKET_OPT_FAILED); + + MockSystemFunc::SetMockFlag(true); + + fd = 1; + EXPECT_CALL(MockSystemFunc::GetInstance(), bind(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(0)); + EXPECT_EQ(BindRawSocket(fd, ifaceIndex, (uint8_t *)MAC_BCAST_ADDR), SOCKET_OPT_FAILED); + EXPECT_EQ(BindRawSocket(fd, ifaceIndex, (uint8_t *)MAC_BCAST_ADDR), SOCKET_OPT_SUCCESS); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpSocketTest, BindKernelSocket_SUCCESS, TestSize.Level1) +{ + int fd = -1; + EXPECT_EQ(BindKernelSocket(fd, NULL, 0, 0, false), SOCKET_OPT_FAILED); + + MockSystemFunc::SetMockFlag(true); + + fd = 1; + const char *ifname = "wlan0"; + EXPECT_CALL(MockSystemFunc::GetInstance(), setsockopt(_, _, _, _, _)) + .WillOnce(Return(-1)) + .WillOnce(Return(-1)) + .WillOnce(Return(-1)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), bind(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + + EXPECT_EQ(BindKernelSocket(fd, ifname, 0, 0, false), SOCKET_OPT_FAILED); + EXPECT_EQ(BindKernelSocket(fd, NULL, 0, 0, true), SOCKET_OPT_FAILED); + EXPECT_EQ(BindKernelSocket(fd, NULL, 0, 0, false), SOCKET_OPT_FAILED); + EXPECT_EQ(BindKernelSocket(fd, NULL, INADDR_ANY, BOOTP_CLIENT, false), SOCKET_OPT_FAILED); + EXPECT_EQ(BindKernelSocket(fd, ifname, INADDR_ANY, BOOTP_CLIENT, true), SOCKET_OPT_SUCCESS); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpSocketTest, SendToDhcpPacket_SUCCESS, TestSize.Level1) +{ + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), bind(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), sendto(_, _, _, _, _, _)) + .WillOnce(Return(-1)) + .WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + + EXPECT_EQ(SendToDhcpPacket(NULL, 0, 0, 0, NULL), SOCKET_OPT_FAILED); + int ifindex = 1; + EXPECT_EQ(SendToDhcpPacket(NULL, 0, 0, ifindex, (uint8_t *)MAC_BCAST_ADDR), SOCKET_OPT_FAILED); + struct DhcpPacket packet; + packet.xid = 123456; + EXPECT_EQ(SendToDhcpPacket(&packet, 0, 0, ifindex, (uint8_t *)MAC_BCAST_ADDR), SOCKET_OPT_FAILED); + EXPECT_EQ(SendToDhcpPacket(&packet, INADDR_ANY, INADDR_BROADCAST, ifindex, (uint8_t *)MAC_BCAST_ADDR), + SOCKET_OPT_SUCCESS); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpSocketTest, SendDhcpPacket_SUCCESS, TestSize.Level1) +{ + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), bind(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), connect(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), write(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + + EXPECT_EQ(SendDhcpPacket(NULL, 0, 0), SOCKET_OPT_FAILED); + EXPECT_EQ(SendDhcpPacket(NULL, INADDR_ANY, 0), SOCKET_OPT_FAILED); + EXPECT_EQ(SendDhcpPacket(NULL, INADDR_ANY, INADDR_BROADCAST), SOCKET_OPT_FAILED); + struct DhcpPacket packet; + packet.xid = 123456; + EXPECT_EQ(SendDhcpPacket(&packet, INADDR_ANY, INADDR_BROADCAST), SOCKET_OPT_FAILED); + EXPECT_EQ(SendDhcpPacket(&packet, INADDR_ANY, INADDR_BROADCAST), SOCKET_OPT_SUCCESS); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpSocketTest, CheckReadBytes_SUCCESS, TestSize.Level1) +{ + int count = -1; + int total = 0; + EXPECT_EQ(CheckReadBytes(-1, 0), SOCKET_OPT_ERROR); + + count = sizeof(struct iphdr) + sizeof(struct udphdr) - 1; + EXPECT_EQ(CheckReadBytes(count, 0), SOCKET_OPT_FAILED); + + count = sizeof(struct iphdr) + sizeof(struct udphdr); + total = count + 1; + EXPECT_EQ(CheckReadBytes(count, total), SOCKET_OPT_FAILED); + + total = count; + EXPECT_EQ(CheckReadBytes(count, total), SOCKET_OPT_SUCCESS); +} + +HWTEST_F(DhcpSocketTest, CheckUdpPacket_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(CheckUdpPacket(NULL, 0), SOCKET_OPT_FAILED); + + struct UdpDhcpPacket packet; + int total = (int)sizeof(struct UdpDhcpPacket) + 1; + EXPECT_EQ(CheckUdpPacket(&packet, total), SOCKET_OPT_FAILED); + + total = (int)sizeof(struct UdpDhcpPacket); + packet.ip.protocol = 0; + packet.ip.version = 0; + EXPECT_EQ(CheckUdpPacket(&packet, total), SOCKET_OPT_FAILED); + + packet.ip.protocol = IPPROTO_UDP; + packet.ip.version = IPVERSION; + packet.ip.ihl = 0; + EXPECT_EQ(CheckUdpPacket(&packet, total), SOCKET_OPT_FAILED); + + packet.ip.ihl = (uint32_t)(sizeof(packet.ip) >> DHCP_UINT16_BYTES); + packet.udp.dest = 0; + EXPECT_EQ(CheckUdpPacket(&packet, total), SOCKET_OPT_FAILED); + + packet.udp.dest = htons(BOOTP_CLIENT); + packet.udp.len = 0; + EXPECT_EQ(CheckUdpPacket(&packet, total), SOCKET_OPT_FAILED); + + uint16_t uLen = (uint16_t)(total - (int)sizeof(packet.ip)); + packet.udp.len = htons(uLen); + EXPECT_EQ(CheckUdpPacket(&packet, total), SOCKET_OPT_SUCCESS); +} + +HWTEST_F(DhcpSocketTest, CheckPacketIpSum_FAILED, TestSize.Level1) +{ + EXPECT_EQ(CheckPacketIpSum(NULL, 0), SOCKET_OPT_FAILED); + + struct UdpDhcpPacket packet; + int total = (int)sizeof(struct UdpDhcpPacket) + 1; + EXPECT_EQ(CheckPacketIpSum(&packet, total), SOCKET_OPT_FAILED); + + total = (int)sizeof(struct UdpDhcpPacket); + packet.ip.protocol = IPPROTO_UDP; + packet.ip.version = IPVERSION; + packet.ip.ihl = (uint32_t)(sizeof(packet.ip) >> DHCP_UINT16_BYTES); + packet.udp.dest = htons(BOOTP_CLIENT); + uint16_t uLen = (uint16_t)(total - (int)sizeof(packet.ip)); + packet.udp.len = htons(uLen); + packet.ip.check = 0; + EXPECT_EQ(CheckPacketIpSum(&packet, total), SOCKET_OPT_ERROR); +} + +HWTEST_F(DhcpSocketTest, CheckPacketUdpSum_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(CheckPacketUdpSum(NULL, 0), SOCKET_OPT_FAILED); + + struct UdpDhcpPacket packet; + packet.udp.check = 1; + EXPECT_EQ(CheckPacketUdpSum(&packet, 0), SOCKET_OPT_FAILED); + packet.udp.check = 0; + EXPECT_EQ(CheckPacketUdpSum(&packet, 1), SOCKET_OPT_SUCCESS); +} + +HWTEST_F(DhcpSocketTest, GetDhcpRawPacket_FAILED, TestSize.Level1) +{ + EXPECT_EQ(GetDhcpRawPacket(NULL, 0), SOCKET_OPT_FAILED); + + MockSystemFunc::SetMockFlag(true); + + struct UdpDhcpPacket udpPackets; + ASSERT_TRUE(memset_s(&udpPackets, sizeof(struct UdpDhcpPacket), 0, sizeof(struct UdpDhcpPacket)) == EOK); + int total = sizeof(struct iphdr) + sizeof(struct udphdr); + EXPECT_CALL(MockSystemFunc::GetInstance(), read(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(total)); + + struct DhcpPacket packet; + EXPECT_EQ(GetDhcpRawPacket(&packet, 1), SOCKET_OPT_ERROR); + EXPECT_EQ(GetDhcpRawPacket(&packet, 1), SOCKET_OPT_FAILED); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpSocketTest, GetDhcpKernelPacket_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(GetDhcpKernelPacket(NULL, 0), SOCKET_OPT_FAILED); + + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), read(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); + + struct DhcpPacket packet; + EXPECT_EQ(GetDhcpKernelPacket(&packet, 1), SOCKET_OPT_ERROR); + EXPECT_EQ(GetDhcpKernelPacket(&packet, 1), SOCKET_OPT_FAILED); + + packet.cookie = htonl(MAGIC_COOKIE); + EXPECT_GT(GetDhcpKernelPacket(&packet, 1), 0); + + MockSystemFunc::SetMockFlag(false); +} +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/global_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/global_test.cpp new file mode 100644 index 000000000..dfbf8144a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/global_test.cpp @@ -0,0 +1,24 @@ +/* + * 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"global_test.h" +void GlobalTest::SetUp() +{ + printf("GlobalTest SetUp\n"); +} +void GlobalTest::TearDown() +{ + printf("GlobalTest TearDown\n"); +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/global_test.h b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/global_test.h new file mode 100644 index 000000000..499f1fbab --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/global_test.h @@ -0,0 +1,24 @@ +/* + * 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 GLOBAL_TEST_H +#define GLOBAL_TEST_H +#include +class GlobalTest : public testing::Environment { +public: + virtual void SetUp(); + virtual void TearDown(); +}; +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_custom_func.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_custom_func.cpp new file mode 100644 index 000000000..50e92f549 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_custom_func.cpp @@ -0,0 +1,128 @@ +/* + * 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 "mock_custom_func.h" +#include "dhcp_ipv4.h" +#include "dhcp_options.h" +#include "dhcp_function.h" +#include "securec.h" + +using namespace OHOS; + +static bool g_mockTag = false; + +MockCustomFunc &MockCustomFunc::GetInstance() +{ + static MockCustomFunc gMockCustomFunc; + return gMockCustomFunc; +}; + +MockCustomFunc::MockCustomFunc() +{} + +void MockCustomFunc::SetMockFlag(bool flag) +{ + g_mockTag = flag; +} + +bool MockCustomFunc::GetMockFlag(void) +{ + return g_mockTag; +} + +#ifdef __cplusplus +extern "C" { +#endif +static int AddOptDoubleValueToOpts(uint8_t *pOpts, uint8_t code, uint32_t value1, uint32_t value2) +{ + uint8_t uOption[DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + DHCP_UINT32_BYTES * 2] = {0}; + uOption[DHCP_OPT_CODE_INDEX] = code; + uOption[DHCP_OPT_LEN_INDEX] = DHCP_UINT32_BYTES * 2; + if ((memcpy_s(uOption + DHCP_OPT_DATA_INDEX, DHCP_UINT32_BYTES, &value1, DHCP_UINT32_BYTES) != EOK) || + (memcpy_s(uOption + DHCP_OPT_DATA_INDEX + DHCP_UINT32_BYTES, + DHCP_UINT32_BYTES, &value2, DHCP_UINT32_BYTES) != EOK)) { + return 0; + } + int nLen = DHCP_OPT_CODE_BYTES + DHCP_OPT_LEN_BYTES + uOption[DHCP_OPT_LEN_INDEX]; + return AddOptStrToOpts(pOpts, uOption, nLen); +} + +int __real_GetDhcpRawPacket(struct DhcpPacket *getPacket, int rawFd); +int __wrap_GetDhcpRawPacket(struct DhcpPacket *getPacket, int rawFd) +{ + if (g_mockTag) { + int nLen = MockCustomFunc::GetInstance().GetDhcpRawPacket(getPacket, rawFd); + char cliIp[INET_ADDRSTRLEN] = "192.77.2.231"; + char serIp[INET_ADDRSTRLEN] = "192.77.2.1"; + uint32_t uCliIp = 0; + uint32_t uSerIp = 0; + Ip4StrConToInt(cliIp, &uCliIp, false); + Ip4StrConToInt(serIp, &uSerIp, false); + getPacket->xid = GetDhcpTransID(); + getPacket->yiaddr = uCliIp; + if (nLen == 1) { + GetPacketHeaderInfo(getPacket, DHCP_OFFER); + AddOptValueToOpts(getPacket->options, SERVER_IDENTIFIER_OPTION, uSerIp); + } else if (nLen == 2) { + GetPacketHeaderInfo(getPacket, DHCP_ACK); + } else if (nLen == 3) { + GetPacketHeaderInfo(getPacket, DHCP_NAK); + } else if (nLen == 4) { + GetPacketHeaderInfo(getPacket, DHCP_ACK); + AddOptValueToOpts(getPacket->options, SERVER_IDENTIFIER_OPTION, uSerIp); + AddOptValueToOpts(getPacket->options, SUBNET_MASK_OPTION, 0); + AddOptValueToOpts(getPacket->options, IP_ADDRESS_LEASE_TIME_OPTION, htonl(10)); + AddOptDoubleValueToOpts(getPacket->options, ROUTER_OPTION, uSerIp, uCliIp); + AddOptDoubleValueToOpts(getPacket->options, DOMAIN_NAME_SERVER_OPTION, uSerIp, uCliIp); + } + return nLen; + } else { + return __real_GetDhcpRawPacket(getPacket, rawFd); + } +} + +int __real_GetDhcpKernelPacket(struct DhcpPacket *getPacket, int sockFd); +int __wrap_GetDhcpKernelPacket(struct DhcpPacket *getPacket, int sockFd) +{ + if (g_mockTag) { + int nLen = MockCustomFunc::GetInstance().GetDhcpKernelPacket(getPacket, sockFd); + char cliIp[INET_ADDRSTRLEN] = "192.77.3.231"; + char serIp[INET_ADDRSTRLEN] = "192.77.3.1"; + uint32_t uCliIp = 0; + uint32_t uSerIp = 0; + Ip4StrConToInt(cliIp, &uCliIp, false); + Ip4StrConToInt(serIp, &uSerIp, false); + getPacket->xid = GetDhcpTransID(); + getPacket->yiaddr = uCliIp; + if (nLen == 1) { + GetPacketHeaderInfo(getPacket, DHCP_OFFER); + AddOptValueToOpts(getPacket->options, SERVER_IDENTIFIER_OPTION, uSerIp); + } else if (nLen == 2) { + GetPacketHeaderInfo(getPacket, DHCP_ACK); + AddOptValueToOpts(getPacket->options, SERVER_IDENTIFIER_OPTION, uSerIp); + AddOptValueToOpts(getPacket->options, SUBNET_MASK_OPTION, 0); + AddOptValueToOpts(getPacket->options, IP_ADDRESS_LEASE_TIME_OPTION, htonl(4)); + AddOptDoubleValueToOpts(getPacket->options, ROUTER_OPTION, uSerIp, uCliIp); + AddOptDoubleValueToOpts(getPacket->options, DOMAIN_NAME_SERVER_OPTION, uSerIp, uCliIp); + } else if (nLen == 3) { + GetPacketHeaderInfo(getPacket, DHCP_NAK); + } + return nLen; + } else { + return __real_GetDhcpKernelPacket(getPacket, sockFd); + } +} +#ifdef __cplusplus +} +#endif diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_custom_func.h b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_custom_func.h new file mode 100644 index 000000000..f50e7892a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_custom_func.h @@ -0,0 +1,52 @@ +/* + * 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_CUSTOM_FUNC_H +#define OHOS_MOCK_CUSTOM_FUNC_H + +#include +#include + +#include "dhcp_define.h" + +namespace OHOS { +class MockCustomFunc { +public: + MOCK_METHOD2(GetDhcpRawPacket, int(struct DhcpPacket *getPacket, int rawFd)); + MOCK_METHOD2(GetDhcpKernelPacket, int(struct DhcpPacket *getPacket, int sockFd)); + // MOCK_METHOD0(GetSelectRet, int(void)); + + static MockCustomFunc &GetInstance(void); + static void SetMockFlag(bool flag); + static bool GetMockFlag(void); + +private: + MockCustomFunc(); + ~MockCustomFunc(){} +}; +} // namespace OHOS + +// #ifdef __cplusplus +// extern "C" { +// #endif + +// int GetSelectRet(void); +// int MySelect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); + +// #ifdef __cplusplus +// } +// #endif + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_system_func.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_system_func.cpp new file mode 100644 index 000000000..092c0bc00 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_system_func.cpp @@ -0,0 +1,182 @@ +/* + * 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 "mock_system_func.h" +#include "dhcp_ipv4.h" +#include "dhcp_client.h" +using namespace OHOS; + +static bool g_mockTag = false; + +MockSystemFunc &MockSystemFunc::GetInstance() +{ + static MockSystemFunc gMockSystemFunc; + return gMockSystemFunc; +}; + +MockSystemFunc::MockSystemFunc() +{} + +void MockSystemFunc::SetMockFlag(bool flag) +{ + g_mockTag = flag; +} + +bool MockSystemFunc::GetMockFlag(void) +{ + return g_mockTag; +} + +#ifdef __cplusplus +extern "C" { +#endif +int __real_open(const char *__file, int __oflag); +int __wrap_open(const char *__file, int __oflag) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().open(__file, __oflag); + } else { + return __real_open(__file, __oflag); + } +} + +int __real_close(int fd); +int __wrap_close(int fd) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().close(fd); + } else { + return __real_close(fd); + } +} + +ssize_t __real_write(int fd, const void *buf, size_t count); +ssize_t __wrap_write(int fd, const void *buf, size_t count) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().write(fd, buf, count); + } else { + return __real_write(fd, buf, count); + } +} + +ssize_t __real_read(int fd, void *buf, size_t count); +ssize_t __wrap_read(int fd, void *buf, size_t count) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().read(fd, buf, count); + } else { + return __real_read(fd, buf, count); + } +} + +int __real_socket(int __domain, int __type, int __protocol); +int __wrap_socket(int __domain, int __type, int __protocol) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().socket(__domain, __type, __protocol); + } else { + return __real_socket(__domain, __type, __protocol); + } +} + +int __real_setsockopt(int __fd, int __level, int __optname, const void *__optval, socklen_t __optlen); +int __wrap_setsockopt(int __fd, int __level, int __optname, const void *__optval, socklen_t __optlen) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().setsockopt(__fd, __level, __optname, __optval, __optlen); + } else { + return __real_setsockopt(__fd, __level, __optname, __optval, __optlen); + } +} + +int __real_ioctl(int __fd, unsigned long __request, struct sockaddr *__ifreq); +int __wrap_ioctl(int __fd, unsigned long __request, struct sockaddr *__ifreq) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().ioctl(__fd, __request, __ifreq); + } else { + return __real_ioctl(__fd, __request, __ifreq); + } +} + +int __real_bind(int __fd, const struct sockaddr *__addr, socklen_t __len); +int __wrap_bind(int __fd, const struct sockaddr *__addr, socklen_t __len) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().bind(__fd, __addr, __len); + } else { + return __real_bind(__fd, __addr, __len); + } +} + +int __real_listen(int __fd, int __n); +int __wrap_listen(int __fd, int __n) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().listen(__fd, __n); + } else { + return __real_listen(__fd, __n); + } +} + +int __real_connect(int __fd, const struct sockaddr *__addr, socklen_t __len); +int __wrap_connect(int __fd, const struct sockaddr *__addr, socklen_t __len) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().connect(__fd, __addr, __len); + } else { + return __real_connect(__fd, __addr, __len); + } +} + +int __real_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); +int __wrap_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout) +{ + if (g_mockTag) { + int nRet = MockSystemFunc::GetInstance().select(nfds, readfds, writefds, exceptfds, timeout); + FD_ZERO(readfds); + if (nRet == 1) { + FD_SET(GetPacketReadSockFd(), readfds); + } else if (nRet == 2) { + FD_SET(GetSigReadSockFd(), readfds); + struct DhcpClientCfg *pCfg = GetDhcpClientCfg(); + pCfg->timeoutExit = true; + } else if (nRet == 3) { + struct DhcpPacket *dhcp = (struct DhcpPacket *)calloc(1, sizeof(*dhcp)); + if (dhcp != nullptr) { + SendReboot(dhcp, time(nullptr)); + } + } else if (nRet == 4) { + FD_SET(GetSigReadSockFd(), readfds); + } + return nRet; + } else { + return __real_select(nfds, readfds, writefds, exceptfds, timeout); + } +} + +ssize_t __real_sendto(int fd, const void *buf, size_t count, int flags, const struct sockaddr *addr, socklen_t len); +ssize_t __wrap_sendto(int fd, const void *buf, size_t count, int flags, const struct sockaddr *addr, socklen_t len) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().sendto(fd, buf, count, flags, addr, len); + } else { + return __real_sendto(fd, buf, count, flags, addr, len); + } +} +#ifdef __cplusplus +} +#endif diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_system_func.h b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_system_func.h new file mode 100644 index 000000000..92b823959 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_system_func.h @@ -0,0 +1,58 @@ +/* + * 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_SYSTEM_FUNC_H +#define OHOS_MOCK_SYSTEM_FUNC_H + +#include +#include +#include +#include +#include +#include + +using ::testing::_; +using ::testing::Return; + +namespace OHOS { +class MockSystemFunc { +public: + MOCK_METHOD2(open, int(const char *__file, int __oflag)); + MOCK_METHOD1(close, int(int)); + MOCK_METHOD3(write, ssize_t(int fd, const void *buf, size_t count)); + MOCK_METHOD3(read, ssize_t(int fd, void *buf, size_t count)); + MOCK_METHOD3(socket, int(int __domain, int __type, int __protocol)); + MOCK_METHOD5(setsockopt, int(int __fd, int __level, int __optname, const void *__optval, socklen_t __optlen)); + MOCK_METHOD3(ioctl, int(int __fd, unsigned long __request, struct sockaddr *__ifreq)); + MOCK_METHOD3(bind, int(int __fd, const struct sockaddr *__addr, socklen_t __len)); + MOCK_METHOD2(listen, int(int __fd, int __n)); + MOCK_METHOD3(connect, int(int __fd, const struct sockaddr *__addr, socklen_t __len)); + MOCK_METHOD5(select, int(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)); + MOCK_METHOD6( + sendto, ssize_t(int fd, const void *buf, size_t count, int flags, const struct sockaddr *addr, socklen_t len)); + + static MockSystemFunc &GetInstance(void); + static void SetMockFlag(bool flag); + static bool GetMockFlag(void); + +private: + MockSystemFunc(); + ~MockSystemFunc(){} +}; +} // namespace OHOS + +extern "C" {} + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/BUILD.gn b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/BUILD.gn new file mode 100644 index 000000000..a35397f93 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/BUILD.gn @@ -0,0 +1,91 @@ +# 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. + +import("//build/test.gni") + +SUBSYSTEM_DIR = "//foundation/communication/wifi" +module_output_path = "wifi_standard/dhcp_server_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include", + ] +} + +ohos_unittest("dhcp_server_unittest") { + module_out_path = module_output_path + sources = [ + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/address_utils.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/common_util.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_argument.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_binding.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_config.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_option.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/hash_table.c", + "address_utils_test.cpp", + "dhcp_address_pool_test.cpp", + "dhcp_argument_test.cpp", + "dhcp_binding_test.cpp", + "dhcp_config_test.cpp", + "dhcp_message_sim.cpp", + "dhcp_option_test.cpp", + "dhcp_server_test.cpp", + "hash_table_test.cpp", + "system_func_mock.cpp", + ] + + include_dirs = [ + "//utils/native/base/include", + "//third_party/googletest/googlemock/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include", + ] + + defines = [ "__OHOS__" ] + + cflags = [] + + deps = [ + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + ldflags = [ + "-fPIC", + "-Wl,--wrap=socket", + "-Wl,--wrap=recvfrom", + "-Wl,--wrap=sendto", + "-Wl,--wrap=bind", + "-Wl,--wrap=setsockopt", + "-Wl,--wrap=select", + "-Wl,--wrap=close", + "--coverage", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + configs = [ ":module_private_config" ] + + part_name = "wifi_standard" + subsystem_name = "communication" + testonly = true +} + +group("unittest") { + testonly = true + deps = [ ":dhcp_server_unittest" ] +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/address_utils_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/address_utils_test.cpp new file mode 100644 index 000000000..1e972b397 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/address_utils_test.cpp @@ -0,0 +1,259 @@ +/* + * 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 "string_ex.h" +#include "dhcp_define.h" +#include "address_utils.h" + +using namespace testing::ext; + +const uint8_t netmask24[] = {255, 255, 255, 0}; +const uint8_t netmask25[] = {255, 255, 255, 128}; +const uint8_t netmask26[] = {255, 255, 255, 192}; +const uint8_t netmask27[] = {255, 255, 255, 224}; + +/** +* @tc.name: ParseIpAddrTest +* @tc.desc: test address translation. +* @tc.type: FUNC +* @tc.require: AR00000000 SR00000000 +*/ +HWTEST(AddressUtilsTest, ParseIpAddrTest, TestSize.Level1) +{ + uint8_t ipData[] = {192, 168, 100, 1}; + uint32_t testIp = ParseIp(ipData); + ASSERT_TRUE(testIp != 0); + EXPECT_EQ(testIp, ParseIpAddr("192.168.100.1")); +} + +HWTEST(AddressUtilsTest, ParseIpAddrFailedTest, TestSize.Level1) +{ + uint32_t expectVal = 0; + EXPECT_EQ(expectVal, ParseIpAddr("192.168.100.")); + EXPECT_EQ(expectVal, ParseIpAddr("0")); + EXPECT_EQ(expectVal, ParseIpAddr("abc.abc.abc.abc")); +} + +HWTEST(AddressUtilsTest, ParseStrIpAddrTest, TestSize.Level1) +{ + uint8_t ipData[] = {192, 168, 100, 1}; + uint32_t testIp = ParseIp(ipData); + EXPECT_TRUE(testIp != 0); + EXPECT_STREQ("192.168.100.1", ParseStrIp(testIp)); +} + +/** +* @tc.name: NetworkAddressTest +* @tc.desc: test network address calculation. +* @tc.type: FUNC +* @tc.require: AR00000000 SR00000000 +*/ +HWTEST(AddressUtilsTest, NetworkAddressTest, TestSize.Level1) +{ + uint8_t srcNetData[] = {192, 168, 100, 0}; + uint32_t srcNet = ParseIp(srcNetData); + ASSERT_TRUE(srcNet != 0); + uint32_t testIp = ParseIpAddr("192.168.100.100"); + ASSERT_TRUE(testIp != 0); + uint32_t testNetmask = ParseIp(netmask24); + EXPECT_TRUE(testNetmask != 0); + EXPECT_EQ(srcNet, NetworkAddress(testIp, testNetmask)); +} + +HWTEST(AddressUtilsTest, FirstIpAddressTest, TestSize.Level1) +{ + uint8_t srcData[] = {192, 168, 100, 1}; + uint32_t srcAddr = ParseIp(srcData); + ASSERT_TRUE(srcAddr != 0); + uint32_t testIp = ParseIpAddr("192.168.100.100"); + ASSERT_TRUE(testIp != 0); + uint32_t testNetmask = ParseIp(netmask24); + EXPECT_TRUE(testNetmask != 0); + EXPECT_EQ(srcAddr, FirstIpAddress(testIp, testNetmask)); +} + +HWTEST(AddressUtilsTest, LastIpAddressTest, TestSize.Level1) +{ + uint8_t srcData[] = {192, 168, 100, 254}; + uint32_t srcAddr = ParseIp(srcData); + ASSERT_TRUE(srcAddr != 0); + uint32_t testIp = ParseIpAddr("192.168.100.100"); + ASSERT_TRUE(testIp != 0); + uint32_t testNetmask = ParseIp(netmask24); + EXPECT_TRUE(testNetmask != 0); + EXPECT_EQ(srcAddr, LastIpAddress(testIp, testNetmask)); +} + +HWTEST(AddressUtilsTest, NextIpAddressTest, TestSize.Level1) +{ + uint8_t srcData[] = {192, 168, 100, 100}; + uint32_t srcAddr = ParseIp(srcData); + EXPECT_TRUE(srcAddr != 0); + uint32_t testIp1 = ParseIpAddr("192.168.100.101"); + EXPECT_TRUE(testIp1 != 0); + uint32_t testIp2 = ParseIpAddr("192.168.100.102"); + EXPECT_TRUE(testIp2 != 0); + uint32_t testNetmask = ParseIp(netmask24); + EXPECT_TRUE(testNetmask != 0); + EXPECT_EQ(testIp1, NextIpAddress(srcAddr, testNetmask, 0)); + EXPECT_EQ(testIp2, NextIpAddress(srcAddr, testNetmask, 1)); +} + +HWTEST(AddressUtilsTest, IpInNetworkTest, TestSize.Level1) +{ + uint8_t srcData[] = {192, 168, 100, 0}; + uint32_t srcAddr = ParseIp(srcData); + EXPECT_TRUE(srcAddr != 0); + uint32_t testNetmask = ParseIp(netmask25); + EXPECT_TRUE(testNetmask != 0); + uint32_t testIp1 = ParseIpAddr("192.168.100.120"); + EXPECT_TRUE(testIp1 != 0); + uint32_t testIp2= ParseIpAddr("192.168.100.150"); + EXPECT_TRUE(testIp2 != 0); + EXPECT_TRUE(IpInNetwork(testIp1, srcAddr, testNetmask)); + EXPECT_FALSE(IpInNetwork(testIp2, srcAddr, testNetmask)); +} + +HWTEST(AddressUtilsTest, IpInRangeTest, TestSize.Level1) +{ + uint32_t testNetmask = ParseIp(netmask26); + ASSERT_TRUE(testNetmask != 0); + uint32_t beginIp = ParseIpAddr("192.168.100.100"); + ASSERT_TRUE(beginIp != 0); + uint32_t endIp = LastIpAddress(beginIp, testNetmask); + ASSERT_TRUE(endIp != 0); + + uint32_t testIp1 = ParseIpAddr("192.168.100.90"); + EXPECT_TRUE(testIp1 != 0); + uint32_t testIp2= ParseIpAddr("192.168.100.130"); + EXPECT_TRUE(testIp2 != 0); + uint32_t testIp3= ParseIpAddr("192.168.100.120"); + EXPECT_TRUE(testIp3 != 0); + + EXPECT_FALSE(IpInRange(testIp1, beginIp, endIp, testNetmask)); + EXPECT_FALSE(IpInRange(testIp2, beginIp, endIp, testNetmask)); + EXPECT_TRUE(IpInRange(testIp3, beginIp, endIp, testNetmask)); +} + +HWTEST(AddressUtilsTest, BroadCastAddressTest, TestSize.Level1) +{ + uint8_t srcData[] = {192, 168, 100, 255}; + uint32_t srcAddr = ParseIp(srcData); + ASSERT_TRUE(srcAddr != 0); + uint32_t testNetmask = ParseIp(netmask24); + ASSERT_TRUE(testNetmask != 0); + uint32_t testIp1 = ParseIpAddr("192.168.100.120"); + EXPECT_TRUE(testIp1 != 0); + EXPECT_EQ(srcAddr, BroadCastAddress(testIp1, testNetmask)); +} + +HWTEST(AddressUtilsTest, ParseIpHtonlTest, TestSize.Level1) +{ + uint8_t srcData[] = {150, 100, 168, 192}; + uint32_t srcAddr = ParseIp(srcData); + ASSERT_TRUE(srcAddr != 0); + EXPECT_EQ(srcAddr, ParseIpHtonl("192.168.100.150")); +} + +HWTEST(AddressUtilsTest, NetworkBitsTest, TestSize.Level1) +{ + uint32_t mask1 = ParseIp(netmask24); + ASSERT_TRUE(mask1 != 0); + uint32_t mask2 = ParseIp(netmask25); + ASSERT_TRUE(mask2 != 0); + uint32_t mask3 = ParseIp(netmask26); + ASSERT_TRUE(mask3 != 0); + uint32_t mask4 = ParseIp(netmask27); + ASSERT_TRUE(mask4 != 0); + + EXPECT_EQ(24, NetworkBits(mask1)); + EXPECT_EQ(25, NetworkBits(mask2)); + EXPECT_EQ(26, NetworkBits(mask3)); + EXPECT_EQ(27, NetworkBits(mask4)); +} + +HWTEST(AddressUtilsTest, HostBitsTest, TestSize.Level1) +{ + uint32_t mask1 = ParseIp(netmask24); + ASSERT_TRUE(mask1 != 0); + uint32_t mask2 = ParseIp(netmask25); + ASSERT_TRUE(mask2 != 0); + uint32_t mask3 = ParseIp(netmask26); + ASSERT_TRUE(mask3 != 0); + uint32_t mask4 = ParseIp(netmask27); + ASSERT_TRUE(mask4 != 0); + + EXPECT_EQ(8, HostBits(mask1)); + EXPECT_EQ(7, HostBits(mask2)); + EXPECT_EQ(6, HostBits(mask3)); + EXPECT_EQ(5, HostBits(mask4)); +} + +HWTEST(AddressUtilsTest, IsEmptyHWAddrTest, TestSize.Level1) +{ + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0, 0, 0, 0, 0, 0, 0, 0x01}; + uint8_t testMac3[DHCP_HWADDR_LENGTH] = {0, 0xae, 0xdc, 0xcc, 0x9f, 0x43, 0}; + + EXPECT_TRUE(IsEmptyHWAddr(testMac1)); + EXPECT_TRUE(IsEmptyHWAddr(testMac2)); + EXPECT_FALSE(IsEmptyHWAddr(testMac3)); +} + +HWTEST(AddressUtilsTest, ParseStrMacTest, TestSize.Level1) +{ + uint8_t testMac[DHCP_HWADDR_LENGTH] = {0, 0xae, 0xdc, 0xcc, 0x9f, 0x43, 0}; + EXPECT_STREQ("00:ae:dc:cc:9f:43", ParseStrMac(testMac, MAC_ADDR_LENGTH)); +} + +HWTEST(AddressUtilsTest, HostToNetworkTest, TestSize.Level1) +{ + uint8_t srcData[] = {150, 100, 168, 192}; + uint32_t srcAddr = ParseIp(srcData); + ASSERT_TRUE(srcAddr != 0); + uint32_t testIp = ParseIpAddr("192.168.100.150"); + ASSERT_TRUE(testIp != 0); + EXPECT_EQ(srcAddr, HostToNetwork(testIp)); +} + +HWTEST(AddressUtilsTest, NetworkToHostTest, TestSize.Level1) +{ + uint8_t srcData[] = {192, 168, 100, 150}; + uint32_t srcAddr = ParseIp(srcData); + ASSERT_TRUE(srcAddr != 0); + uint8_t testData[] = {150, 100, 168, 192}; + uint32_t testAddr = ParseIp(testData); + ASSERT_TRUE(testAddr != 0); + EXPECT_EQ(srcAddr, NetworkToHost(testAddr)); +} + +HWTEST(AddressUtilsTest, ParseLogMacTest, TestSize.Level1) +{ + uint8_t testMac[DHCP_HWADDR_LENGTH] = {0, 0xae, 0xdc, 0xcc, 0x9f, 0x43, 0}; + EXPECT_STREQ("??:ae:??:??:9f:43", ParseLogMac(testMac)); +} + +HWTEST(AddressUtilsTest, AddrEquelsTest, TestSize.Level1) +{ + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0, 0xae, 0xdc, 0xcc, 0x9f, 0x43, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0, 0xae, 0xdc, 0xcc, 0x9f, 0x43, 0}; + uint8_t testMac3[DHCP_HWADDR_LENGTH] = {0, 0xae, 0xdc, 0xcc, 0x9f, 0x45, 0}; + + EXPECT_EQ(1, AddrEquels(testMac1, testMac2, MAC_ADDR_LENGTH)); + EXPECT_EQ(0, AddrEquels(testMac1, testMac3, MAC_ADDR_LENGTH)); + EXPECT_EQ(0, AddrEquels(testMac2, testMac3, MAC_ADDR_LENGTH)); +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_address_pool_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_address_pool_test.cpp new file mode 100644 index 000000000..8100e141c --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_address_pool_test.cpp @@ -0,0 +1,340 @@ +/* + * 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 "string_ex.h" +#include "dhcp_define.h" +#include "dhcp_ipv4.h" +#include "dhcp_message.h" +#include "dhcp_option.h" +#include "dhcp_address_pool.h" +#include "address_utils.h" +#include "common_util.h" + +using namespace testing::ext; + +class DhcpAddressPoolTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + if (InitAddressPool(&testPool, "lo", NULL)) { + printf("failed to initialized address pool.\n"); + } + } + virtual void TearDown() + { + FreeAddressPool(&testPool); + } + +public: + DhcpAddressPool testPool; + +}; + +HWTEST_F(DhcpAddressPoolTest, AddBindingTest, TestSize.Level1) +{ + AddressBinding bind = {0}; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0a, 0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.1"); + uint32_t testIp2 = ParseIpAddr("192.168.100.2"); + bind.ipAddress = testIp1; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac1[i]; + } + EXPECT_EQ(RET_SUCCESS, AddBinding(&bind)); + bind.ipAddress = testIp2; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac2[i]; + } + EXPECT_EQ(RET_SUCCESS, AddBinding(&bind)); + EXPECT_EQ(RET_FAILED, AddBinding(&bind)); + EXPECT_EQ(RET_SUCCESS, RemoveBinding(testMac1)); + EXPECT_EQ(RET_SUCCESS, RemoveBinding(testMac2)); +} + +HWTEST_F(DhcpAddressPoolTest, IsReservedTest, TestSize.Level1) +{ + AddressBinding bind = {0}; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0a, 0}; + uint8_t testMac3[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0b, 0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.1"); + ASSERT_TRUE(testIp1 != 0); + uint32_t testIp2 = ParseIpAddr("192.168.100.2"); + ASSERT_TRUE(testIp2 != 0); + bind.ipAddress = testIp1; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac1[i]; + } + EXPECT_EQ(RET_SUCCESS, AddBinding(&bind)); + bind.ipAddress = testIp2; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac2[i]; + } + EXPECT_EQ(RET_SUCCESS, AddReservedBinding(testMac2)); + EXPECT_EQ(RET_FAILED, AddBinding(&bind)); + EXPECT_EQ(0, IsReserved(testMac1)); + EXPECT_EQ(1, IsReserved(testMac2)); + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac3[i]; + } + EXPECT_EQ(0, IsReserved(testMac3)); + EXPECT_EQ(RET_SUCCESS, RemoveBinding(testMac1)); + EXPECT_EQ(RET_SUCCESS, RemoveBinding(testMac2)); +} + + +HWTEST_F(DhcpAddressPoolTest, IsReservedIpTest, TestSize.Level1) +{ + AddressBinding bind = {0}; + bind.bindingMode = BIND_MODE_DYNAMIC; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0a, 0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.1"); + ASSERT_TRUE(testIp1 != 0); + uint32_t testIp2 = ParseIpAddr("192.168.100.2"); + ASSERT_TRUE(testIp2 != 0); + bind.ipAddress = testIp1; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac1[i]; + } + EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &bind)); + bind.ipAddress = testIp2; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac2[i]; + } + bind.bindingMode = BIND_MODE_RESERVED; + EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &bind)); + EXPECT_EQ(0, IsReservedIp(&testPool, testIp1)); + EXPECT_EQ(1, IsReservedIp(&testPool, testIp2)); + bind.ipAddress = testIp1; + EXPECT_EQ(RET_SUCCESS, RemoveLease(&testPool, &bind)); + bind.ipAddress = testIp2; + EXPECT_EQ(RET_SUCCESS, RemoveLease(&testPool, &bind)); +} + +HWTEST_F(DhcpAddressPoolTest, RemoveReservedBindingTest, TestSize.Level1) +{ + AddressBinding bind = {0}, bind2 = {0}; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x01, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x00, 0x02, 0x3c, 0x65, 0x3a, 0x0a, 0}; + uint8_t testMac3[DHCP_HWADDR_LENGTH] = {0x00, 0x03, 0x3c, 0x65, 0x3a, 0x0b, 0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.1"); + EXPECT_TRUE(testIp1 != 0); + uint32_t testIp2 = ParseIpAddr("192.168.100.2"); + EXPECT_TRUE(testIp2 != 0); + bind.ipAddress = testIp1; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac1[i]; + } + EXPECT_EQ(RET_SUCCESS, AddBinding(&bind)); + bind2.ipAddress = testIp2; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind2.chaddr[i] = testMac2[i]; + } + bind2.bindingMode = BIND_MODE_RESERVED; + ASSERT_EQ(RET_SUCCESS, AddBinding(&bind2)); + EXPECT_EQ(RET_FAILED, RemoveReservedBinding(testMac1)); + EXPECT_EQ(RET_SUCCESS, RemoveBinding(testMac1)); + AddressBinding *binding = QueryBinding(testMac2, NULL); + ASSERT_TRUE(binding != NULL); + EXPECT_EQ(RET_SUCCESS, RemoveReservedBinding(testMac2)); + EXPECT_EQ(RET_FAILED, RemoveReservedBinding(testMac3)); +} + +HWTEST_F(DhcpAddressPoolTest, ReleaseBindingTest, TestSize.Level1) +{ + AddressBinding bind = {0}; + bind.bindingMode = BIND_ASSOCIATED; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0a, 0}; + uint8_t testMac3[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0b, 0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.1"); + ASSERT_TRUE(testIp1 != 0); + uint32_t testIp2 = ParseIpAddr("192.168.100.2"); + ASSERT_TRUE(testIp2 != 0); + bind.ipAddress = testIp1; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac1[i]; + } + ASSERT_EQ(RET_SUCCESS, AddBinding(&bind)); + bind.ipAddress = testIp2; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac2[i]; + } + ASSERT_EQ(RET_SUCCESS, AddBinding(&bind)); + EXPECT_EQ(RET_SUCCESS, ReleaseBinding(testMac1)); + EXPECT_EQ(RET_FAILED, ReleaseBinding(testMac3)); + EXPECT_EQ(RET_SUCCESS, RemoveBinding(testMac1)); + EXPECT_EQ(RET_SUCCESS, RemoveBinding(testMac2)); +} + +HWTEST_F(DhcpAddressPoolTest, AddLeaseTest, TestSize.Level1) +{ + AddressBinding lease = {0}; + lease.bindingMode = BIND_MODE_DYNAMIC; + lease.bindingStatus = BIND_ASSOCIATED; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3d, 0x65, 0x3a, 0x09, 0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.101"); + ASSERT_TRUE(testIp1 != 0); + lease.ipAddress = testIp1; + lease.leaseTime = DHCP_LEASE_TIME; + lease.pendingTime = 1631240659; + lease.bindingTime = 1631240659; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + lease.chaddr[i] = testMac1[i]; + } + ASSERT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + lease.chaddr[i] = testMac2[i]; + } + EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); + EXPECT_EQ(RET_SUCCESS, RemoveLease(&testPool, &lease)); +} + +HWTEST_F(DhcpAddressPoolTest, GetLeaseTest, TestSize.Level1) +{ + AddressBinding lease = {0}; + lease.bindingMode = BIND_MODE_DYNAMIC; + lease.bindingStatus = BIND_ASSOCIATED; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.101"); + ASSERT_TRUE(testIp1 != 0); + lease.ipAddress = testIp1; + lease.leaseTime = DHCP_LEASE_TIME; + lease.pendingTime = 1631240659; + lease.bindingTime = 1631240659; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + lease.chaddr[i] = testMac1[i]; + } + EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); + EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); + AddressBinding *leaseRec = GetLease(&testPool, testIp1); + ASSERT_TRUE(leaseRec != NULL); + EXPECT_EQ(lease.ipAddress, leaseRec->ipAddress); + EXPECT_EQ(lease.leaseTime, leaseRec->leaseTime); + EXPECT_EQ(lease.bindingMode, leaseRec->bindingMode); + EXPECT_EQ(lease.bindingStatus, leaseRec->bindingStatus); + EXPECT_EQ(RET_SUCCESS, RemoveLease(&testPool, &lease)); +} + +HWTEST_F(DhcpAddressPoolTest, UpdateLeaseTest, TestSize.Level1) +{ + AddressBinding lease = {0}; + lease.bindingMode = BIND_MODE_DYNAMIC; + lease.bindingStatus = BIND_ASSOCIATED; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.101"); + ASSERT_TRUE(testIp1 != 0); + lease.ipAddress = testIp1; + lease.leaseTime = DHCP_LEASE_TIME; + lease.pendingTime = 1631240659; + lease.bindingTime = 1631240659; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + lease.chaddr[i] = testMac1[i]; + } + EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); + AddressBinding *leaseRec = GetLease(&testPool, testIp1); + ASSERT_TRUE(leaseRec != NULL); + EXPECT_EQ(lease.ipAddress, leaseRec->ipAddress); + EXPECT_EQ(lease.leaseTime, leaseRec->leaseTime); + EXPECT_EQ(lease.bindingMode, leaseRec->bindingMode); + EXPECT_EQ(lease.bindingStatus, leaseRec->bindingStatus); + lease.pendingTime = 1631260680; + lease.bindingTime = 1631260680; + EXPECT_EQ(RET_SUCCESS, UpdateLease(&testPool, &lease)); + EXPECT_EQ(lease.leaseTime, leaseRec->leaseTime); + EXPECT_EQ(lease.leaseTime, leaseRec->leaseTime); + EXPECT_EQ(RET_SUCCESS, RemoveLease(&testPool, &lease)); +} + + +HWTEST_F(DhcpAddressPoolTest, LoadBindingRecodersTest, TestSize.Level1) +{ + AddressBinding lease = {0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.101"); + ASSERT_TRUE(testIp1 != 0); + uint32_t testIp2 = ParseIpAddr("192.168.100.102"); + ASSERT_TRUE(testIp2 != 0); + uint32_t testIp3 = ParseIpAddr("192.168.100.103"); + ASSERT_TRUE(testIp3!= 0); + + lease.bindingMode = BIND_MODE_DYNAMIC; + lease.bindingStatus = BIND_ASSOCIATED; + lease.pendingTime = 1631260680; + lease.bindingTime = 1631260680; + + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0a, 0}; + uint8_t testMac3[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0b, 0}; + lease.ipAddress = testIp1; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + lease.chaddr[i] = testMac1[i]; + } + EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); + lease.ipAddress = testIp2; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + lease.chaddr[i] = testMac2[i]; + } + EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); + lease.ipAddress = testIp3; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + lease.chaddr[i] = testMac3[i]; + } + EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); + + EXPECT_EQ(RET_SUCCESS, SaveBindingRecoders(&testPool, 1)); + EXPECT_EQ(HASH_SUCCESS, ClearAll(&testPool.leaseTable)); + EXPECT_TRUE(testPool.leaseTable.size == 0); + EXPECT_EQ(RET_SUCCESS, LoadBindingRecoders(&testPool)); + EXPECT_TRUE(testPool.leaseTable.size == 3); + EXPECT_TRUE(GetLease(&testPool, testIp1) != NULL); + EXPECT_TRUE(GetLease(&testPool, testIp2) != NULL); + EXPECT_TRUE(GetLease(&testPool, testIp3) != NULL); +} + +HWTEST_F(DhcpAddressPoolTest, GetBindingByMacTest, TestSize.Level1) +{ + AddressBinding lease = {0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.101"); + ASSERT_TRUE(testIp1 != 0); + + lease.bindingMode = BIND_MODE_DYNAMIC; + lease.bindingStatus = BIND_ASSOCIATED; + lease.pendingTime = 1631260680; + lease.bindingTime = 1631260680; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + + lease.ipAddress = testIp1; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + lease.chaddr[i] = testMac1[i]; + } + ASSERT_EQ(RET_SUCCESS, AddBinding(&lease)); + AddressBinding *binding = QueryBinding(testMac1, 0); + ASSERT_TRUE(binding != NULL); + EXPECT_EQ(lease.ipAddress, binding->ipAddress); + EXPECT_EQ(lease.leaseTime, binding->leaseTime); + EXPECT_EQ(lease.bindingMode, binding->bindingMode); + EXPECT_EQ(lease.bindingStatus, binding->bindingStatus); +} + diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_argument_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_argument_test.cpp new file mode 100644 index 000000000..06c1d6be4 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_argument_test.cpp @@ -0,0 +1,83 @@ +/* + * 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 +#include +#include "dhcp_argument.h" + +using namespace testing::ext; + +HWTEST(DhcpArgumentTest, InitArgumentsTest, TestSize.Level1) +{ + EXPECT_TRUE(InitArguments() == RET_SUCCESS); +} + +HWTEST(DhcpArgumentTest, ParseArgumentsTest, TestSize.Level1) +{ + char *argv[ARGUMENT_VALUE_SIZE] = { + const_cast(""), + const_cast("--dns=192.168.1.1,192.168.1.2"), + const_cast("--ifname=eth0") + }; + + EXPECT_TRUE(ParseArguments(3, argv) == RET_SUCCESS); + ArgumentInfo *arg = GetArgument("dns"); + EXPECT_TRUE(arg); + EXPECT_EQ(strncmp(arg->name, "dns", strlen("dns")), 0); + EXPECT_EQ(strncmp(arg->value, "192.168.1.1,192.168.1.2", strlen("192.168.1.1,192.168.1.2")), 0); + arg = GetArgument("ifname"); + EXPECT_TRUE(arg); + EXPECT_EQ(strncmp(arg->name, "ifname", strlen("ifname")), 0); + EXPECT_EQ(strncmp(arg->value, "eth0", strlen("eth0")), 0); +} + +HWTEST(DhcpArgumentTest, PutArgumentTest, TestSize.Level1) +{ + EXPECT_TRUE(PutArgument(NULL, NULL) == RET_FAILED); + const char *argu = "lease"; + const char *val = "4000"; + EXPECT_TRUE(PutArgument(NULL, val) == RET_FAILED); + EXPECT_TRUE(PutArgument(argu, NULL) == RET_FAILED); + EXPECT_TRUE(PutArgument(argu, val) == RET_SUCCESS); + argu = "xxxx"; + val = "nothing"; + EXPECT_TRUE(PutArgument(argu, val) == RET_SUCCESS); + EXPECT_TRUE(PutArgument(argu, val) == RET_FAILED); +} + +HWTEST(DhcpArgumentTest, GetArgumentTest, TestSize.Level1) +{ + ArgumentInfo *arg = GetArgument("lease"); + EXPECT_TRUE(arg); + EXPECT_EQ(0, strncmp(arg->name, "lease", strlen("lease"))); + EXPECT_EQ(0, strncmp(arg->value, "4000", strlen("4000"))); + + arg = GetArgument("xxxx"); + EXPECT_TRUE(arg); + EXPECT_EQ(0, strncmp(arg->name, "xxxx", strlen("xxxx"))); + EXPECT_EQ(0, strncmp(arg->value, "nothing", strlen("nothing"))); +} + +HWTEST(DhcpArgumentTest, HasArgumentTest, TestSize.Level1) +{ + const char *name = "xxx"; + EXPECT_TRUE(HasArgument(name) == 0); + name = "lease"; + EXPECT_TRUE(HasArgument(name) == 1); +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_binding_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_binding_test.cpp new file mode 100644 index 000000000..3a1db4307 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_binding_test.cpp @@ -0,0 +1,107 @@ +/* + * 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 "dhcp_binding.h" +#include "common_util.h" + +using namespace testing::ext; + +HWTEST(DhcpBindingTest, NextPendingIntervalTest, TestSize.Level1) +{ + uint64_t pendingInterval = 0; + EXPECT_TRUE(NextPendingInterval(pendingInterval) == pendingInterval + 1); + pendingInterval = 2; + EXPECT_TRUE(NextPendingInterval(pendingInterval) == pendingInterval + 1); + pendingInterval = 3; + EXPECT_TRUE(NextPendingInterval(pendingInterval) == pendingInterval + 2); + pendingInterval = 9; + EXPECT_TRUE(NextPendingInterval(pendingInterval) == pendingInterval + 2); + pendingInterval = 10; + EXPECT_TRUE(NextPendingInterval(pendingInterval) == pendingInterval + 5); + pendingInterval = 11; + EXPECT_TRUE(NextPendingInterval(pendingInterval) == pendingInterval + 5); + pendingInterval = 29; + EXPECT_TRUE(NextPendingInterval(pendingInterval) == pendingInterval + 5); + pendingInterval = 30; + EXPECT_TRUE(NextPendingInterval(pendingInterval) == 1200); + pendingInterval = 31; + EXPECT_TRUE(NextPendingInterval(pendingInterval) == 1200); + pendingInterval = (uint64_t)-1; + EXPECT_TRUE(NextPendingInterval(pendingInterval) == 1200); +} + +HWTEST(DhcpBindingTest, IsExpireTest, TestSize.Level1) +{ + EXPECT_EQ(IsExpire(nullptr), DHCP_FALSE); + AddressBinding binding; + ASSERT_TRUE(memset_s(&binding, sizeof(binding), 0, sizeof(binding)) == EOK); + EXPECT_EQ(IsExpire(&binding), DHCP_TRUE); + uint64_t curr = Tmspsec(); + binding.leaseTime = 60; + binding.bindingStatus = BIND_PENDING; + binding.pendingTime = curr - binding.leaseTime + 5; + EXPECT_EQ(IsExpire(&binding), DHCP_FALSE); + binding.bindingStatus = BIND_PENDING; + binding.pendingTime = curr - binding.leaseTime - 1; + EXPECT_EQ(IsExpire(&binding), DHCP_TRUE); + binding.bindingStatus = BIND_ASSOCIATED; + binding.bindingTime = curr - binding.leaseTime + 5; + EXPECT_EQ(IsExpire(&binding), DHCP_FALSE); + binding.bindingStatus = BIND_ASSOCIATED; + binding.bindingTime = curr - binding.leaseTime - 1; + EXPECT_EQ(IsExpire(&binding), DHCP_TRUE); +} + +HWTEST(DhcpBindingTest, WriteAddressBindingTest, TestSize.Level1) +{ + EXPECT_TRUE(WriteAddressBinding(nullptr, nullptr, 0) == RET_FAILED); + AddressBinding binding; + ASSERT_TRUE(memset_s(&binding, sizeof(binding), 0, sizeof(binding)) == EOK); + for (int i = 0; i <= NUM_FIVE; ++i) { + binding.chaddr[i] = (uint8_t)i; + } + binding.leaseTime = 60; + binding.bindingTime = 10; + binding.pendingTime = 11; + binding.pendingInterval = 2; + binding.bindingMode = 1; + binding.bindingStatus = 0; + char outBinding[1024] = {0}; + EXPECT_TRUE(WriteAddressBinding(&binding, outBinding, sizeof(outBinding)) == RET_SUCCESS); + std::string expectMsg = "00:01:02:03:04:05 0.0.0.0 60 10 11 2 1 0"; + EXPECT_TRUE(expectMsg == std::string(outBinding)); +} + +HWTEST(DhcpBindingTest, ParseAddressBindingTest, TestSize.Level1) +{ + std::string msg; + AddressBinding binding; + ASSERT_TRUE(memset_s(&binding, sizeof(binding), 0, sizeof(binding)) == EOK); + EXPECT_TRUE(ParseAddressBinding(&binding, msg.c_str()) == -1); + msg = "00:01:02:03:04:05 127.0.0.1 60 10 11 2 1"; + EXPECT_TRUE(ParseAddressBinding(&binding, msg.c_str()) == -1); + msg = "00:01:02:03:04:05 127.0.0.1 60 10 11 2 1 0"; + EXPECT_TRUE(ParseAddressBinding(&binding, msg.c_str()) == -1); + msg = "00:01:02:03:04:05 127.0.0.1 60 10 5 2 1 0"; + EXPECT_TRUE(ParseAddressBinding(&binding, msg.c_str()) == 0); + msg = "00:01:02:03:04:05 127.0.0.1 60 10 5 2 1 2"; + EXPECT_TRUE(ParseAddressBinding(&binding, msg.c_str()) == 0); + uint64_t curr = Tmspsec(); + msg = "00:01:02:03:04:05 127.0.0.1 60 " + std::to_string(curr + 60) + " " + std::to_string(curr + 10) + " 5 2 1 2"; + EXPECT_TRUE(ParseAddressBinding(&binding, msg.c_str()) == 0); +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_config_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_config_test.cpp new file mode 100644 index 000000000..2f4ed39e3 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_config_test.cpp @@ -0,0 +1,113 @@ +/* + * 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 "dhcp_config.h" + +using namespace testing::ext; + +class MockConfigFile { +public: + MockConfigFile() : mFilePath("./unittest_dhcp_config.conf") + {} + + ~MockConfigFile() + { + unlink(mFilePath.c_str()); + } + + void ClearAndWriteFile(const std::string &line) + { + FILE *fp = fopen(mFilePath.c_str(), "w"); + if (fp == nullptr) { + return; + } + fprintf(fp, "%s\n", line.c_str()); + fclose(fp); + return; + } + + void AppendFile(const std::string &line) + { + FILE *fp = fopen(mFilePath.c_str(), "w+"); + if (fp == nullptr) { + return; + } + fprintf(fp, "%s\n", line.c_str()); + fclose(fp); + return; + } + + std::string GetConfigFile() + { + return mFilePath; + } + +private: + std::string mFilePath; +}; + +HWTEST(DhcpConfigTest, LoadConfigTest, TestSize.Level1) +{ + EXPECT_TRUE(LoadConfig(nullptr, nullptr, nullptr) == RET_FAILED); + std::string configFile; + EXPECT_TRUE(LoadConfig(configFile.c_str(), nullptr, nullptr) == RET_FAILED); + std::string ifName; + EXPECT_TRUE(LoadConfig(configFile.c_str(), ifName.c_str(), nullptr) == RET_FAILED); + DhcpConfig config; + ASSERT_TRUE(memset_s(&config, sizeof(config), 0, sizeof(config)) == EOK); + MockConfigFile mockConfigFile; + configFile = mockConfigFile.GetConfigFile(); + ifName = "veryveryveryveryveryveryveryveryveryverylanginterface"; + EXPECT_TRUE(LoadConfig(configFile.c_str(), ifName.c_str(), &config) == RET_FAILED); + std::string content = "# comment \ninterface=" + ifName; + mockConfigFile.AppendFile(content); + EXPECT_TRUE(LoadConfig(configFile.c_str(), ifName.c_str(), &config) == RET_FAILED); + ifName = "wlan0"; + content = "interface=wlan0\ndns=255.255.255.256"; + mockConfigFile.ClearAndWriteFile(content); + EXPECT_TRUE(LoadConfig(configFile.c_str(), ifName.c_str(), &config) == RET_FAILED); + content = "interface=wlan0\ndns=8.8.8.8,114.114.114.114\npool=error_poll_msg"; + mockConfigFile.ClearAndWriteFile(content); + EXPECT_TRUE(LoadConfig(configFile.c_str(), ifName.c_str(), &config) == RET_FAILED); + content = "interface=wlan0\ndns=8.8.8.8,114.114.114.114\npool=a,b"; + mockConfigFile.ClearAndWriteFile(content); + EXPECT_TRUE(LoadConfig(configFile.c_str(), ifName.c_str(), &config) == RET_FAILED); + content = "interface=wlan0\ndns=8.8.8.8,114.114.114.114\npool=192.168.1.1,b"; + mockConfigFile.ClearAndWriteFile(content); + EXPECT_TRUE(LoadConfig(configFile.c_str(), ifName.c_str(), &config) == RET_FAILED); + content = "interface=wlan0\ndns=8.8.8.8,114.114.114.114\npool=192.168.1.10,192.168.1.100"; + mockConfigFile.ClearAndWriteFile(content); + EXPECT_TRUE(LoadConfig(configFile.c_str(), ifName.c_str(), &config) == RET_FAILED); + content = "interface=wlan0\ndns=8.8.8.8,114.114.114.114\npool=192.168.1.1,192.168.1.100\n" + "server=192.168.1.256"; + mockConfigFile.ClearAndWriteFile(content); + EXPECT_TRUE(LoadConfig(configFile.c_str(), ifName.c_str(), &config) == RET_FAILED); + content = "interface=wlan0\ndns=8.8.8.8,114.114.114.114\npool=192.168.1.10,192.168.1.100\n" + "server=192.168.1.2\ngateway=192.168.1.1\nnetmask=255.255.255.0\nleaseTime=0"; + mockConfigFile.ClearAndWriteFile(content); + EXPECT_TRUE(LoadConfig(configFile.c_str(), ifName.c_str(), &config) == RET_FAILED); + content = "interface=wlan0\ndns=8.8.8.8,114.114.114.114\npool=192.168.1.10,192.168.1.100\n" + "server=192.168.1.2\ngateway=192.168.1.1\nnetmask=255.255.255.0\nleaseTime=60\n" + "renewalTime=10\nrebindingTime=10\ndistribution=3"; + mockConfigFile.ClearAndWriteFile(content); + EXPECT_TRUE(LoadConfig(configFile.c_str(), ifName.c_str(), &config) == RET_FAILED); + content = "interface=wlan0\ndns=8.8.8.8,114.114.114.114\npool=192.168.1.10,192.168.1.100\n" + "server=192.168.1.2\ngateway=192.168.1.1\nnetmask=255.255.255.0\nleaseTime=60\n" + "renewalTime=10\nrebindingTime=10\ndistribution=0\nbroadcast=1\ninvalid_key=haha"; + mockConfigFile.ClearAndWriteFile(content); + EXPECT_TRUE(LoadConfig(configFile.c_str(), ifName.c_str(), &config) == RET_SUCCESS); +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_message_sim.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_message_sim.cpp new file mode 100644 index 000000000..9717cfc8c --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_message_sim.cpp @@ -0,0 +1,391 @@ +/* + * 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 "dhcp_message_sim.h" +#include +#include +#include +#include +#include +#include +#include +#include "dhcp_logger.h" +#include "dhcp_option.h" +#include "dhcp_ipv4.h" +#include "address_utils.h" +#include "securec.h" + +#define OPT_MESSAGE_TYPE_LEGTH 1 +#define OPT_HEADER_LENGTH 2 +#define OPT_TIME_LENGTH 4 +#define OPT_TYPE_FIELD_LENGTH 1 +#define OPT_MAC_ADDR_LENGTH 6 +#define MAGIC_COOKIE_LENGTH 4 +#define OPT_BROADCAST_FLAG_ENABLE 0 + +#define OFFER_MIN_INTERVAL_TIME 5 + +#define PENDING_DEFAULT_TIMEOUT 1200 +#define PENDING_DEFAULT_INTERVAL 1 +#define PENDING_INTERVAL_CHECKING_ENABLE 1 +#define DHCP_MAGIC_COOKIE 0x63825363 +#define ALLOW_NOBINDING_REQUEST 1 +#define REUSE_ADDRESS_ENABLE 1 +#define WAIT_STOPED_TIME 5 + +#undef LOG_TAG +#define LOG_TAG "DhcpMessageSimulator" + + +using namespace OHOS::Wifi; + +DhcpMsgManager& DhcpMsgManager::GetInstance() +{ + static DhcpMsgManager gMessageManager; + return gMessageManager; +} + +int DhcpMsgManager::SendTotal() +{ + int total = 0; + m_sendQueueLocker.lock(); + total = m_sendMessages.size(); + m_sendQueueLocker.unlock(); + return total; +} + +int DhcpMsgManager::RecvTotal() +{ + int total = 0; + m_recvQueueLocker.lock(); + total = m_recvMessages.size(); + m_recvQueueLocker.unlock(); + return total; +} + + +void DhcpMsgManager::PopSendMsg() +{ + m_sendQueueLocker.lock(); + if (!m_sendMessages.empty()) { + m_sendMessages.pop(); + } + m_sendQueueLocker.unlock(); +} + +void DhcpMsgManager::PopRecvMsg() +{ + m_recvQueueLocker.lock(); + if (!m_recvMessages.empty()) { + m_recvMessages.pop(); + } + m_recvQueueLocker.unlock(); +} + +int DhcpMsgManager::PushSendMsg(const DhcpMessage &msg) +{ + m_sendQueueLocker.lock(); + m_sendMessages.push(msg); + m_sendQueueLocker.unlock(); + return 1; +} + +int DhcpMsgManager::PushRecvMsg(const DhcpMessage &msg) +{ + m_recvQueueLocker.lock(); + m_recvMessages.push(msg); + m_recvQueueLocker.unlock(); + return 1; +} + +struct DhcpClientContext +{ + int clientFd; + int state; + DhcpClientConfig config; +}; + +struct sockaddr_in *BroadcastAddrIn(void) +{ + static struct sockaddr_in broadcastAddrIn = {0}; + if (broadcastAddrIn.sin_port == 0) { + broadcastAddrIn.sin_port = htons(DHCP_SERVER_PORT); + broadcastAddrIn.sin_family = AF_INET; + broadcastAddrIn.sin_addr.s_addr = INADDR_BROADCAST; + } + return &broadcastAddrIn; +} +struct sockaddr_in *DestinationAddr(void) +{ + static struct sockaddr_in destAddrIn = {0}; + if (destAddrIn.sin_port == 0) { + destAddrIn.sin_port = htons(DHCP_SERVER_PORT); + destAddrIn.sin_family = AF_INET; + destAddrIn.sin_addr.s_addr = INADDR_BROADCAST; + } + return &destAddrIn; +} + +int FillHwAddr(uint8_t *dst, size_t dsize, uint8_t *src, size_t ssize) +{ + if (!dst || !src) { + return DHCP_FALSE; + } + if (ssize > dsize){ + return DHCP_FALSE; + } + if (memset_s(dst, dsize, 0, dsize) != EOK) { + return DHCP_FALSE; + } + if (memcpy_s(dst, dsize, src, ssize) != EOK) { + return DHCP_FALSE; + } + return DHCP_TRUE; +} + +struct sockaddr_in *SetDestinationAddr(uint32_t ipAddress) +{ + struct sockaddr_in *destAddr = DestinationAddr(); + destAddr->sin_addr.s_addr = htons(ipAddress); + return destAddr; +} + +DhcpClientContext *InitialDhcpClient(DhcpClientConfig *config) +{ + LOGD("init dhcp client."); + if (!config) { + return NULL; + } + DhcpClientContext *context = (DhcpClientContext *)calloc(1, sizeof(DhcpClientContext)); + if (context == NULL) { + LOGE("failed to calloc client context."); + return NULL; + } + if (memset_s(context, sizeof(DhcpClientContext), 0, sizeof(DhcpClientContext)) != EOK) { + LOGE("failed to reset client context."); + free(context); + return NULL; + } + if (memset_s(context->config.ifname, IFACE_NAME_SIZE, '\0', IFACE_NAME_SIZE) != EOK) { + LOGE("failed to reset interface name."); + free(context); + return NULL; + } + if (strncpy_s(context->config.ifname, IFACE_NAME_SIZE, config->ifname, strlen(config->ifname)) != EOK) { + LOGE("failed to set interface name."); + free(context); + return NULL; + } + if (!FillHwAddr(context->config.chaddr, DHCP_HWADDR_LENGTH, config->chaddr, MAC_ADDR_LENGTH)) { + LOGE("failed to set chaddr."); + free(context); + return NULL; + } + context->clientFd = 1; + return context; +} + +static int ParseDhcpOptions(PDhcpMsgInfo msg) +{ + int ret; + PDhcpOptionNode pNode = msg->options.first->next; + DhcpOption endOpt = {END_OPTION, 0}; + PushBackOption(&msg->options, &endOpt); + int replyOptsLength = 0; + uint8_t *current = msg->packet.options, olen = MAGIC_COOKIE_LENGTH; + uint32_t cookie = htonl(DHCP_MAGIC_COOKIE); + if (memcpy_s(current, olen, &cookie, olen) != EOK) { + LOGE("memcpy cookie out of options buffer!"); + return RET_FAILED; + } + replyOptsLength += olen; + current += olen; + ret = RET_SUCCESS; + while (pNode && (uint32_t)pNode->option.length < DHCP_OPTION_SIZE) { + if ((uint32_t)pNode->option.code == END_OPTION) { + olen = OPT_HEADER_LENGTH + 1; + } else { + olen = OPT_HEADER_LENGTH + pNode->option.length; + } + if (memcpy_s(current, olen, &pNode->option, olen) != EOK) { + LOGE("memcpy current option out of options buffer!"); + ret = RET_FAILED; + break; + } + current += olen; + replyOptsLength += olen; + if ((uint32_t)pNode->option.code == END_OPTION) { + break; + } + pNode = pNode->next; + if (replyOptsLength >= DHCP_OPTIONS_SIZE) { + LOGE("current option out of options buffer!"); + ret = RET_FAILED; + break; + } + } + msg->length += replyOptsLength; + return ret; +} + + +int SendDhcpMessage(DhcpClientContext *ctx, PDhcpMsgInfo msg) +{ + if (!ctx || !msg) { + LOGE("client context or message pointer is null."); + return RET_FAILED; + } + if (ParseDhcpOptions(msg) != RET_SUCCESS) { + LOGE("failed to parse dhcp message info."); + return RET_FAILED; + } + DhcpMsgManager::GetInstance().PushSendMsg(msg->packet); + return RET_SUCCESS; +} + +static uint32_t GetXid(int update) +{ + static uint32_t currXid = Tmspsec(); + if (update) { + currXid = Tmspsec(); + } + return currXid; +} + +static int InitMessage(DhcpClientContext *ctx, PDhcpMsgInfo msg, uint8_t msgType) +{ + LOGD("init dhcp message..."); + if (!ctx) { + LOGD("client context pointer is null."); + return DHCP_FALSE; + } + if (!msg) { + LOGD("dhcp message pointer is null."); + return DHCP_FALSE; + } + if (memset_s(msg, sizeof(DhcpMsgInfo), 0, sizeof(DhcpMsgInfo)) != EOK) { + LOGD("message info pointer is null."); + return DHCP_FALSE; + } + if (InitOptionList(&msg->options) != RET_SUCCESS) { + LOGD("failed to initialize dhcp client options."); + return DHCP_FALSE; + } + if (!FillHwAddr(msg->packet.chaddr, DHCP_HWADDR_LENGTH, ctx->config.chaddr, MAC_ADDR_LENGTH)) { + return DHCP_FALSE; + } + msg->packet.op = BOOTREQUEST; + msg->packet.htype = 0x01; + msg->packet.hlen = MAC_ADDR_LENGTH; + if (msgType == DHCPDISCOVER) { + msg->packet.xid = GetXid(DHCP_TRUE); + } else { + msg->packet.xid = GetXid(DHCP_FALSE); + } + DhcpOption optMsgType = {DHCP_MESSAGE_TYPE_OPTION, OPT_MESSAGE_TYPE_LEGTH, {msgType, 0}}; + PushFrontOption(&msg->options, &optMsgType); + + return DHCP_TRUE; +} + +int DhcpDiscover(DhcpClientContext *ctx) +{ + if (!ctx) { + return RET_FAILED; + } + DhcpMsgInfo msgInfo; + if (!InitMessage(ctx, &msgInfo, DHCPDISCOVER)) { + LOGD("failed to init dhcp message."); + return RET_FAILED; + } + if (SendDhcpMessage(ctx, &msgInfo) != RET_SUCCESS) { + LOGD("failed to send dhcp message."); + return RET_FAILED; + } + LOGD("send dhcp discover..."); + return RET_SUCCESS; +} + +int DhcpRequest(DhcpClientContext *ctx) +{ + if (!ctx) { + return RET_FAILED; + } + DhcpMsgInfo msgInfo; + if (!InitMessage(ctx, &msgInfo, DHCPREQUEST)) { + LOGD("failed to init dhcp message."); + return RET_FAILED; + } + if (SendDhcpMessage(ctx, &msgInfo) != RET_SUCCESS) { + LOGD("failed to send dhcp message."); + return RET_FAILED; + } + LOGD("send dhcp request..."); + return RET_SUCCESS; +} + +int DhcpInform(DhcpClientContext *ctx) +{ + if (!ctx) { + return RET_FAILED; + } + DhcpMsgInfo msgInfo; + if (!InitMessage(ctx, &msgInfo, DHCPINFORM)) { + LOGD("failed to init dhcp message."); + return RET_FAILED; + } + if (SendDhcpMessage(ctx, &msgInfo) != RET_SUCCESS) { + LOGD("failed to send dhcp message."); + return RET_FAILED; + } + LOGD("send dhcp inform..."); + return RET_SUCCESS; +} + +int DhcpDecline(DhcpClientContext *ctx) +{ + if (!ctx) { + return RET_FAILED; + } + DhcpMsgInfo msgInfo; + if (!InitMessage(ctx, &msgInfo, DHCPDECLINE)) { + LOGD("failed to init dhcp message."); + return RET_FAILED; + } + if (SendDhcpMessage(ctx, &msgInfo) != RET_SUCCESS) { + LOGD("failed to send dhcp message."); + return RET_FAILED; + } + LOGD("send dhcp decline..."); + return RET_SUCCESS; +} + +int DhcpRelease(DhcpClientContext *ctx) +{ + if (!ctx) { + return RET_FAILED; + } + DhcpMsgInfo msgInfo; + if (!InitMessage(ctx, &msgInfo, DHCPRELEASE)) { + LOGD("failed to init dhcp message."); + return RET_FAILED; + } + if (SendDhcpMessage(ctx, &msgInfo) != RET_SUCCESS) { + LOGD("failed to send dhcp message."); + return RET_FAILED; + } + LOGD("send dhcp release..."); + return RET_SUCCESS; +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_message_sim.h b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_message_sim.h new file mode 100644 index 000000000..1335bad5e --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_message_sim.h @@ -0,0 +1,91 @@ +/* + * 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 "dhcp_message.h" + +#ifndef OHOS_DHCP_MESSAGE_SIM_H +#define OHOS_DHCP_MESSAGE_SIM_H + +typedef struct DhcpClientConfig DhcpClientConfig; + +typedef struct DhcpClientContext DhcpClientContext; + + +namespace OHOS { +namespace Wifi { +class DhcpMsgManager +{ +public: + static DhcpMsgManager &GetInstance(void); + + int SendTotal(); + + int RecvTotal(); + + int PushSendMsg(const DhcpMessage &msg); + int PushRecvMsg(const DhcpMessage &msg); + + void PopSendMsg(); + void PopRecvMsg(); +private: + DhcpMsgManager(){}; + ~DhcpMsgManager(){}; + + std::mutex m_recvQueueLocker; + std::queue m_recvMessages; + std::mutex m_sendQueueLocker; + std::queue m_sendMessages; +}; +} // namespace Wifi +} // namespace OHOS + +typedef struct { + int (*OnReceivedOffer)(DhcpMessage *msg); + int (*OnReceivedNak)( DhcpMessage *msg); + int (*OnReceivedAck)(DhcpMessage *msg); +} DhcpClientCallback; + +struct DhcpClientConfig +{ + char ifname[IFACE_NAME_SIZE]; + uint8_t chaddr[DHCP_HWADDR_LENGTH]; +}; + +DhcpClientContext *InitialDhcpClient(DhcpClientConfig *config); + +int *StatrDhcpClient(DhcpClientContext *config); + +int SendDhcpMessage(DhcpClientContext *ctx, PDhcpMsgInfo *msg); + +int DhcpDiscover(DhcpClientContext *ctx); + +int DhcpRequest(DhcpClientContext *ctx); + +int DhcpInform(DhcpClientContext *ctx); + +int DhcpDecline(DhcpClientContext *ctx); + +int DhcpRelease(DhcpClientContext *ctx); + +int StopDhcpClient(DhcpClientContext *ctx); + +int GetDhcpClinetState(DhcpClientContext *ctx); + +int FreeDhcpClient(DhcpClientContext *ctx); +int FillHwAddr(uint8_t *dst, size_t dsize, uint8_t *src, size_t ssize); + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_option_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_option_test.cpp new file mode 100644 index 000000000..28cc6bc93 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_option_test.cpp @@ -0,0 +1,151 @@ +/* + * 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 "string_ex.h" +#include "dhcp_define.h" +#include "dhcp_ipv4.h" +#include "dhcp_message.h" +#include "dhcp_option.h" +#include "address_utils.h" + +using namespace testing::ext; + +class DhcpOptionTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + if (InitOptionList(&options)) { + printf("failed to initialized hash table.\n"); + } + } + virtual void TearDown() + { + FreeOptionList(&options); + } +public: + DhcpOptionList options; +}; + +HWTEST_F(DhcpOptionTest, InitOptionListTest, TestSize.Level1) +{ + DhcpOptionList testOpts; + EXPECT_EQ(RET_SUCCESS, InitOptionList(&testOpts)); + FreeOptionList(&testOpts); + EXPECT_EQ(RET_SUCCESS, InitOptionList(&options)); +} + +HWTEST_F(DhcpOptionTest, HasInitializedTest, TestSize.Level1) +{ + DhcpOptionList testOpts = {0}; + EXPECT_EQ(0, HasInitialized(&testOpts)); + EXPECT_EQ(1, HasInitialized(&options)); +} + +HWTEST_F(DhcpOptionTest, PushBackOptionTest, TestSize.Level1) +{ + DhcpOption optRouter = {ROUTER_OPTION, 0, {0}}; + EXPECT_EQ(RET_SUCCESS, PushBackOption(&options, &optRouter)); + + DhcpOption optMsgType = {DHCP_MESSAGE_TYPE_OPTION, 1, {DHCPOFFER, 0}}; + EXPECT_EQ(RET_SUCCESS, PushBackOption(&options, &optMsgType)); + EXPECT_TRUE(options.size == 2); + ClearOptions(&options); + EXPECT_TRUE(options.size == 0); +} + +HWTEST_F(DhcpOptionTest, PushFrontOptionTest, TestSize.Level1) +{ + DhcpOption optRouter = {ROUTER_OPTION, 0, {0}}; + EXPECT_EQ(RET_SUCCESS, PushFrontOption(&options, &optRouter)); + + DhcpOption optMsgType = {DHCP_MESSAGE_TYPE_OPTION, 1, {DHCPOFFER, 0}}; + EXPECT_EQ(RET_SUCCESS, PushFrontOption(&options, &optMsgType)); + EXPECT_TRUE(options.size == 2); + ClearOptions(&options); + EXPECT_TRUE(options.size == 0); +} + +HWTEST_F(DhcpOptionTest, GetOptionNodeTest, TestSize.Level1) +{ + DhcpOption optRouter = {ROUTER_OPTION, 0, {0}}; + EXPECT_EQ(RET_SUCCESS, PushFrontOption(&options, &optRouter)); + DhcpOption optMsgType = {DHCP_MESSAGE_TYPE_OPTION, 1, {DHCPOFFER, 0}}; + EXPECT_EQ(RET_SUCCESS, PushFrontOption(&options, &optMsgType)); + EXPECT_TRUE(options.size == 2); + + DhcpOptionNode *node = GetOptionNode(&options, DHCP_MESSAGE_TYPE_OPTION); + EXPECT_TRUE(node!=NULL); + ClearOptions(&options); + EXPECT_TRUE(options.size == 0); +} + +HWTEST_F(DhcpOptionTest, GetOptionTest, TestSize.Level1) +{ + DhcpOption optRouter = {ROUTER_OPTION, 0, {0}}; + EXPECT_EQ(RET_SUCCESS, PushFrontOption(&options, &optRouter)); + DhcpOption optMsgType = {DHCP_MESSAGE_TYPE_OPTION, 1, {DHCPOFFER, 0}}; + EXPECT_EQ(RET_SUCCESS, PushFrontOption(&options, &optMsgType)); + EXPECT_TRUE(options.size == 2); + + DhcpOption *node = GetOption(&options, DHCP_MESSAGE_TYPE_OPTION); + EXPECT_TRUE(node!=NULL); + ClearOptions(&options); + EXPECT_TRUE(options.size == 0); +} + +HWTEST_F(DhcpOptionTest, FillOptionTest, TestSize.Level1) +{ + const char *serverInfo = "dhcp server 1.0"; + DhcpOption optVendorInfo = {VENDOR_SPECIFIC_INFO_OPTION, 0, {0}}; + EXPECT_EQ(RET_SUCCESS, FillOption(&optVendorInfo, serverInfo, strlen(serverInfo))); +} + +HWTEST_F(DhcpOptionTest, FillOptionDataTest, TestSize.Level1) +{ + uint8_t testData[] = {192, 168, 100, 254}; + DhcpOption optRouter = {ROUTER_OPTION, 0, {0}}; + EXPECT_EQ(RET_SUCCESS, FillOptionData(&optRouter, testData, sizeof(testData))); +} + +HWTEST_F(DhcpOptionTest, FillU32OptionTest, TestSize.Level1) +{ + uint32_t testIp = ParseIpAddr("192.168.100.254"); + EXPECT_TRUE(testIp != 0); + DhcpOption optRouter = {ROUTER_OPTION, 0, {0}}; + EXPECT_EQ(RET_SUCCESS, FillU32Option(&optRouter, testIp)); +} + +HWTEST_F(DhcpOptionTest, AppendAddressOptionTest, TestSize.Level1) +{ + uint32_t testDns1 = ParseIpAddr("192.168.100.1"); + EXPECT_TRUE(testDns1 != 0); + uint32_t testDns2 = ParseIpAddr("192.168.100.2"); + EXPECT_TRUE(testDns2 != 0); + uint32_t testDns3 = ParseIpAddr("192.168.100.3"); + EXPECT_TRUE(testDns3 != 0); + + DhcpOption optDns = {DOMAIN_NAME_SERVER_OPTION, 0, {0}}; + EXPECT_EQ(RET_SUCCESS, AppendAddressOption(&optDns, testDns1)); + EXPECT_EQ(RET_SUCCESS, AppendAddressOption(&optDns, testDns2)); + EXPECT_EQ(RET_SUCCESS, AppendAddressOption(&optDns, testDns3)); + EXPECT_EQ(12, optDns.length); +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_server_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_server_test.cpp new file mode 100644 index 000000000..28558aa9a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_server_test.cpp @@ -0,0 +1,210 @@ +/* + * 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 +#include +#include "string_ex.h" +#include "dhcp_server.h" +#include "address_utils.h" +#include "dhcp_config.h" +#include "dhcp_option.h" +#include "dhcp_logger.h" +#include "system_func_mock.h" +#include "dhcp_message_sim.h" +#include "securec.h" + +using namespace testing::ext; +using namespace std; +using namespace OHOS::Wifi; + +#undef LOG_TAG +#define LOG_TAG "DhcpServerTest" + +static const int SERVER_RUNING_TIME = 10; //the value is in units of seconds. +class DhcpServerTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} + + int InitServerConfig(DhcpConfig *config); + int FreeServerConfig(DhcpConfig *config); + + int InitDhcpClient(); + void ServerRun(void); + bool StartServerTest(); + bool StopServerTest(); + +private: + DhcpServerContext *m_pServerCtx = NULL; + DhcpConfig m_serverConfg; + thread testSrvTh; + + DhcpClientContext *m_pMockClient = NULL; + DhcpClientConfig m_clientConfg; +}; + +int DhcpServerTest::InitServerConfig(DhcpConfig *config) +{ + if (!config) { + return RET_FAILED; + } + const char* testIfaceName = "wlan0"; + uint32_t serverId = ParseIpAddr("192.168.188.254"); + uint32_t netmask = ParseIpAddr("255.255.255.0"); + uint32_t beginIp = ParseIpAddr("192.168.188.100"); + uint32_t endIp = ParseIpAddr("192.168.188.150"); + if (serverId == 0 || netmask == 0 || beginIp == 0 || endIp == 0) { + printf("failed to parse address.\n"); + return RET_FAILED; + } + if (memset_s(config, sizeof(DhcpConfig), 0, sizeof(DhcpConfig)) != EOK) { + return RET_FAILED; + } + if (memset_s(config->ifname, sizeof(config->ifname), '\0', sizeof(config->ifname)) != EOK) { + return RET_FAILED; + } + if (strncpy_s(config->ifname, sizeof(config->ifname), testIfaceName, sizeof(config->ifname)) != EOK) { + return RET_FAILED; + } + config->serverId = serverId; + config->netmask = netmask; + config->pool.beginAddress = beginIp; + config->pool.endAddress = endIp; + if (InitOptionList(&config->options) != RET_SUCCESS) { + return RET_FAILED; + } + return RET_SUCCESS; +} + +void DhcpServerTest::ServerRun(void) +{ + LOGD("begin test start dhcp server."); + SystemFuncMock::GetInstance().SetMockFlag(true); + EXPECT_CALL(SystemFuncMock::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(SystemFuncMock::GetInstance(), setsockopt(_, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), select(_, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), recvfrom(_, _, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), bind(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), close(_)).WillRepeatedly(Return(0)); + m_pServerCtx = InitializeServer(&m_serverConfg); + if (!m_pServerCtx) { + LOGE("failed to initialized dhcp server context."); + } + if (m_pServerCtx && StartDhcpServer(m_pServerCtx) != RET_SUCCESS) { + printf("failed to start dhcp server. \n"); + } + SystemFuncMock::GetInstance().SetMockFlag(false); +} +bool DhcpServerTest::StartServerTest() +{ + SystemFuncMock::GetInstance().SetMockFlag(true); + EXPECT_CALL(SystemFuncMock::GetInstance(), close(_)).WillRepeatedly(Return(0)); + bool retval = true; + if (InitServerConfig(&m_serverConfg) != RET_SUCCESS) { + LOGD("failed to initialized dhcp server config."); + retval = false; + } + testSrvTh = std::thread(std::bind(&DhcpServerTest::ServerRun, this)); + testSrvTh.detach(); + sleep(SERVER_RUNING_TIME); + if (retval && StopServerTest() != RET_SUCCESS) { + retval = false; + } + sleep(6); + if (m_pServerCtx) { + FreeServerContex(m_pServerCtx); + m_pServerCtx = NULL; + } + SystemFuncMock::GetInstance().SetMockFlag(false); + return retval; +} + +bool DhcpServerTest::StopServerTest() +{ + printf("begin stop dhcp server. \n"); + if (!m_pServerCtx) { + return false; + } + if (StopDhcpServer(m_pServerCtx) != RET_SUCCESS) { + return false; + } + return true; +} + +int DhcpServerTest::InitDhcpClient() +{ + LOGD("init mock dhcp client."); + const char* testIfname = "wlan0"; + uint8_t testMac[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + + if (memset_s(&m_clientConfg, sizeof(DhcpClientConfig), 0, sizeof(DhcpClientConfig)) != EOK) { + return RET_FAILED; + } + if (!FillHwAddr(m_clientConfg.chaddr, DHCP_HWADDR_LENGTH, testMac, MAC_ADDR_LENGTH)) { + return RET_FAILED; + } + if (memset_s(m_clientConfg.ifname, IFACE_NAME_SIZE, '\0', IFACE_NAME_SIZE) != EOK) { + return RET_FAILED; + } + if (memcpy_s(m_clientConfg.ifname, IFACE_NAME_SIZE, testIfname, strlen(testIfname)) != EOK) { + return RET_FAILED; + } + m_pMockClient = InitialDhcpClient(&m_clientConfg); + + if (!m_pMockClient) { + return RET_FAILED; + } + return DhcpDiscover(m_pMockClient); +} + +int DhcpServerTest::FreeServerConfig(DhcpConfig *config) +{ + if (!config) { + return RET_FAILED; + } + FreeOptionList(&config->options); + return RET_SUCCESS; +} + +HWTEST_F(DhcpServerTest, InitializeServerTest, TestSize.Level1) +{ + SystemFuncMock::GetInstance().SetMockFlag(true); + EXPECT_CALL(SystemFuncMock::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(SystemFuncMock::GetInstance(), setsockopt(_, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), select(_, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), recvfrom(_, _, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), bind(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), close(_)).WillRepeatedly(Return(0)); + + DhcpConfig config; + PDhcpServerContext ctx = InitializeServer(&config); + EXPECT_TRUE(ctx == NULL); + EXPECT_EQ(RET_SUCCESS, InitServerConfig(&config)); + ctx = InitializeServer(&config); + ASSERT_TRUE(ctx != NULL); + EXPECT_EQ(RET_SUCCESS, FreeServerConfig(&config)); + EXPECT_EQ(RET_SUCCESS, FreeServerContex(ctx)); + SystemFuncMock::GetInstance().SetMockFlag(false); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/hash_table_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/hash_table_test.cpp new file mode 100644 index 000000000..7500b394b --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/hash_table_test.cpp @@ -0,0 +1,167 @@ +/* + * 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 "string_ex.h" +#include "hash_table.h" + +using namespace testing::ext; + +class HashTableTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + if (CreateHashTable(&table, sizeof(uint32_t), sizeof(uint32_t), HASH_MINI_CAPACITY) != HASH_SUCCESS) { + printf("failed to create hash table.\n"); + } + } + virtual void TearDown() + { + if (Initialized(&table)) { + DestroyHashTable(&table); + } + } +public: + HashTable table; +}; + + +HWTEST_F(HashTableTest, InitializedTest, TestSize.Level1) +{ + HashTable testTable = {0}; + EXPECT_EQ(0, Initialized(&testTable)); + EXPECT_EQ(0, Initialized(0)); + EXPECT_EQ(1, Initialized(&table)); +} + +HWTEST_F(HashTableTest, InsertTest, TestSize.Level1) +{ + uint32_t keyOffset = 100; + uint32_t valOffset = 1000; + size_t expectSize = 100; + + EXPECT_TRUE(Initialized(&table)); + int testRet = 1; + for (size_t i = 0; i < expectSize; i++) + { + uint32_t key = keyOffset + i; + uint32_t val = valOffset; + if (Insert(&table, (uintptr_t)&key, (uintptr_t)&val) != HASH_INSERTED) { + printf("failed to test insert.\n"); + testRet = 0; + } + } + uint32_t updateKey = keyOffset; + uint32_t updateVal = 1000; + EXPECT_TRUE(Insert(&table, (uintptr_t)&updateKey, (uintptr_t)&updateVal) == HASH_UPDATED); + EXPECT_TRUE(testRet); + EXPECT_TRUE(expectSize == table.size); + EXPECT_EQ(HASH_SUCCESS, ClearAll(&table)); + EXPECT_TRUE(table.size == 0); +} + +HWTEST_F(HashTableTest, ContainsKeyTest, TestSize.Level1) +{ + uint32_t key1 = 1001; + uint32_t val1 = 2001; + uint32_t key2 = 1002; + uint32_t val2 = 2002; + uint32_t key3 = 1003; + uint32_t val3 = 2003; + + EXPECT_EQ(HASH_INSERTED, Insert(&table, (uintptr_t)&key1, (uintptr_t)&val1)); + EXPECT_EQ(HASH_INSERTED, Insert(&table, (uintptr_t)&key2, (uintptr_t)&val2)); + EXPECT_EQ(HASH_INSERTED, Insert(&table, (uintptr_t)&key3, (uintptr_t)&val3)); + EXPECT_EQ(HASH_UPDATED, Insert(&table, (uintptr_t)&key3, (uintptr_t)&val3)); + uint32_t testKey = 1002; + uint32_t testKey2 = 6002; + EXPECT_EQ(1, ContainsKey(&table, (uintptr_t)&testKey)); + EXPECT_EQ(0, ContainsKey(&table, (uintptr_t)&testKey2)); + EXPECT_EQ(HASH_SUCCESS, ClearAll(&table)); + EXPECT_TRUE(table.size == 0); +} + +HWTEST_F(HashTableTest, GetAtTest, TestSize.Level1) +{ + uint32_t key1 = 1001; + uint32_t val1 = 2001; + uint32_t key2 = 1002; + uint32_t val2 = 2002; + uint32_t key3 = 1003; + uint32_t val3 = 2003; + + EXPECT_EQ(HASH_INSERTED, Insert(&table, (uintptr_t)&key1, (uintptr_t)&val1)); + EXPECT_EQ(HASH_INSERTED, Insert(&table, (uintptr_t)&key2, (uintptr_t)&val2)); + EXPECT_EQ(HASH_INSERTED, Insert(&table, (uintptr_t)&key3, (uintptr_t)&val3)); + + uint32_t testKey = 1002; + uint32_t expectVal = val2; + uintptr_t valPtr = At(&table, (uintptr_t)&testKey); + uint32_t rstVal = 0; + if (valPtr) { + rstVal = *(uint32_t*)valPtr; + } + EXPECT_EQ(expectVal, rstVal); + EXPECT_EQ(HASH_SUCCESS, ClearAll(&table)); + EXPECT_TRUE(table.size == 0); +} + +HWTEST_F(HashTableTest, RemoveTest, TestSize.Level1) +{ + uint32_t key1 = 1001; + uint32_t val1 = 2001; + uint32_t key2 = 1002; + uint32_t val2 = 2002; + uint32_t key3 = 1003; + uint32_t val3 = 2003; + + EXPECT_EQ(HASH_INSERTED, Insert(&table, (uintptr_t)&key1, (uintptr_t)&val1)); + EXPECT_EQ(HASH_INSERTED, Insert(&table, (uintptr_t)&key2, (uintptr_t)&val2)); + EXPECT_EQ(HASH_INSERTED, Insert(&table, (uintptr_t)&key3, (uintptr_t)&val3)); + + uint32_t testKey = 1002; + EXPECT_EQ(1, ContainsKey(&table, (uintptr_t)&testKey)); + EXPECT_EQ(HASH_SUCCESS, Remove(&table, (uintptr_t)&testKey)); + EXPECT_EQ(0, ContainsKey(&table, (uintptr_t)&testKey)); + EXPECT_EQ(HASH_SUCCESS, ClearAll(&table)); + EXPECT_TRUE(table.size == 0); +} + +HWTEST_F(HashTableTest, EmptyTest, TestSize.Level1) +{ + EXPECT_EQ(HASH_ERROR, Empty(0)); + EXPECT_EQ(HASH_SUCCESS, Empty(&table)); + uint32_t key1 = 1001; + uint32_t val1 = 2001; + EXPECT_TRUE(Insert(&table, (uintptr_t)&key1, (uintptr_t)&val1) == HASH_INSERTED); + EXPECT_EQ(HASH_NOT_EMPTY, Empty(&table)); +} + +HWTEST_F(HashTableTest, ResizeTest, TestSize.Level1) +{ + HashTable testTable; + EXPECT_EQ(HASH_SUCCESS, CreateHashTable(&testTable, sizeof(uint32_t), + sizeof(uint32_t), HASH_MINI_CAPACITY)); + EXPECT_TRUE(testTable.capacity == HASH_MINI_CAPACITY); + EXPECT_EQ(HASH_SUCCESS, Resize(&testTable, HASH_MINI_CAPACITY * 2)); + EXPECT_TRUE(testTable.capacity == HASH_MINI_CAPACITY * 2); + EXPECT_EQ(HASH_SUCCESS, DestroyHashTable(&testTable)); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/system_func_mock.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/system_func_mock.cpp new file mode 100644 index 000000000..6d5b89659 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/system_func_mock.cpp @@ -0,0 +1,155 @@ +/* + * 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 "system_func_mock.h" +#include +#include +#include +#include +#include +#include "dhcp_logger.h" +#include "dhcp_message_sim.h" + +using namespace OHOS::Wifi; + +#undef LOG_TAG +#define LOG_TAG "DhcpServerSystemFuncMock" + +#define TIME_SEC_TO_USEC (1000 * 1000) +#define DHCP_SEL_WAIT_TIMEOUTS 1500 + +static bool g_mockTag = false; + +SystemFuncMock &SystemFuncMock::GetInstance() +{ + static SystemFuncMock gSystemFuncMock; + return gSystemFuncMock; +}; + +SystemFuncMock::SystemFuncMock() +{} + +SystemFuncMock::~SystemFuncMock() +{} + +void SystemFuncMock::SetMockFlag(bool flag) +{ + g_mockTag = flag; +} + +bool SystemFuncMock::GetMockFlag(void) +{ + return g_mockTag; +} + +extern "C" { +int __real_socket(int __domain, int __type, int __protocol); +int __wrap_socket(int __domain, int __type, int __protocol) +{ + LOGD("==>socket."); + if (g_mockTag) { + LOGD(" ==>mock enable."); + return SystemFuncMock::GetInstance().socket(__domain, __type, __protocol); + } + return __real_socket(__domain, __type, __protocol); +} + +int __real_setsockopt(int __fd, int __level, int __optname, const void *__optval, socklen_t __optlen); +int __wrap_setsockopt(int __fd, int __level, int __optname, const void *__optval, socklen_t __optlen) +{ + LOGD("==>setsockopt."); + if (g_mockTag) { + LOGD(" ==>mock enable."); + return SystemFuncMock::GetInstance().setsockopt(__fd, __level, __optname, __optval, __optlen); + } + return __real_setsockopt(__fd, __level, __optname, __optval, __optlen); +} +int __real_select(int __nfds, fd_set *__readfds, fd_set *__writefds, fd_set *__exceptfds, struct timeval *__timeout); +int __wrap_select(int __nfds, fd_set *__readfds, fd_set *__writefds, fd_set *__exceptfds, struct timeval *__timeout) +{ + LOGD("==>select."); + if (g_mockTag) { + LOGD(" ==>mock enable."); + LOGD("message queue total: %d.", DhcpMsgManager::GetInstance().SendTotal()); + if (DhcpMsgManager::GetInstance().SendTotal() > 0) { + FD_CLR(__nfds, __readfds); + return 1; + } + int retval = SystemFuncMock::GetInstance().select(__nfds, __readfds, __writefds, __exceptfds, __timeout); + if (retval == 0) { + if (__timeout) { + usleep(DHCP_SEL_WAIT_TIMEOUTS * 1000); + LOGD("select time out."); + } + } + return retval; + } + return __real_select(__nfds, __readfds, __writefds, __exceptfds, __timeout); +} + +int __real_bind(int __fd, struct sockaddr * __addr, socklen_t __len); +int __wrap_bind(int __fd, struct sockaddr * __addr, socklen_t __len) +{ + LOGD("==>bind."); + if (g_mockTag) { + LOGD(" ==>mock enable."); + return SystemFuncMock::GetInstance().bind(__fd, __addr, __len); + } + return __real_bind(__fd, __addr, __len); +} + +int __real_close(int _fileno); +int __wrap_close(int _fileno) +{ + LOGD("==>close."); + if (g_mockTag) { + LOGD(" ==>mock enable."); + return SystemFuncMock::GetInstance().close(_fileno); + } + return __real_close(_fileno); +} + +ssize_t __real_sendto(int __fd, const void *__buf, size_t __n, int __flags, struct sockaddr *__addr, + socklen_t __addr_len); +ssize_t __wrap_sendto(int __fd, const void *__buf, size_t __n, int __flags, struct sockaddr *__addr, + socklen_t __addr_len) +{ + LOGD("==>sendto."); + if (g_mockTag) { + LOGD(" ==>mock enable."); + return SystemFuncMock::GetInstance().sendto(__fd, __buf, __n, __flags, __addr, __addr_len); + } + return __real_sendto(__fd, __buf, __n, __flags, __addr, __addr_len); +} + +ssize_t __real_recvfrom(int __fd, void *__buf, size_t __n, int __flags, struct sockaddr *__addr, + socklen_t *__addr_len); + +ssize_t __wrap_recvfrom(int __fd, void *__buf, size_t __n, int __flags, struct sockaddr *__addr, + socklen_t *__addr_len) +{ + LOGD("==>recvfrom."); + if (g_mockTag) { + LOGD(" ==>mock enable."); + if (DhcpMsgManager::GetInstance().SendTotal() > 0) { + LOGD("== new message received."); + usleep(150 * 1000); + DhcpMsgManager::GetInstance().PopSendMsg(); + } + return SystemFuncMock::GetInstance().recvfrom(__fd, __buf, __n, __flags, __addr, __addr_len); + } + return __real_recvfrom(__fd, __buf, __n, __flags, __addr, __addr_len); +} +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/system_func_mock.h b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/system_func_mock.h new file mode 100644 index 000000000..65be403a8 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/system_func_mock.h @@ -0,0 +1,52 @@ +/* + * 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_DHCP_SYSTEM_FUNC_MOCK_H +#define OHOS_DHCP_SYSTEM_FUNC_MOCK_H + +#include +#include +#include +#include +#include + +using ::testing::_; +using ::testing::Return; + +namespace OHOS { +namespace Wifi { +class SystemFuncMock { +public: + MOCK_METHOD3(socket, int(int __domain, int __type, int __protocol)); + MOCK_METHOD5(setsockopt, int(int __fd, int __level, int __optname, const void *__optval, socklen_t __optlen)); + MOCK_METHOD5(select, int(int __nfds, fd_set *__readfds, fd_set *__writefds, fd_set *__exceptfds, + struct timeval *__timeout)); + MOCK_METHOD3(bind, int(int __fd, struct sockaddr *__addr, socklen_t __len)); + MOCK_METHOD6(sendto, ssize_t(int __fd, const void *__buf, size_t __n, int __flags, struct sockaddr *__addr, + socklen_t __addr_len)); + MOCK_METHOD6(recvfrom, ssize_t(int __fd, void *__buf, size_t __n, int __flags, struct sockaddr *__addr, + socklen_t *__addr_len)); + MOCK_METHOD1(close, int(int _fileno)); + static SystemFuncMock &GetInstance(void); + static void SetMockFlag(bool flag); + static bool GetMockFlag(void); +private: + SystemFuncMock(); + ~SystemFuncMock(); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/BUILD.gn b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/BUILD.gn new file mode 100644 index 000000000..2e84991c9 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/BUILD.gn @@ -0,0 +1,106 @@ +# 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. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +################################################################################ + +SUBSYSTEM_DIR = "//foundation/communication" +module_output_path = "wifi_standard/dhcp_manage_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/test", + ] +} + +ohos_unittest("dhcp_manage_unittest") { + module_out_path = module_output_path + sources = [ + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_client_service_impl.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_event_subscriber.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_func.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_server_service.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_service.cpp", + "dhcp_client_service_test.cpp", + "dhcp_func_test.cpp", + "dhcp_manage_test.cpp", + "dhcp_result_notify.cpp", + "dhcp_server_service_test.cpp", + "dhcp_service_test.cpp", + "global_test.cpp", + "mock_system_func.cpp", + ] + + include_dirs = [ + "//third_party/googletest/googlemock/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/test", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", + "//utils/native/base/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "${even_path}/cesfwk/kits/native/include", + "${even_path}/cesfwk/innerkits/include", + "//base/notification/ces_standard/frameworks/core/include", + ] + + deps = [ + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + ldflags = [ + "-fPIC", + "-Wl,-E", + "--coverage", + "-Wl,-rpath=/vendor/lib64/hw", + "-Wl,--wrap=open", + "-Wl,--wrap=close", + "-Wl,--wrap=write", + "-Wl,--wrap=read", + "-Wl,--wrap=socket", + "-Wl,--wrap=setsockopt", + "-Wl,--wrap=ioctl", + "-Wl,--wrap=bind", + "-Wl,--wrap=listen", + "-Wl,--wrap=connect", + "-Wl,--wrap=select", + "-Wl,--wrap=sendto", + "-Wl,--wrap=vfork", + "-Wl,--wrap=execv", + "-Wl,--wrap=_exit", + "-Wl,--wrap=waitpid", + "-Wl,--wrap=kill", + ] + + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + ] + configs = [ ":module_private_config" ] + + part_name = "wifi_standard" + subsystem_name = "communication" +} + +group("unittest") { + testonly = true + deps = [ ":dhcp_manage_unittest" ] +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_client_service_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_client_service_test.cpp new file mode 100644 index 000000000..c7d2d30c7 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_client_service_test.cpp @@ -0,0 +1,131 @@ +/* + * 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 "dhcp_client_service_impl.h" +#include "dhcp_result_notify.h" +#include "mock_system_func.h" +#include "dhcp_func.h" +#include "securec.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Wifi; + +class DhcpClientServiceTest : public testing::Test { +public: + static void SetUpTestCase(){} + static void TearDownTestCase(){} + virtual void SetUp() + { + printf("DhcpClientServiceTest SetUp()...\n"); + pClientService = std::make_unique(); + if (pClientService == nullptr) { + printf("DhcpClientServiceTest SetUp() make_unique DhcpClientServiceImpl failed\n"); + } + } + virtual void TearDown() + { + printf("DhcpClientServiceTest TearDown()...\n"); + if (pClientService != nullptr) { + pClientService.reset(nullptr); + } + } +public: + std::unique_ptr pClientService; +}; + +HWTEST_F(DhcpClientServiceTest, DhcpClientService_Test2, TestSize.Level1) +{ + ASSERT_TRUE(pClientService != nullptr); + + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), vfork()) + .WillOnce(Return(-1)).WillOnce(Return(1)) + .WillOnce(Return(-1)).WillOnce(Return(1)) + .WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), waitpid(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), open(_, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + + std::string ifname = "wlan0"; + std::string strFile4 = DHCP_WORK_DIR + ifname + DHCP_RESULT_FILETYPE; + std::string strData4 = "IP4 0 * * * * * * * * 0"; + ASSERT_TRUE(DhcpFunc::CreateFile(strFile4, strData4)); + bool bIpv6 = true; + EXPECT_EQ(DHCP_OPT_FAILED, pClientService->StartDhcpClient(ifname, bIpv6)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pClientService->StartDhcpClient(ifname, bIpv6)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pClientService->StartDhcpClient(ifname, bIpv6)); + + DhcpResultNotify dhcpResultNotify; + EXPECT_EQ(DHCP_OPT_FAILED, pClientService->GetDhcpResult("", &dhcpResultNotify, 0)); + EXPECT_EQ(DHCP_OPT_FAILED, pClientService->GetDhcpResult(ifname, nullptr, 0)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pClientService->GetDhcpResult(ifname, &dhcpResultNotify, 0)); + DhcpResultNotify dhcpResultNotify1; + EXPECT_EQ(DHCP_OPT_SUCCESS, pClientService->GetDhcpResult(ifname, &dhcpResultNotify1, 10)); + DhcpResultNotify dhcpResultNotify2; + EXPECT_EQ(DHCP_OPT_SUCCESS, pClientService->GetDhcpResult(ifname, &dhcpResultNotify2, 20)); + DhcpResultNotify dhcpResultNotify3; + EXPECT_EQ(DHCP_OPT_SUCCESS, pClientService->GetDhcpResult("wlan1", &dhcpResultNotify3, 30)); + + sleep(DHCP_NUM_ONE); + + EXPECT_EQ(DHCP_OPT_FAILED, pClientService->StopDhcpClient(ifname, true)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pClientService->StopDhcpClient(ifname, true)); + ASSERT_TRUE(DhcpFunc::RemoveFile(strFile4)); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpClientServiceTest, DhcpClientService_Test3, TestSize.Level1) +{ + ASSERT_TRUE(pClientService != nullptr); + + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), vfork()).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), waitpid(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), kill(_, _)) + .WillOnce(Return(-1)).WillOnce(Return(0)) + .WillOnce(Return(-1)).WillOnce(Return(0)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), open(_, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + + std::string ifname = "wlan0"; + EXPECT_EQ(0, pClientService->GetDhcpClientProPid("")); + EXPECT_EQ(0, pClientService->GetDhcpClientProPid(ifname)); + + std::string strFile4 = DHCP_WORK_DIR + ifname + DHCP_RESULT_FILETYPE; + std::string strData4 = "IP4 0 * * * * * * * * 0"; + ASSERT_TRUE(DhcpFunc::CreateFile(strFile4, strData4)); + bool bIpv6 = true; + EXPECT_EQ(DHCP_OPT_SUCCESS, pClientService->StopDhcpClient(ifname, bIpv6)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pClientService->StartDhcpClient(ifname, bIpv6)); + + EXPECT_EQ(DHCP_OPT_FAILED, pClientService->RenewDhcpClient(ifname)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pClientService->RenewDhcpClient(ifname)); + EXPECT_EQ(DHCP_OPT_FAILED, pClientService->ReleaseDhcpClient(ifname)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pClientService->ReleaseDhcpClient(ifname)); + + EXPECT_EQ(DHCP_OPT_SUCCESS, pClientService->StopDhcpClient(ifname, bIpv6)); + ASSERT_TRUE(DhcpFunc::RemoveFile(strFile4)); + + EXPECT_EQ(DHCP_OPT_SUCCESS, pClientService->StartDhcpClient("wlan1", false)); + + MockSystemFunc::SetMockFlag(false); +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_func_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_func_test.cpp new file mode 100644 index 000000000..caa2122d8 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_func_test.cpp @@ -0,0 +1,250 @@ +/* + * 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 "dhcp_func.h" +#include "mock_system_func.h" +#include "securec.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Wifi; + +class DhcpFuncTest : public testing::Test { +public: + static void SetUpTestCase(){} + static void TearDownTestCase(){} + virtual void SetUp() + { + printf("DhcpFuncTest SetUp()...\n"); + } + virtual void TearDown() + { + printf("DhcpFuncTest TearDown()...\n"); + } +}; + +HWTEST_F(DhcpFuncTest, Ip4StrConToInt_SUCCESS, TestSize.Level1) +{ + std::string strIp = "192.77.1.232"; + uint32_t uSerIp = 0; + EXPECT_EQ(true, DhcpFunc::Ip4StrConToInt(strIp, uSerIp)); + printf("DhcpFuncTest Ip4StrConToInt_SUCCESS strIp:%s -> uSerIp:%u.\n", strIp.c_str(), uSerIp); +} + +HWTEST_F(DhcpFuncTest, Ip4StrConToInt_FAILED, TestSize.Level1) +{ + std::string strIp = "test4"; + uint32_t uSerIp = 0; + EXPECT_EQ(false, DhcpFunc::Ip4StrConToInt(strIp, uSerIp)); + + strIp.clear(); + uSerIp = 0; + EXPECT_EQ(false, DhcpFunc::Ip4StrConToInt(strIp, uSerIp)); +} + +HWTEST_F(DhcpFuncTest, Ip4IntConToStr_SUCCESS, TestSize.Level1) +{ + uint32_t uSerIp = 3226272232; + std::string strIp = DhcpFunc::Ip4IntConToStr(uSerIp); + EXPECT_STRNE(strIp.c_str(), ""); + printf("DhcpFuncTest Ip4IntConToStr_SUCCESS uSerIp:%u -> strIp:%s.\n", uSerIp, strIp.c_str()); +} + +HWTEST_F(DhcpFuncTest, Ip4IntConToStr_FAILED, TestSize.Level1) +{ + uint32_t uSerIp = 0; + std::string strIp = DhcpFunc::Ip4IntConToStr(uSerIp); + EXPECT_STREQ(strIp.c_str(), "0.0.0.0"); +} + +HWTEST_F(DhcpFuncTest, Ip6StrConToChar_SUCCESS, TestSize.Level1) +{ + std::string strIp = "fe80::20c:29ff:fed7:fac8"; + uint8_t addr6[sizeof(struct in6_addr)] = {0}; + EXPECT_EQ(true, DhcpFunc::Ip6StrConToChar(strIp, addr6, sizeof(struct in6_addr))); +} + +HWTEST_F(DhcpFuncTest, Ip6StrConToChar_FAILED, TestSize.Level1) +{ + std::string strIp = "test6"; + uint8_t addr6[sizeof(struct in6_addr)] = {0}; + EXPECT_EQ(false, DhcpFunc::Ip6StrConToChar(strIp, addr6, sizeof(struct in6_addr))); + + strIp.clear(); + EXPECT_EQ(false, DhcpFunc::Ip6StrConToChar(strIp, addr6, sizeof(struct in6_addr))); +} + +HWTEST_F(DhcpFuncTest, Ip6CharConToStr_SUCCESS, TestSize.Level1) +{ + uint8_t addr6[sizeof(struct in6_addr)] = {0}; + EXPECT_STREQ(DhcpFunc::Ip6CharConToStr(addr6, sizeof(struct in6_addr)).c_str(), ""); +} + +HWTEST_F(DhcpFuncTest, Ip6CharConToStr_FAILED, TestSize.Level1) +{ + uint8_t addr6[sizeof(struct in6_addr)] = {0}; + EXPECT_STREQ(DhcpFunc::Ip6CharConToStr(addr6, 0).c_str(), ""); +} + +HWTEST_F(DhcpFuncTest, CheckIpStr_SUCCESS, TestSize.Level1) +{ + std::string strIp4 = "192.77.1.232"; + EXPECT_EQ(true, DhcpFunc::CheckIpStr(strIp4)); + + std::string strIp6 = "fe80::20c:29ff:fed7:fac8"; + EXPECT_EQ(true, DhcpFunc::CheckIpStr(strIp6)); +} + +HWTEST_F(DhcpFuncTest, CheckIpStr_FAILED, TestSize.Level1) +{ + std::string strIp1 = "192.77.232"; + EXPECT_EQ(false, DhcpFunc::CheckIpStr(strIp1)); + strIp1.clear(); + EXPECT_EQ(false, DhcpFunc::CheckIpStr(strIp1)); + + std::string strIp2 = "fe80:fac8"; + EXPECT_EQ(false, DhcpFunc::CheckIpStr(strIp2)); + + std::string strIp3 = "192.77.232:fe80:fac8"; + EXPECT_EQ(false, DhcpFunc::CheckIpStr(strIp3)); +} + +HWTEST_F(DhcpFuncTest, GetLocalIp_TEST, TestSize.Level1) +{ + std::string ifname, ip, netmask; + EXPECT_EQ(DHCP_OPT_ERROR, DhcpFunc::GetLocalIp(ifname, ip, netmask)); + + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), ioctl(_, _, _)) + .WillOnce(Return(-1)) + .WillOnce(Return(0)).WillOnce(Return(-1)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + + ifname = "wlan"; + EXPECT_EQ(DHCP_OPT_FAILED, DhcpFunc::GetLocalIp(ifname, ip, netmask)); + EXPECT_EQ(DHCP_OPT_FAILED, DhcpFunc::GetLocalIp(ifname, ip, netmask)); + EXPECT_EQ(DHCP_OPT_SUCCESS, DhcpFunc::GetLocalIp(ifname, ip, netmask)); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpFuncTest, GetLocalMac_TEST, TestSize.Level1) +{ + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), ioctl(_, _, _)) + .WillOnce(Return(-1)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + + std::string ifname = "wlan"; + std::string mac; + EXPECT_EQ(-1, DhcpFunc::GetLocalMac(ifname, mac)); + EXPECT_EQ(-1, DhcpFunc::GetLocalMac(ifname, mac)); + EXPECT_EQ(0, DhcpFunc::GetLocalMac(ifname, mac)); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpFuncTest, CheckRangeNetwork_TEST, TestSize.Level1) +{ + std::string ifname, begin, end; + EXPECT_EQ(DHCP_OPT_ERROR, DhcpFunc::CheckRangeNetwork(ifname, begin, end)); +} + +HWTEST_F(DhcpFuncTest, FileManage_SUCCESS, TestSize.Level1) +{ + std::string strFile = "./wlan0.result"; + bool bExist = DhcpFunc::IsExistFile(strFile); + if (bExist) { + EXPECT_EQ(true, DhcpFunc::RemoveFile(strFile)); + usleep(200); + } else { + EXPECT_EQ(false, DhcpFunc::RemoveFile(strFile)); + } + + std::string strData = "IP4 1624421132 192.168.1.207 192.168.1.2 255.255.255.0 192.168.1.2 * 192.168.1.2 * * 43200"; + EXPECT_EQ(true, DhcpFunc::CreateFile(strFile, strData)); + + std::string strAdd = "test add str"; + EXPECT_EQ(true, DhcpFunc::AddFileLineData(strFile, strData, strAdd)); + std::string strModify = "test modify str"; + EXPECT_EQ(true, DhcpFunc::ModifyFileLineData(strFile, strAdd, strModify)); + EXPECT_EQ(true, DhcpFunc::DelFileLineData(strFile, strModify)); + + EXPECT_EQ(true, DhcpFunc::RemoveFile(strFile)); +} + +HWTEST_F(DhcpFuncTest, FileManage_FAILED, TestSize.Level1) +{ + std::string strFile = "./test/wlan0.result"; + EXPECT_EQ(false, DhcpFunc::RemoveFile(strFile)); +} + +HWTEST_F(DhcpFuncTest, FormatString_SUCCESS, TestSize.Level1) +{ + struct DhcpPacketResult result; + ASSERT_TRUE(memset_s(&result, sizeof(result), 0, sizeof(result)) == EOK); + ASSERT_TRUE(strncpy_s(result.strYiaddr, INET_ADDRSTRLEN, "*", INET_ADDRSTRLEN - 1) == EOK); + ASSERT_TRUE(strncpy_s(result.strOptServerId, INET_ADDRSTRLEN, "*", INET_ADDRSTRLEN - 1) == EOK); + ASSERT_TRUE(strncpy_s(result.strOptSubnet, INET_ADDRSTRLEN, "*", INET_ADDRSTRLEN - 1) == EOK); + ASSERT_TRUE(strncpy_s(result.strOptDns1, INET_ADDRSTRLEN, "*", INET_ADDRSTRLEN - 1) == EOK); + ASSERT_TRUE(strncpy_s(result.strOptDns2, INET_ADDRSTRLEN, "*", INET_ADDRSTRLEN - 1) == EOK); + ASSERT_TRUE(strncpy_s(result.strOptRouter1, INET_ADDRSTRLEN, "*", INET_ADDRSTRLEN - 1) == EOK); + ASSERT_TRUE(strncpy_s(result.strOptRouter2, INET_ADDRSTRLEN, "*", INET_ADDRSTRLEN - 1) == EOK); + ASSERT_TRUE(strncpy_s(result.strOptVendor, DHCP_FILE_MAX_BYTES, "*", DHCP_FILE_MAX_BYTES - 1) == EOK); + EXPECT_EQ(0, DhcpFunc::FormatString(result)); +} + +HWTEST_F(DhcpFuncTest, InitPidfile_TEST, TestSize.Level1) +{ + std::string pidDir, pidFile; + EXPECT_EQ(DHCP_OPT_FAILED, DhcpFunc::InitPidfile(pidDir, pidFile)); + + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), open(_, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), write(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + + pidDir = "./"; + pidFile = "./wlan.pid"; + EXPECT_EQ(DHCP_OPT_FAILED, DhcpFunc::InitPidfile(pidDir, pidFile)); + EXPECT_EQ(DHCP_OPT_FAILED, DhcpFunc::InitPidfile(pidDir, pidFile)); + EXPECT_EQ(DHCP_OPT_SUCCESS, DhcpFunc::InitPidfile(pidDir, pidFile)); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpFuncTest, GetPID_TEST, TestSize.Level1) +{ + std::string pidDir = "./"; + std::string pidFile = "./wlan.pid"; + EXPECT_EQ(DHCP_OPT_SUCCESS, DhcpFunc::InitPidfile(pidDir, pidFile)); + EXPECT_GT(DhcpFunc::GetPID(pidFile), 0); + unlink(pidFile.c_str()); + EXPECT_EQ(DhcpFunc::GetPID(pidFile), -1); +} + +HWTEST_F(DhcpFuncTest, CreateDirs_TEST, TestSize.Level1) +{ + std::string strDir; + EXPECT_EQ(DhcpFunc::CreateDirs(strDir), DHCP_OPT_FAILED); +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_manage_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_manage_test.cpp new file mode 100644 index 000000000..17d38d8b8 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_manage_test.cpp @@ -0,0 +1,25 @@ +/* + * 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 "global_test.h" + +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + testing::Environment *env = new GlobalTest(); + testing::AddGlobalTestEnvironment(env); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_result_notify.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_result_notify.cpp new file mode 100644 index 000000000..adf09cc67 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_result_notify.cpp @@ -0,0 +1,54 @@ +/* + * 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 "dhcp_result_notify.h" + +#include + +namespace OHOS { +namespace Wifi { +DhcpResultNotify::DhcpResultNotify() +{ + std::cout << "enter DhcpResultNotify::DhcpResultNotify()..." << std::endl; +} + +DhcpResultNotify::~DhcpResultNotify() +{ + std::cout << "enter DhcpResultNotify::~DhcpResultNotify()..." << std::endl; +} + +void DhcpResultNotify::OnSuccess(int status, const std::string& ifname, DhcpResult& result) +{ + std::cout << "===================enter DhcpResultNotify::OnSuccess()...status:" << status << ",ifname:" << ifname + << ", result.iptype:" << result.iptype << ",isOptSuc:" << result.isOptSuc + << ",strYourCli:" << result.strYourCli << ",strServer:" << result.strServer << ",strSubnet:" << result.strSubnet + << ",strDns1:" << result.strDns1 << ",strDns2:" << result.strDns2 + << ",strRouter1:" << result.strRouter1 << ",strRouter2:" << result.strRouter2 + << ",strVendor:" << result.strVendor << ",uLeaseTime:" << result.uLeaseTime + << ",uAddTime:" << result.uAddTime << ",uGetTime:" << result.uGetTime << std::endl; +} + +void DhcpResultNotify::OnFailed(int status, const std::string& ifname, const std::string& reason) +{ + std::cout << "===================enter DhcpResultNotify::OnFailed()...status:" << status << ",ifname:" << ifname + << ", reason:" << reason << std::endl; +} + +void DhcpResultNotify::OnSerExitNotify(const std::string& ifname) +{ + std::cout << "===================enter DhcpResultNotify::OnSerExitNotify()...ifname:" << ifname << std::endl; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_result_notify.h b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_result_notify.h new file mode 100644 index 000000000..71ff5c263 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_result_notify.h @@ -0,0 +1,66 @@ +/* + * 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_DHCP_RESULT_NOTIFY_H +#define OHOS_DHCP_RESULT_NOTIFY_H + +#include "i_dhcp_result_notify.h" +#include "dhcp_define.h" + + +namespace OHOS { +namespace Wifi { +class DhcpResultNotify : public OHOS::Wifi::IDhcpResultNotify { +public: + /** + * @Description : Construct a new dhcp result notify object + * + */ + DhcpResultNotify(); + + /** + * @Description : Destroy the dhcp result notify object + * + */ + ~DhcpResultNotify() override; + + /** + * @Description:asyn get dhcp result of specified interface success notify + * + * @param status - int + * @param ifname - interface name,eg:wlan0 + * @param result - dhcp result + */ + void OnSuccess(int status, const std::string& ifname, DhcpResult& result) override; + + /** + * @Description:asyn get dhcp result of specified interface failed notify + * + * @param status - int + * @param ifname - interface name,eg:wlan0 + * @param reason - failed reason + */ + void OnFailed(int status, const std::string& ifname, const std::string& reason) override; + + /** + * @Description : Get the abnormal exit notify of dhcp server process. + * + * @param ifname - interface name, eg:wlan0 [in] + */ + void OnSerExitNotify(const std::string& ifname) override; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_server_service_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_server_service_test.cpp new file mode 100644 index 000000000..55054a2c8 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_server_service_test.cpp @@ -0,0 +1,271 @@ +/* + * 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 "dhcp_server_service.h" +#include "dhcp_result_notify.h" +#include "mock_system_func.h" +#include "dhcp_func.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Wifi; + +class DhcpServerServiceTest : public testing::Test { +public: + static void SetUpTestCase(){} + static void TearDownTestCase(){} + virtual void SetUp() + { + printf("DhcpServerServiceTest SetUp()...\n"); + pServerService = std::make_unique(); + if (pServerService == nullptr) { + printf("DhcpServerServiceTest SetUp() make_unique DhcpServerService failed\n"); + } + } + virtual void TearDown() + { + printf("DhcpServerServiceTest TearDown()...\n"); + if (pServerService != nullptr) { + pServerService.reset(nullptr); + } + } +public: + std::unique_ptr pServerService; +}; + +HWTEST_F(DhcpServerServiceTest, DhcpServerService_Test2, TestSize.Level1) +{ + ASSERT_TRUE(pServerService != nullptr); + + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), vfork()) + .WillOnce(Return(-1)).WillOnce(Return(1)) + .WillOnce(Return(-1)).WillOnce(Return(1)) + .WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), waitpid(_, _, _)) + .WillOnce(Return(-1)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), kill(_, _)) + .WillOnce(Return(-1)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), ioctl(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), open(_, _)).WillRepeatedly(Return(1)); + + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->StopDhcpServer("wlan1")); + + std::string tagName; + DhcpRange putRange; + EXPECT_EQ(DHCP_OPT_ERROR, pServerService->PutDhcpRange(tagName, putRange)); + tagName = "sta"; + putRange.iptype = -1; + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->PutDhcpRange(tagName, putRange)); + putRange.iptype = 0; + putRange.strStartip = "192.168.0.1"; + putRange.strEndip = "192.168.0.49"; + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->PutDhcpRange(tagName, putRange)); + putRange.leaseHours = 12; + putRange.strTagName = tagName; + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->PutDhcpRange(tagName, putRange)); + putRange.strStartip = "192.168.0.50"; + putRange.strEndip = "192.168.0.99"; + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->PutDhcpRange(tagName, putRange)); + tagName.clear(); + EXPECT_EQ(DHCP_OPT_ERROR, pServerService->RemoveDhcpRange(tagName, putRange)); + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->RemoveDhcpRange("ap", putRange)); + tagName = "sta"; + putRange.iptype = -1; + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->RemoveDhcpRange(tagName, putRange)); + putRange.iptype = 0; + putRange.strStartip = "192.168.0.1"; + putRange.strEndip = "192.168.0.49"; + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->RemoveDhcpRange(tagName, putRange)); + tagName.clear(); + EXPECT_EQ(DHCP_OPT_ERROR, pServerService->RemoveAllDhcpRange(tagName)); + tagName = "sta1"; + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->RemoveAllDhcpRange(tagName)); + + std::string ifname; + DhcpRange setRange; + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->SetDhcpRange(ifname, setRange)); + ifname = "wlan0"; + setRange.iptype = 0; + setRange.strStartip = "192.168.0.1"; + setRange.strEndip = "192.168.0.49"; + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->SetDhcpRange(ifname, setRange)); + setRange.leaseHours = 12; + setRange.strTagName = ifname; + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->SetDhcpRange(ifname, setRange)); + + ifname.clear(); + tagName = "sta"; + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->SetDhcpRange(ifname, tagName)); + ifname = "wlan0"; + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->SetDhcpRange(ifname, "sta1")); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->PutDhcpRange(tagName, putRange)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->RemoveDhcpRange(tagName, putRange)); + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->SetDhcpRange(ifname, tagName)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->PutDhcpRange(tagName, putRange)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->SetDhcpRange(ifname, tagName)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->SetDhcpRange(ifname, tagName)); + + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->StartDhcpServer(ifname)); //start vfork failed + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->StartDhcpServer(ifname)); //start vfork success + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->StartDhcpServer(ifname)); //restart stop kill failed + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->StartDhcpServer(ifname)); //restart stop waitpid failed + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->StartDhcpServer(ifname)); //restart start vfork failed + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->StartDhcpServer(ifname)); //restart start vfork success + + DhcpResultNotify dhcpResultNotify; + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->GetDhcpSerProExit("", nullptr)); + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->GetDhcpSerProExit(ifname, nullptr)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->GetDhcpSerProExit(ifname, &dhcpResultNotify)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->GetDhcpSerProExit(ifname, &dhcpResultNotify)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->StopDhcpServer(ifname)); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpServerServiceTest, DhcpServerService_Test3, TestSize.Level1) +{ + ASSERT_TRUE(pServerService != nullptr); + + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), vfork()) + .WillOnce(Return(0)).WillOnce(Return(1)) + .WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), waitpid(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), kill(_, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)) + .WillOnce(Return(1)).WillOnce(Return(-1)) + .WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), ioctl(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), open(_, _)).WillRepeatedly(Return(1)); + + std::string ifname = "wlan0"; + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->StartDhcpServer(ifname)); //start vfork child failed + DhcpRange setRange; + setRange.iptype = 0; + setRange.strStartip = "192.168.0.1"; + setRange.strEndip = "192.168.0.49"; + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->SetDhcpRange(ifname, setRange));//socket failed + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->SetDhcpRange(ifname, setRange)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->StartDhcpServer(ifname)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->StopDhcpServer(ifname)); + + std::string ifname2 = "wlan2"; + std::string tagName = "sta2"; + DhcpRange putRange; + putRange.iptype = 0; + putRange.strStartip = "192.168.0.50"; + putRange.strEndip = "192.168.0.99"; + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->PutDhcpRange(tagName, putRange)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->SetDhcpRange(ifname2, tagName)); + std::string ipRange; + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->GetUsingIpRange(ifname2, ipRange)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->StartDhcpServer(ifname2)); //start vfork parent success + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->StartDhcpServer(ifname2)); //restart start vfork parent success + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->StopDhcpServer(ifname2)); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpServerServiceTest, DhcpServerService_Test4, TestSize.Level1) +{ + ASSERT_TRUE(pServerService != nullptr); + + MockSystemFunc::SetMockFlag(true); + + EXPECT_CALL(MockSystemFunc::GetInstance(), vfork()) + .WillOnce(Return(1)) + .WillOnce(Return(0)) + .WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), waitpid(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), kill(_, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)) + .WillOnce(Return(1)).WillOnce(Return(-1)) + .WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), ioctl(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); + EXPECT_CALL(MockSystemFunc::GetInstance(), open(_, _)).WillRepeatedly(Return(1)); + + std::string ifname = "wlan0"; + DhcpRange setRange; + setRange.iptype = 0; + setRange.strStartip = "192.168.0.1"; + setRange.strEndip = "192.168.0.49"; + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->SetDhcpRange(ifname, setRange)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->StartDhcpServer(ifname)); + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->ReloadConfig(ifname)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->StartDhcpServer(ifname)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->StopDhcpServer(ifname)); + + MockSystemFunc::SetMockFlag(false); +} + +HWTEST_F(DhcpServerServiceTest, DhcpServerService_Test5, TestSize.Level1) +{ + ASSERT_TRUE(pServerService != nullptr); + + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->ReloadConfig("")); + EXPECT_EQ(DHCP_OPT_FAILED, pServerService->ReloadConfig("wlan0")); + EXPECT_EQ(DHCP_OPT_ERROR, pServerService->CheckAndUpdateConf("")); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->CheckAndUpdateConf("wlan1")); + + std::string ipRange; + EXPECT_EQ(DHCP_OPT_ERROR, pServerService->GetUsingIpRange("", ipRange)); + + DhcpRange checkRange; + EXPECT_EQ(false, pServerService->CheckIpAddrRange(checkRange)); + checkRange.iptype = 0; + checkRange.strStartip = "192.168.0"; + checkRange.strEndip = "192.168.1"; + EXPECT_EQ(false, pServerService->CheckIpAddrRange(checkRange)); + checkRange.strStartip = "192.168.0.49"; + checkRange.strEndip = "192.168.1"; + EXPECT_EQ(false, pServerService->CheckIpAddrRange(checkRange)); + checkRange.strEndip = "192.168.0.1"; + EXPECT_EQ(false, pServerService->CheckIpAddrRange(checkRange)); + + checkRange.iptype = 1; + checkRange.strStartip = "fe80:fac8"; + EXPECT_EQ(false, pServerService->CheckIpAddrRange(checkRange)); + checkRange.strStartip = "fe80::fac8"; + checkRange.strEndip = "fe80:fac8"; + EXPECT_EQ(false, pServerService->CheckIpAddrRange(checkRange)); + + std::string ifname; + EXPECT_EQ(DHCP_OPT_ERROR, pServerService->AddSpecifiedInterface(ifname)); + ifname = "wlan"; + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->AddSpecifiedInterface(ifname)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->AddSpecifiedInterface(ifname)); + + ifname.clear(); + EXPECT_EQ(DHCP_OPT_ERROR, pServerService->DelSpecifiedInterface(ifname)); + ifname = "wlan"; + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->DelSpecifiedInterface(ifname)); + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->DelSpecifiedInterface(ifname)); + + std::string strFile = DHCP_SERVER_LEASES_FILE + "." + ifname; + std::string strTestData = "dhcp server leases file test"; + ASSERT_TRUE(DhcpFunc::CreateFile(strFile, strTestData)); + std::vector vecLeases; + EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->GetLeases(ifname, vecLeases)); + ASSERT_TRUE(DhcpFunc::RemoveFile(strFile)); +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_service_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_service_test.cpp new file mode 100644 index 000000000..fc73fc8b9 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_service_test.cpp @@ -0,0 +1,93 @@ +/* + * 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 "dhcp_service.h" +#include "dhcp_result_notify.h" +#include "dhcp_func.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::Wifi; + +class DhcpServiceTest : public testing::Test { +public: + static void SetUpTestCase(){} + static void TearDownTestCase(){} + virtual void SetUp() + { + printf("DhcpServiceTest SetUp()...\n"); + pDhcpService = std::make_unique(); + if (pDhcpService == nullptr) { + printf("DhcpServiceTest SetUp() make_unique DhcpService failed\n"); + } + } + virtual void TearDown() + { + printf("DhcpServiceTest TearDown()...\n"); + if (pDhcpService != nullptr) { + pDhcpService.reset(nullptr); + } + } +public: + std::unique_ptr pDhcpService; +}; + +HWTEST_F(DhcpServiceTest, DhcpClientService_Test1, TestSize.Level1) +{ + ASSERT_TRUE(pDhcpService != nullptr); + + std::string ifname = ""; + DhcpResultNotify dhcpResultNotify; + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->GetDhcpResult(ifname, &dhcpResultNotify, 0)); + DhcpServiceInfo dhcpInfo; + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->GetDhcpInfo(ifname, dhcpInfo)); + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->RenewDhcpClient(ifname)); + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->ReleaseDhcpClient(ifname)); + + bool bIpv6 = false; + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->StartDhcpClient(ifname, bIpv6)); + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->GetDhcpResult(ifname, &dhcpResultNotify, 0)); + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->GetDhcpInfo(ifname, dhcpInfo)); + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->RenewDhcpClient(ifname)); + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->ReleaseDhcpClient(ifname)); + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->StopDhcpClient(ifname, bIpv6)); +} + +HWTEST_F(DhcpServiceTest, DhcpServerService_Test1, TestSize.Level1) +{ + ASSERT_TRUE(pDhcpService != nullptr); + + std::string ifname = ""; + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->StartDhcpServer(ifname)); + EXPECT_EQ(0, pDhcpService->GetServerStatus()); + + std::string tagName = ""; + DhcpRange putRange; + EXPECT_EQ(DHCP_OPT_ERROR, pDhcpService->PutDhcpRange(tagName, putRange)); + EXPECT_EQ(DHCP_OPT_ERROR, pDhcpService->RemoveDhcpRange(tagName, putRange)); + EXPECT_EQ(DHCP_OPT_ERROR, pDhcpService->RemoveAllDhcpRange(tagName)); + DhcpRange setRange; + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->SetDhcpRange(ifname, setRange)); + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->SetDhcpRange(ifname, tagName)); + + unlink(DHCP_SERVER_LEASES_FILE.c_str()); + std::vector vecLeases; + EXPECT_EQ(DHCP_OPT_ERROR, pDhcpService->GetLeases(ifname, vecLeases)); + DhcpResultNotify dhcpResultNotify; + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->GetDhcpSerProExit(ifname, &dhcpResultNotify)); + EXPECT_EQ(DHCP_OPT_FAILED, pDhcpService->StopDhcpServer(ifname)); +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/global_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/global_test.cpp new file mode 100644 index 000000000..71d64719b --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/global_test.cpp @@ -0,0 +1,24 @@ +/* + * 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 "global_test.h" +void GlobalTest::SetUp() +{ + printf("GlobalTest SetUp\n"); +} +void GlobalTest::TearDown() +{ + printf("GlobalTest TearDown\n"); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/global_test.h b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/global_test.h new file mode 100644 index 000000000..0059df118 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/global_test.h @@ -0,0 +1,24 @@ +/* + * 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 GLOBAL_TEST_H +#define GLOBAL_TEST_H +#include +class GlobalTest : public testing::Environment { +public: + virtual void SetUp(); + virtual void TearDown(); +}; +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/mock_system_func.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/mock_system_func.cpp new file mode 100644 index 000000000..c5563f788 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/mock_system_func.cpp @@ -0,0 +1,216 @@ +/* + * 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 "mock_system_func.h" +using namespace OHOS; +using namespace OHOS::Wifi; + +static bool g_mockTag = false; + +MockSystemFunc &MockSystemFunc::GetInstance() +{ + static MockSystemFunc gMockSystemFunc; + return gMockSystemFunc; +}; + +MockSystemFunc::MockSystemFunc() +{} + +void MockSystemFunc::SetMockFlag(bool flag) +{ + g_mockTag = flag; +} + +bool MockSystemFunc::GetMockFlag(void) +{ + return g_mockTag; +} + +#ifdef __cplusplus +extern "C" { +#endif +int __real_open(const char *__file, int __oflag); +int __wrap_open(const char *__file, int __oflag) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().open(__file, __oflag); + } else { + return __real_open(__file, __oflag); + } +} + +int __real_close(int fd); +int __wrap_close(int fd) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().close(fd); + } else { + return __real_close(fd); + } +} + +ssize_t __real_write(int fd, const void *buf, size_t count); +ssize_t __wrap_write(int fd, const void *buf, size_t count) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().write(fd, buf, count); + } else { + return __real_write(fd, buf, count); + } +} + +ssize_t __real_read(int fd, void *buf, size_t count); +ssize_t __wrap_read(int fd, void *buf, size_t count) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().read(fd, buf, count); + } else { + return __real_read(fd, buf, count); + } +} + +int __real_socket(int __domain, int __type, int __protocol); +int __wrap_socket(int __domain, int __type, int __protocol) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().socket(__domain, __type, __protocol); + } else { + return __real_socket(__domain, __type, __protocol); + } +} + +int __real_setsockopt(int __fd, int __level, int __optname, const void *__optval, socklen_t __optlen); +int __wrap_setsockopt(int __fd, int __level, int __optname, const void *__optval, socklen_t __optlen) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().setsockopt(__fd, __level, __optname, __optval, __optlen); + } else { + return __real_setsockopt(__fd, __level, __optname, __optval, __optlen); + } +} + +int __real_ioctl(int __fd, unsigned long __request, struct sockaddr *__ifreq); +int __wrap_ioctl(int __fd, unsigned long __request, struct sockaddr *__ifreq) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().ioctl(__fd, __request, __ifreq); + } else { + return __real_ioctl(__fd, __request, __ifreq); + } +} + +int __real_bind(int __fd, const struct sockaddr *__addr, socklen_t __len); +int __wrap_bind(int __fd, const struct sockaddr *__addr, socklen_t __len) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().bind(__fd, __addr, __len); + } else { + return __real_bind(__fd, __addr, __len); + } +} + +int __real_listen(int __fd, int __n); +int __wrap_listen(int __fd, int __n) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().listen(__fd, __n); + } else { + return __real_listen(__fd, __n); + } +} + +int __real_connect(int __fd, const struct sockaddr *__addr, socklen_t __len); +int __wrap_connect(int __fd, const struct sockaddr *__addr, socklen_t __len) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().connect(__fd, __addr, __len); + } else { + return __real_connect(__fd, __addr, __len); + } +} + +int __real_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); +int __wrap_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().select(nfds, readfds, writefds, exceptfds, timeout); + } else { + return __real_select(nfds, readfds, writefds, exceptfds, timeout); + } +} + +ssize_t __real_sendto(int fd, const void *buf, size_t count, int flags, const struct sockaddr *addr, socklen_t len); +ssize_t __wrap_sendto(int fd, const void *buf, size_t count, int flags, const struct sockaddr *addr, socklen_t len) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().sendto(fd, buf, count, flags, addr, len); + } else { + return __real_sendto(fd, buf, count, flags, addr, len); + } +} + +pid_t __real_vfork(); +pid_t __wrap_vfork() +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().vfork(); + } else { + return __real_vfork(); + } +} + +int __real_execv(const char *__path, char *const *__argv); +int __wrap_execv(const char *__path, char *const *__argv) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().execv(__path, __argv); + } else { + return __real_execv(__path, __argv); + } +} + +void __real__exit(int status); +void __wrap__exit(int status) +{ + if (g_mockTag) { + MockSystemFunc::GetInstance()._exit(status); + } else { + __real__exit(status); + } + return; +} + +pid_t __real_waitpid(pid_t pid, int *status, int options); +pid_t __wrap_waitpid(pid_t pid, int *status, int options) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().waitpid(pid, status, options); + } else { + return __real_waitpid(pid, status, options); + } +} + +int __real_kill(pid_t pid, int sig); +int __wrap_kill(pid_t pid, int sig) +{ + if (g_mockTag) { + return MockSystemFunc::GetInstance().kill(pid, sig); + } else { + return __real_kill(pid, sig); + } +} +#ifdef __cplusplus +} +#endif diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/mock_system_func.h b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/mock_system_func.h new file mode 100644 index 000000000..51e29985c --- /dev/null +++ b/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/mock_system_func.h @@ -0,0 +1,64 @@ +/* + * 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_SYSTEM_FUNC_H +#define OHOS_MOCK_SYSTEM_FUNC_H + +#include +#include +#include +#include + +using ::testing::_; +using ::testing::Return; + +namespace OHOS { +namespace Wifi { +class MockSystemFunc { +public: + MOCK_METHOD2(open, int(const char *__file, int __oflag)); + MOCK_METHOD1(close, int(int)); + MOCK_METHOD3(write, ssize_t(int fd, const void *buf, size_t count)); + MOCK_METHOD3(read, ssize_t(int fd, void *buf, size_t count)); + MOCK_METHOD3(socket, int(int __domain, int __type, int __protocol)); + MOCK_METHOD5(setsockopt, int(int __fd, int __level, int __optname, const void *__optval, socklen_t __optlen)); + MOCK_METHOD3(ioctl, int(int __fd, unsigned long __request, struct sockaddr *__ifreq)); + MOCK_METHOD3(bind, int(int __fd, const struct sockaddr *__addr, socklen_t __len)); + MOCK_METHOD2(listen, int(int __fd, int __n)); + MOCK_METHOD3(connect, int(int __fd, const struct sockaddr *__addr, socklen_t __len)); + MOCK_METHOD5(select, int(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)); + MOCK_METHOD6( + sendto, ssize_t(int fd, const void *buf, size_t count, int flags, const struct sockaddr *addr, socklen_t len)); + + MOCK_METHOD0(vfork, pid_t(void)); + MOCK_METHOD2(execv, int(const char *__path, char *const *__argv)); + MOCK_METHOD1(_exit, void(int status)); + MOCK_METHOD3(waitpid, pid_t(pid_t pid, int *status, int options)); + MOCK_METHOD2(kill, int(pid_t pid, int sig)); + + static MockSystemFunc &GetInstance(void); + static void SetMockFlag(bool flag); + static bool GetMockFlag(void); + +private: + MockSystemFunc(); + ~MockSystemFunc(){} +}; +} // namespace Wifi +} // namespace OHOS + +extern "C" {} + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/BUILD.gn new file mode 100644 index 000000000..2144b2ce2 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/BUILD.gn @@ -0,0 +1,142 @@ +# 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. + +import("//build/test.gni") +SUBSYSTEM_DIR = "//foundation/communication/wifi" +module_output_path = "wifi_standard/idl_client_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest", + ] +} + +ohos_unittest("idl_client_unittest") { + module_out_path = module_output_path + sources = [ + "$SUBSYSTEM_DIR/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_iface.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_public_func.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_supplicant_iface.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_base_hal_interface.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.cpp", + "idl_client_test_main.cpp", + "wifi_ap_hal_interface_test.cpp", + "wifi_base_hal_interface_test.cpp", + "wifi_chip_hal_interface_test.cpp", + "wifi_idl_client_test.cpp", + "wifi_idl_interface_test.cpp", + "wifi_p2p_hal_interface_test.cpp", + "wifi_sta_hal_interface_test.cpp", + "wifi_supplicant_hal_interface_test.cpp", + ] + + include_dirs = [ + "$SUBSYSTEM_DIR/interfaces/innerkits/native_cpp/wifi_standard/interfaces", + "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/include", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/config", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/utils", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/log", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "//utils/native/base/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + + deps = [ + "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_client", + "//utils/native/base:utils", + ] + + ldflags = [ + "-fPIC", + "--coverage", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + configs = [ ":module_private_config" ] + + part_name = "wifi_standard" + subsystem_name = "communication" + testonly = true +} + +ohos_unittest("mock_wifi_hal_service") { + module_out_path = module_output_path + sources = [ + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/log/log_helper.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/main.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_adapter.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_callback.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.c", + "mock_wifi_hal_service.c", + ] + + include_dirs = [ + "//utils/native/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "$SUBSYSTEM_DIR/interfaces/innerkits/native_cpp/wifi_standard/interfaces", + "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/common", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/log", + ] + + deps = [ + "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_server", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//utils/native/base:utils", + ] + + cflags_cc = [ "-fno-rtti" ] + + defines = [] + + part_name = "wifi_standard" + subsystem_name = "communication" + testonly = true +} + +group("unittest") { + testonly = true + deps = [ + ":idl_client_unittest", + ":mock_wifi_hal_service", + ] +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/idl_client_test_main.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/idl_client_test_main.cpp new file mode 100644 index 000000000..2c2414a40 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/idl_client_test_main.cpp @@ -0,0 +1,21 @@ +/* + * 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 + +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/mock_wifi_hal_service.c b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/mock_wifi_hal_service.c new file mode 100644 index 000000000..741de69b1 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/mock_wifi_hal_service.c @@ -0,0 +1,763 @@ +/* + * 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 "wifi_hal_base_interface.h" +#include "wifi_hal_sta_interface.h" +#include "wifi_hal_ap_interface.h" +#include "wifi_hal_chip_interface.h" +#include "wifi_hal_p2p_struct.h" +#include "wifi_hal_callback.h" +#include +#include "securec.h" +#include "wifi_log.h" +#undef LOG_TAG +#define LOG_TAG "WifiMockHalService" + +/* --------- wifi_hal_base_interface.h begin -------------*/ +WifiErrorNo GetName(char *ifname, int32_t size) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetType(int32_t *type) +{ + return WIFI_HAL_SUCCESS; +} + +/* --------- wifi_hal_base_interface.h end -------------*/ + +/* --------- wifi_hal_sta_interface.h begin -------------*/ +WifiErrorNo Start(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo Stop(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo ForceStop(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo StartSupplicant(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo StopSupplicant(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo ConnectSupplicant(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo DisconnectSupplicant(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo RequestToSupplicant(const unsigned char *buf, int32_t bufSize) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo StartScan(const ScanSettings *settings) +{ + WifiHalCbNotifyScanEnd(0); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetScanInfos(ScanInfo *results, int *size) +{ + if (results == NULL || size == NULL || *size == 0) { + return WIFI_HAL_SUCCESS; + } + if (strcpy_s(results[0].ssid, sizeof(results[0].ssid), "OHOS_testAp") != EOK || + strcpy_s(results[0].bssid, sizeof(results[0].bssid), "00:00:00:00:00:00") != EOK || + strcpy_s(results[0].flags, sizeof(results[0].flags), "CMCC") != EOK) { + return WIFI_HAL_FAILED; + } + results[0].freq = 2412; + results[0].infoElems = (ScanInfoElem *)calloc(1, sizeof(ScanInfoElem)); + if (results[0].infoElems == NULL) { + return WIFI_HAL_FAILED; + } + results[0].infoElems[0].id = 0; + results[0].infoElems[0].content = (char *)calloc(64, sizeof(char)); + if (results[0].infoElems[0].content == NULL) { + free(results[0].infoElems); + return WIFI_HAL_FAILED; + } + if (strcpy_s(results[0].infoElems[0].content, 64, "hello") != EOK) { + free(results[0].infoElems[0].content); + free(results[0].infoElems); + return WIFI_HAL_FAILED; + } + results[0].infoElems[0].size = strlen(results[0].infoElems[0].content); + results[0].ieSize = 1; + results[0].timestamp = time(NULL); + results[0].ant = NETWORK_PRIVATE; + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo StartPnoScan(const PnoScanSettings *settings) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo StopPnoScan(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo Connect(int networkId) +{ + WifiHalCbNotifyConnectChanged(0, 0, "00:00:00:00:00:00"); + WifiHalCbNotifyWrongKey(0); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo Reconnect(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo Reassociate(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo Disconnect(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo SetPowerSave(int enable) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetStaCapabilities(int32_t *capabilities) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetDeviceMacAddress(unsigned char *mac, int *lenMac) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetFrequencies(int32_t band, int *frequencies, int32_t *size) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo SetAssocMacAddr(const unsigned char *mac, int lenMac) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo SetScanningMacAddress(const unsigned char *mac, int lenMac) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo DeauthLastRoamingBssid(const unsigned char *mac, int lenMac) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetSupportFeature(long *feature) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo RunCmd(const char *ifname, int32_t cmdid, const unsigned char *buf, int32_t bufSize) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo SetWifiTxPower(int32_t power) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo RemoveNetwork(int networkId) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo AddNetwork(int *networkId) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo EnableNetwork(int networkId) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo DisableNetwork(int networkId) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo SetNetwork(int networkId, const HidlSetNetworkConfig *confs, int size) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo SaveNetworkConfig(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo StartWpsPbcMode(const WifiWpsParam *param) +{ + WifiHalCbNotifyWpaStateChange(0); + WifiHalCbNotifyWpsOverlap(0); + WifiHalCbNotifyWpsTimeOut(0); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo StartWpsPinMode(const WifiWpsParam *param, int *pinCode) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo StopWps(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetRoamingCapabilities(WifiRoamCapability *capability) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo SetRoamConfig(char **blocklist, int blocksize, char **trustlist, int trustsize) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo WpaSetCountryCode(const char *countryCode) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo WpaGetCountryCode(char *countryCode, int codeSize) +{ + if (countryCode == NULL) { + return WIFI_HAL_FAILED; + } + for (int i = 0; i < codeSize && i < 2; ++i) { + countryCode[i] = 'C'; + } + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo WpaGetNetWork(HidlGetNetworkConfig *conf) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo WpaAutoConnect(int enable) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo WpaBlocklistClear(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetNetworkList(HidlNetworkInfo *infos, int *size) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetConnectSignalInfo(const char *endBssid, HidlWpaSignalInfo *info) +{ + return WIFI_HAL_SUCCESS; +} + +/* --------- wifi_hal_sta_interface.h end -------------*/ + +/* --------- wifi_hal_ap_interface.h begin -------------*/ +WifiErrorNo StartSoftAp(void) +{ + WifiHalCbApState("AP-ENABLED"); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo StartHostapd(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo StartHostapdHal(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo StopSoftAp(void) +{ + WifiHalCbApState("AP-DISABLED"); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo StopHostapd(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo StopHostapdHal(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetStaInfos(char *infos, int32_t *size) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo SetCountryCode(const char *code) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo SetHostapdConfig(HostapdConfig *config) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo SetMacFilter(const unsigned char *mac, int lenMac) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo DelMacFilter(const unsigned char *mac, int lenMac) +{ + char buff[1024] = {0}; + if (snprintf_s(buff, sizeof(buff), sizeof(buff) - 1, "AP-STA-CONNECTED %s", mac) < 0) { + return WIFI_HAL_FAILED; + } + WifiHalCbStaJoin(buff); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo DisassociateSta(const unsigned char *mac, int lenMac) +{ + char buff[1024] = {0}; + if (snprintf_s(buff, sizeof(buff), sizeof(buff) - 1, "AP-STA-DISCONNECTED %s", mac) < 0) { + return WIFI_HAL_FAILED; + } + WifiHalCbStaJoin(buff); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t *size) +{ + return WIFI_HAL_SUCCESS; +} + +/* --------- wifi_hal_ap_interface.h end -------------*/ + +/* --------- wifi_hal_chip_interface.h begin -------------*/ +WifiErrorNo GetWifiChip(uint8_t id, WifiChip *chip) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetWifiChipIds(uint8_t *ids, int32_t *size) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetChipId(int32_t *id) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo CreateIface(int32_t type, WifiIface *iface) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetIface(const char *ifname, WifiIface *iface) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetIfaceNames(int32_t type, char *ifaces, int32_t size) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo RemoveIface(const char *ifname) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetCapabilities(uint32_t *capabilities) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetSupportedComboModes(int32_t *modes, int32_t *size) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo ConfigComboModes(int32_t mode) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetComboModes(int32_t *id) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo RequestFirmwareDebugDump(unsigned char *bytes, int32_t *size) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo SetPowerMode(uint8_t mode) +{ + return WIFI_HAL_SUCCESS; +} + +/* --------- wifi_hal_chip_interface.h end -------------*/ +/* --------- wifi_hal_p2p_interface.h begin -----------*/ +WifiErrorNo P2pStart(void) +{ + WifiP2pHalCbNotifyConnectSupplicant(0); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pStop(void) +{ + P2pHalCbConnectSupplicantFailed(); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pForceStop(void) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetRandomMac(int enable) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetDeviceName(const char *name) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetSsidPostfixName(const char *postfixName) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetWpsDeviceType(const char *type) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetWpsConfigMethods(const char *config) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pGetDeviceAddress(char *deviceAddress, int size) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pFlush() +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pFlushService() +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSaveConfig() +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetupWpsPbc(const char *groupIfc, const char *address) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetupWpsPin(const char *groupIfc, const char *address, const char *pin, char *result, int resultLen) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pRemoveNetwork(int networkId) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pListNetworks(HidlP2pNetworkList *infoList) +{ + if (infoList == NULL) { + return WIFI_HAL_FAILED; + } + infoList->infos = (HidlP2pNetworkInfo *)calloc(1, sizeof(HidlP2pNetworkInfo)); + if (infoList->infos == NULL) { + return WIFI_HAL_FAILED; + } + infoList->infoNum = 1; + infoList->infos[0].id = 0; + if (strcpy_s(infoList->infos[0].ssid, sizeof(infoList->infos[0].ssid), "p2p_test") != EOK || + strcpy_s(infoList->infos[0].bssid, sizeof(infoList->infos[0].bssid), "00:00:00:00:00:00") != EOK || + strcpy_s(infoList->infos[0].flags, sizeof(infoList->infos[0].flags), "P2P-PERSISTENT") != EOK) { + free(infoList->infos); + infoList->infos = NULL; + return WIFI_HAL_FAILED; + } + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetGroupMaxIdle(const char *groupIfc, int time) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetPowerSave(const char *groupIfc, int enable) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetWfdEnable(int enable) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetWfdDeviceConfig(const char *config) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pStartFind(int timeout) +{ + HidlP2pDeviceInfo device; + if (memset_s(&device, sizeof(device), 0, sizeof(device)) != EOK || + strcpy_s(device.srcAddress, sizeof(device.srcAddress), "00:00:00:00:00:00") != EOK || + strcpy_s(device.p2pDeviceAddress, sizeof(device.p2pDeviceAddress), "01:00:00:00:00:00") != EOK || + strcpy_s(device.deviceName, sizeof(device.deviceName), "p2p_test") != EOK || + strcpy_s(device.wfdDeviceInfo, sizeof(device.wfdDeviceInfo), "0x000000000000") != EOK) { + return WIFI_HAL_FAILED; + } + device.wfdLength = strlen(device.wfdDeviceInfo); + P2pHalCbDeviceFound(&device); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pStopFind() +{ + P2pHalCbDeviceLost("00:00:00:00:00:00"); + P2pHalCbFindStopped(); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetExtListen(int enable, int period, int interval) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetListenChannel(int channel, int regClass) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pConnect(const HidlP2pConnectInfo *info) +{ + P2pHalCbStaConnectState("00:00:00:00:00:00", 1); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pCancelConnect() +{ + P2pHalCbStaConnectState("00:00:00:00:00:00", 0); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pProvisionDiscovery(const char *peerBssid, int mode) +{ + P2pHalCbGoNegotiationRequest(peerBssid, 10086); + P2pHalCbGoNegotiationSuccess(); + P2pHalCbGoNegotiationFailure(1); + P2pHalCbProvisionDiscoveryPbcRequest("00:00:00:00:00:00"); + P2pHalCbProvisionDiscoveryPbcResponse("10:00:00:00:00:00"); + P2pHalCbProvisionDiscoveryEnterPin("20:00:00:00:00:00"); + P2pHalCbProvisionDiscoveryShowPin("30:00:00:00:00:00", "12345678"); + P2pHalCbProvisionDiscoveryFailure(); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pAddGroup(int isPersistent, int networkId) +{ + P2pHalCbGroupFormationSuccess(); + P2pHalCbGroupFormationFailure("unknown"); + HidlP2pGroupInfo info; + if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK || + strcpy_s(info.groupIfName, sizeof(info.groupIfName), "p2p-dev-wlan1") != EOK || + strcpy_s(info.ssid, sizeof(info.ssid), "p2p_honor_suffix") != EOK || + strcpy_s(info.passphrase, sizeof(info.passphrase), "12345678") != EOK || + strcpy_s(info.goDeviceAddress, sizeof(info.goDeviceAddress), "01:00:00:00:00:00") != EOK) { + return WIFI_HAL_FAILED; + } + P2pHalCbGroupStarted(&info); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pRemoveGroup(const char *interface) +{ + P2pHalCbGroupRemoved(interface, 0); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pInvite(int persisitent, const char *peerBssid, const char *goBssid, const char *ifname) +{ + HidlP2pInvitationInfo info; + if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK || + strcpy_s(info.srcAddress, sizeof(info.srcAddress), "00:00:00:00:00:00") != EOK || + strcpy_s(info.goDeviceAddress, + sizeof(info.goDeviceAddress), + ((goBssid == NULL) ? "00:00:00:00:00:00" : goBssid)) != EOK || + strcpy_s(info.bssid, sizeof(info.bssid), ((peerBssid == NULL) ? "00:00:00:00:00:00" : peerBssid)) != EOK) { + return WIFI_HAL_FAILED; + } + P2pHalCbInvitationReceived(&info); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pReinvoke(int networkId, const char *bssid) +{ + P2pHalCbInvitationResult(bssid, 0); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pGetGroupCapability(const char *bssid, int *cap) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pAddService(const HidlP2pServiceInfo *info) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pRemoveService(const HidlP2pServiceInfo *info) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pReqServiceDiscovery(const char *bssid, const char *msg) +{ + HidlP2pServDiscReqInfo reqInfo; + if (memset_s(&reqInfo, sizeof(reqInfo), 0, sizeof(reqInfo)) != EOK || + strcpy_s(reqInfo.mac, sizeof(reqInfo.mac), "00:00:00:00:00:00") != EOK) { + return WIFI_HAL_FAILED; + } + P2pHalCbServDiscReq(&reqInfo); + HidlP2pServDiscRespInfo info; + if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK || + strcpy_s(info.srcAddress, sizeof(info.srcAddress), "00:00:00:00:00:00") != EOK) { + return WIFI_HAL_FAILED; + } + info.tlvs = (char *)calloc(256, sizeof(char)); + if (info.tlvs == NULL || strcpy_s(info.tlvs, 256, "0123456789abcdefABCDEF") != EOK) { + free(info.tlvs); + return WIFI_HAL_FAILED; + } + P2pHalCbServiceDiscoveryResponse(&info); + free(info.tlvs); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pCancelServiceDiscovery(const char *id) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetMiracastType(int type) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetPersistentReconnect(int mode) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pRespServerDiscovery(HidlP2pServDiscReqInfo *info) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetServDiscExternal(int mode) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetWpsSecondaryDeviceType(const char *type) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pGetPeer(const char *bssid, HidlP2pDeviceInfo *peerInfo) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pGetFrequencies(int band, int *frequencies, int *size) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pSetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int size) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pGetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int size) +{ + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo P2pAddNetwork(int *networkId) +{ + return WIFI_HAL_SUCCESS; +} + +/*--------------- wifi_hal_p2p_interface.h end---------------------------*/ diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.cpp new file mode 100644 index 000000000..2d0cb7f1e --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.cpp @@ -0,0 +1,135 @@ +/* + * 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 "wifi_ap_hal_interface_test.h" +#include "wifi_ap_hal_interface.h" +#include "wifi_log.h" +#undef LOG_TAG +#define LOG_TAG "OHWIFI_IDLCLIENT_AP_TEST" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +void ApHalTestStationCbk(const WifiApConnectionNofify &info) +{ + LOGD("apHalTestStationCbk"); + LOGD("station : %s, %s", info.mac.c_str(), ((info.type == 105) ? "join" : "leave")); +} + +void ApHalTestStateCbk(int state) +{ + LOGD("apHalTestStateCbk state: %d", state); +} + +void WifiApHalInterfaceTest::SetUpTestCase() +{ + IWifiApMonitorEventCallback callback; + callback.onStaJoinOrLeave = ApHalTestStationCbk; + callback.onApEnableOrDisable = ApHalTestStateCbk; + WifiApHalInterface::GetInstance().RegisterApEvent(callback); +} + +void WifiApHalInterfaceTest::TearDownTestCase() +{ + IWifiApMonitorEventCallback callback; + WifiApHalInterface::GetInstance().RegisterApEvent(callback); +} + +HWTEST_F(WifiApHalInterfaceTest, StartApTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiApHalInterface::GetInstance().StartAp(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiApHalInterfaceTest, SetSoftApConfigTest, TestSize.Level1) +{ + HotspotConfig config; + config.SetSecurityType(KeyMgmt::NONE); + config.SetSsid("myWifiTest"); + config.SetBand(BandType::BAND_2GHZ); + config.SetChannel(0); + config.SetMaxConn(1); + WifiErrorNo ret = WifiApHalInterface::GetInstance().SetSoftApConfig(config); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiApHalInterfaceTest, GetStationListTest, TestSize.Level1) +{ + std::vector vec; + WifiErrorNo ret = WifiApHalInterface::GetInstance().GetStationList(vec); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiApHalInterfaceTest, AddBlockByMacTest, TestSize.Level1) +{ + std::string mac = "abcdefghijklmn"; + WifiErrorNo ret = WifiApHalInterface::GetInstance().AddBlockByMac(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_INPUT_MAC_INVALID); + mac = "00:00:00:00:00:00"; + ret = WifiApHalInterface::GetInstance().AddBlockByMac(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiApHalInterfaceTest, DelBlockByMacTest, TestSize.Level1) +{ + std::string mac = "abcdefghijklmn"; + WifiErrorNo ret = WifiApHalInterface::GetInstance().DelBlockByMac(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_INPUT_MAC_INVALID); + mac = "00:00:00:00:00:00"; + ret = WifiApHalInterface::GetInstance().DelBlockByMac(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiApHalInterfaceTest, RemoveStationTest, TestSize.Level1) +{ + std::string mac = "abcdefghijklmn"; + WifiErrorNo ret = WifiApHalInterface::GetInstance().RemoveStation(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_INPUT_MAC_INVALID); + mac = "00:00:00:00:00:00"; + ret = WifiApHalInterface::GetInstance().RemoveStation(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiApHalInterfaceTest, DisconnectStaByMacTest, TestSize.Level1) +{ + std::string mac = "abcdefghijklmn"; + WifiErrorNo ret = WifiApHalInterface::GetInstance().DisconnectStaByMac(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_INPUT_MAC_INVALID); + mac = "00:00:00:00:00:00"; + ret = WifiApHalInterface::GetInstance().DisconnectStaByMac(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiApHalInterfaceTest, GetFrequenciesByBandTest, TestSize.Level1) +{ + std::vector freq; + WifiErrorNo ret = WifiApHalInterface::GetInstance().GetFrequenciesByBand(1, freq); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiApHalInterfaceTest, SetWifiCountryCodeTest, TestSize.Level1) +{ + std::string code = "CN"; + WifiErrorNo ret = WifiApHalInterface::GetInstance().SetWifiCountryCode(code); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiApHalInterfaceTest, StopApTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiApHalInterface::GetInstance().StopAp(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.h new file mode 100644 index 000000000..f831e3168 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.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_WIFI_AP_HAL_INTERFACE_TEST_H +#define OHOS_WIFI_AP_HAL_INTERFACE_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiApHalInterfaceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.cpp new file mode 100644 index 000000000..01a1961c9 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.cpp @@ -0,0 +1,37 @@ +/* + * 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 "wifi_base_hal_interface_test.h" +#include "wifi_base_hal_interface.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiBaseHalInterfaceTest, InitIdlClientTest, TestSize.Level1) +{ + WifiBaseHalInterface iface; + iface.InitIdlClient(); + ASSERT_TRUE(iface.mIdlClient != nullptr); +} + +HWTEST_F(WifiBaseHalInterfaceTest, ExitAllIdlClientTest, TestSize.Level1) +{ + WifiBaseHalInterface iface; + iface.InitIdlClient(); + ASSERT_TRUE(iface.mIdlClient != nullptr); + iface.ExitAllIdlClient(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.h new file mode 100644 index 000000000..153311334 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.h @@ -0,0 +1,37 @@ +/* + * 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_WIFI_BASE_HAL_INTERFACE_TEST_H +#define OHOS_WIFI_BASE_HAL_INTERFACE_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiBaseHalInterfaceTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.cpp new file mode 100644 index 000000000..4790f59ff --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.cpp @@ -0,0 +1,111 @@ +/* + * 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 "wifi_chip_hal_interface_test.h" +#include "wifi_chip_hal_interface.h" +#include "wifi_log.h" +#undef LOG_TAG +#define LOG_TAG "OHWIFI_IDLCLIENT_CHIP_TEST" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +void OnIfaceAdded(int32_t type, char *ifname) +{ + LOGD("OnIfaceAdded type %d, ifname: %s", type, ((ifname == nullptr) ? "" : ifname)); +} + +void OnIfaceRemoved(int32_t type, char *ifname) +{ + LOGD("OnIfaceRemoved type %d, ifname: %s", type, ((ifname == nullptr) ? "" : ifname)); +} + +void WifiChipHalInterfaceTest::SetUpTestCase() +{ + WifiChipEventCallback callback; + callback.onIfaceAdded = OnIfaceAdded; + callback.onIfaceRemoved = OnIfaceRemoved; + WifiChipHalInterface::GetInstance().RegisterChipEventCallback(callback); +} + +void WifiChipHalInterfaceTest::TearDownTestCase() +{ + WifiChipEventCallback callback; + WifiChipHalInterface::GetInstance().RegisterChipEventCallback(callback); +} + +HWTEST_F(WifiChipHalInterfaceTest, GetWifiChipObjectTest, TestSize.Level1) +{ + IWifiChip chip; + WifiErrorNo ret = WifiChipHalInterface::GetInstance().GetWifiChipObject(1, chip); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiChipHalInterfaceTest, GetChipIdsTest, TestSize.Level1) +{ + std::vector vec; + WifiErrorNo ret = WifiChipHalInterface::GetInstance().GetChipIds(vec); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiChipHalInterfaceTest, GetUsedChipIdTest, TestSize.Level1) +{ + int id = 0; + WifiErrorNo ret = WifiChipHalInterface::GetInstance().GetUsedChipId(id); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiChipHalInterfaceTest, GetChipCapabilitiesTest, TestSize.Level1) +{ + int capabilities = 0; + WifiErrorNo ret = WifiChipHalInterface::GetInstance().GetChipCapabilities(capabilities); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiChipHalInterfaceTest, GetSupportedModesTest, TestSize.Level1) +{ + std::vector vec; + WifiErrorNo ret = WifiChipHalInterface::GetInstance().GetSupportedModes(vec); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiChipHalInterfaceTest, ConfigRunModesTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiChipHalInterface::GetInstance().ConfigRunModes(0); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiChipHalInterfaceTest, GetCurrentModeTest, TestSize.Level1) +{ + int mode = 0; + WifiErrorNo ret = WifiChipHalInterface::GetInstance().GetCurrentMode(mode); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiChipHalInterfaceTest, RequestFirmwareDebugInfoTest, TestSize.Level1) +{ + std::string info; + WifiErrorNo ret = WifiChipHalInterface::GetInstance().RequestFirmwareDebugInfo(info); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiChipHalInterfaceTest, SetWifiPowerModeTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiChipHalInterface::GetInstance().SetWifiPowerMode(0); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.h new file mode 100644 index 000000000..e63b414a4 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.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_WIFI_CHIP_HAL_INTERFACE_TEST_H +#define OHOS_WIFI_CHIP_HAL_INTERFACE_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiChipHalInterfaceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.cpp new file mode 100644 index 000000000..b1246e247 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.cpp @@ -0,0 +1,356 @@ +/* + * 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 "wifi_idl_client_test.h" +#include "securec.h" +#include "wifi_scan_param.h" +#include "wifi_log.h" + +#undef LOG_TAG +#define LOG_TAG "WifiIdlClientTest" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiIdlClientTest, InitClientTest, TestSize.Level1) +{ + EXPECT_TRUE(mClient.InitClient() == 0); +} + +HWTEST_F(WifiIdlClientTest, StartWifiTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + EXPECT_TRUE(mClient.StartWifi() == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiIdlClientTest, GetStaDeviceMacAddressTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + std::string mac; + WifiErrorNo err = mClient.GetStaDeviceMacAddress(mac); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK) << " Get device mac address is: " << mac; +} + +HWTEST_F(WifiIdlClientTest, GetStaCapabilitiesTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + unsigned int capabilities = 0; + WifiErrorNo err = mClient.GetStaCapabilities(capabilities); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiIdlClientTest, GetSupportFrequenciesTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + std::vector freqs; + WifiErrorNo err = mClient.GetSupportFrequencies(1, freqs); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK); + for (auto iter = freqs.begin(); iter != freqs.end(); ++iter) { + LOGD("Get frequency: %{public}d", *iter); + } + freqs.clear(); + err = mClient.GetSupportFrequencies(2, freqs); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK); + for (auto iter = freqs.begin(); iter != freqs.end(); ++iter) { + LOGD("Get frequency: %{public}d", *iter); + } + freqs.clear(); + err = mClient.GetSupportFrequencies(4, freqs); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK); + for (auto iter = freqs.begin(); iter != freqs.end(); ++iter) { + LOGD("Get frequency: %{public}d", *iter); + } +} + +HWTEST_F(WifiIdlClientTest, SetConnectMacAddrTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + std::string mac = "abcdefghijklmn"; + WifiErrorNo err = mClient.SetConnectMacAddr(mac); + EXPECT_TRUE(err == WIFI_IDL_OPT_INPUT_MAC_INVALID); + mac = "00:00:00:00:00:00"; + err = mClient.SetConnectMacAddr(mac); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiIdlClientTest, SetScanMacAddressTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + std::string mac = "abcdefghijklmn"; + WifiErrorNo err = mClient.SetScanMacAddress(mac); + EXPECT_TRUE(err == WIFI_IDL_OPT_INPUT_MAC_INVALID); + mac = "00:00:00:00:00:00"; + err = mClient.SetScanMacAddress(mac); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiIdlClientTest, DisconnectLastRoamingBssidTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + std::string mac = "abcdefghijklmn"; + WifiErrorNo err = mClient.DisconnectLastRoamingBssid(mac); + EXPECT_TRUE(err == WIFI_IDL_OPT_INPUT_MAC_INVALID); + mac = "00:00:00:00:00:00"; + err = mClient.DisconnectLastRoamingBssid(mac); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiIdlClientTest, ReqGetSupportFeatureTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + long feature = 0; + WifiErrorNo err = mClient.ReqGetSupportFeature(feature); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiIdlClientTest, SetTxPowerTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + int power = 1; + WifiErrorNo err = mClient.SetTxPower(power); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK); +} + +static char **MockConVectorToCArrayString(const std::vector &vec) +{ + int size = vec.size(); + if (size == 0) { + return nullptr; + } + char **list = (char **)calloc(size, sizeof(char *)); + if (list == nullptr) { + return nullptr; + } + int i = 0; + for (; i < size; ++i) { + int len = vec[i].length(); + list[i] = (char *)calloc(len + 1, sizeof(char)); + if (list[i] == nullptr) { + break; + } + if (strncpy_s(list[i], len + 1, vec[i].c_str(), len) != EOK) { + break; + } + } + if (i < size) { + for (int j = 0; j <= i; ++j) { + free(list[j]); + } + free(list); + return nullptr; + } else { + return list; + } +} + +HWTEST_F(WifiIdlClientTest, MockConVectorToCArrayStringTest, TestSize.Level1) +{ + std::vector vec; + char **list = MockConVectorToCArrayString(vec); + ASSERT_TRUE(list == nullptr); + vec.push_back("hello"); + vec.push_back("world"); + list = MockConVectorToCArrayString(vec); + ASSERT_TRUE(list != nullptr); + for (std::size_t i = 0; i < vec.size(); ++i) { + ASSERT_TRUE(list[i] != nullptr); + ASSERT_TRUE(strcmp(list[i], vec[i].c_str()) == 0); + } + for (std::size_t i = 0; i < vec.size(); ++i) { + free(list[i]); + } + free(list); +} + +static bool MockScanTest(const WifiScanParam &scanParam) +{ + ScanSettings settings; + if (memset_s(&settings, sizeof(settings), 0, sizeof(settings)) != EOK) { + return false; + } + bool bfail = false; + do { + if (scanParam.hiddenNetworkSsid.size() > 0) { + settings.hiddenSsidSize = scanParam.hiddenNetworkSsid.size(); + settings.hiddenSsid = MockConVectorToCArrayString(scanParam.hiddenNetworkSsid); + if (settings.hiddenSsid == nullptr) { + bfail = true; + break; + } + } + if (scanParam.scanFreqs.size() > 0) { + settings.freqSize = scanParam.scanFreqs.size(); + settings.freqs = (int *)calloc(settings.freqSize, sizeof(int)); + if (settings.freqs == nullptr) { + bfail = true; + break; + } + for (int i = 0; i < settings.freqSize; ++i) { + settings.freqs[i] = scanParam.scanFreqs[i]; + } + } + if (scanParam.scanStyle > 0) { + settings.scanStyle = scanParam.scanStyle; + } + } while (0); + if (settings.freqs != nullptr) { + free(settings.freqs); + } + if (settings.hiddenSsid != nullptr) { + for (int i = 0; i < settings.hiddenSsidSize; ++i) { + free(settings.hiddenSsid[i]); + } + free(settings.hiddenSsid); + } + return !bfail; +} + +HWTEST_F(WifiIdlClientTest, ScanTest, TestSize.Level1) +{ + WifiScanParam param; + param.hiddenNetworkSsid.push_back("abcd"); + param.hiddenNetworkSsid.push_back("efgh"); + ASSERT_TRUE(MockScanTest(param)); + param.scanFreqs.push_back(2412); + param.scanFreqs.push_back(2417); + param.scanStyle = 1; + ASSERT_TRUE(MockScanTest(param)); +} + +HWTEST_F(WifiIdlClientTest, ReqGetNetworkListTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + std::vector infos; + WifiErrorNo err = mClient.ReqGetNetworkList(infos); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK); +} + +static void FreePnoScanPstr(PnoScanSettings &settings) +{ + if (settings.freqs != nullptr) { + free(settings.freqs); + } + if (settings.hiddenSsid != nullptr) { + for (int i = 0; i < settings.hiddenSsidSize; ++i) { + free(settings.hiddenSsid[i]); + } + free(settings.hiddenSsid); + } + if (settings.savedSsid != nullptr) { + for (int i = 0; i < settings.savedSsidSize; ++i) { + free(settings.savedSsid[i]); + } + free(settings.savedSsid); + } +} + +static bool MockPnoScanTest(const WifiPnoScanParam &scanParam) +{ + PnoScanSettings settings; + if (memset_s(&settings, sizeof(settings), 0, sizeof(settings)) != EOK) { + return false; + } + bool bfail = false; + do { + if (scanParam.scanInterval > 0) { + settings.scanInterval = scanParam.scanInterval; + } + settings.minRssi2Dot4Ghz = scanParam.minRssi2Dot4Ghz; + settings.minRssi5Ghz = scanParam.minRssi5Ghz; + if (scanParam.hiddenSsid.size() > 0) { + settings.hiddenSsidSize = scanParam.hiddenSsid.size(); + settings.hiddenSsid = MockConVectorToCArrayString(scanParam.hiddenSsid); + if (settings.hiddenSsid == nullptr) { + bfail = true; + break; + } + } + if (scanParam.savedSsid.size() > 0) { + settings.savedSsidSize = scanParam.savedSsid.size(); + settings.savedSsid = MockConVectorToCArrayString(scanParam.savedSsid); + if (settings.savedSsid == nullptr) { + bfail = true; + break; + } + } + if (scanParam.scanFreqs.size() > 0) { + settings.freqSize = scanParam.scanFreqs.size(); + settings.freqs = (int *)calloc(settings.freqSize, sizeof(int)); + if (settings.freqs == nullptr) { + return WIFI_IDL_OPT_FAILED; + } + for (int i = 0; i < settings.freqSize; ++i) { + settings.freqs[i] = scanParam.scanFreqs[i]; + } + } + } while (0); + FreePnoScanPstr(settings); + return !bfail; +} + +HWTEST_F(WifiIdlClientTest, ReqStartPnoScanTest, TestSize.Level1) +{ + WifiPnoScanParam param; + param.hiddenSsid.push_back("abcd"); + param.hiddenSsid.push_back("efgh"); + ASSERT_TRUE(MockPnoScanTest(param)); + param.scanFreqs.push_back(2412); + param.scanFreqs.push_back(2417); + ASSERT_TRUE(MockPnoScanTest(param)); + param.savedSsid.push_back("abcd"); + ASSERT_TRUE(MockPnoScanTest(param)); +} + +HWTEST_F(WifiIdlClientTest, StopWifiTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + EXPECT_TRUE(mClient.StopWifi() == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiIdlClientTest, AddBlockByMacTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + std::string mac = "abcdefghijklmn"; + WifiErrorNo err = mClient.AddBlockByMac(mac); + EXPECT_TRUE(err == WIFI_IDL_OPT_INPUT_MAC_INVALID); + mac = "00:00:00:00:00:00"; + err = mClient.AddBlockByMac(mac); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK || err == WIFI_IDL_OPT_HOSTAPD_NOT_INIT); +} + +HWTEST_F(WifiIdlClientTest, DelBlockByMacTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + std::string mac = "abcdefghijklmn"; + WifiErrorNo err = mClient.DelBlockByMac(mac); + EXPECT_TRUE(err == WIFI_IDL_OPT_INPUT_MAC_INVALID); + mac = "00:00:00:00:00:00"; + err = mClient.DelBlockByMac(mac); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK || err == WIFI_IDL_OPT_HOSTAPD_NOT_INIT); +} + +HWTEST_F(WifiIdlClientTest, RemoveStationTest, TestSize.Level1) +{ + ASSERT_TRUE(mClient.InitClient() == 0); + std::string mac = "abcdefghijklmn"; + WifiErrorNo err = mClient.RemoveStation(mac); + EXPECT_TRUE(err == WIFI_IDL_OPT_INPUT_MAC_INVALID); + mac = "00:00:00:00:00:00"; + err = mClient.RemoveStation(mac); + EXPECT_TRUE(err == WIFI_IDL_OPT_OK || err == WIFI_IDL_OPT_HOSTAPD_NOT_INIT); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.h new file mode 100644 index 000000000..75de234d6 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.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_WIFI_IDL_CLIENT_TEST_H +#define OHOS_WIFI_IDL_CLIENT_TEST_H + +#include +#include "wifi_idl_client.h" + +namespace OHOS { +namespace Wifi { +class WifiIdlClientTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: + WifiIdlClient mClient; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.cpp new file mode 100644 index 000000000..5be1648b6 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.cpp @@ -0,0 +1,126 @@ +/* + * 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 "wifi_idl_interface_test.h" +#include "i_wifi.h" +#include "i_wifi_chip.h" +#include "i_wifi_iface.h" +#include "i_wifi_sta_iface.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiIdlInterfaceTest, GetWifiChipTest, TestSize.Level1) +{ + uint8_t id = 0; + IWifiChip chip; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, GetWifiChip(id, &chip)); +} + +HWTEST_F(WifiIdlInterfaceTest, GetWifiChipIdsTest, TestSize.Level1) +{ + uint8_t chipIds[8] = {0}; + int32_t size = 8; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, GetWifiChipIds(chipIds, &size)); +} + +HWTEST_F(WifiIdlInterfaceTest, GetChipIdTest, TestSize.Level1) +{ + int32_t id = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, GetChipId(&id)); +} + +HWTEST_F(WifiIdlInterfaceTest, CreateIfaceTest, TestSize.Level1) +{ + int32_t type = 0; + IWifiIface iface; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, CreateIface(type, &iface)); +} + +HWTEST_F(WifiIdlInterfaceTest, GetIfaceTest, TestSize.Level1) +{ + char ifname[] = "wlan0"; + IWifiIface iface; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, GetIface(ifname, &iface)); +} + +HWTEST_F(WifiIdlInterfaceTest, GetIfaceNamesTest, TestSize.Level1) +{ + char iface[32] = {0}; + int size = 32; + int32_t type = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, GetIfaceNames(type, iface, size)); +} + +HWTEST_F(WifiIdlInterfaceTest, RemoveIfaceTest, TestSize.Level1) +{ + char ifname[] = "wlan0"; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, RemoveIface(ifname)); +} + +HWTEST_F(WifiIdlInterfaceTest, ConfigComboModesTest, TestSize.Level1) +{ + int32_t mode = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, ConfigComboModes(mode)); +} + +HWTEST_F(WifiIdlInterfaceTest, GetComboModesTest, TestSize.Level1) +{ + int32_t mode = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, GetComboModes(&mode)); +} + +HWTEST_F(WifiIdlInterfaceTest, RequestFirmwareDebugDumpTest, TestSize.Level1) +{ + unsigned char buff[128] = {0}; + int size = 128; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, RequestFirmwareDebugDump(buff, &size)); +} + +HWTEST_F(WifiIdlInterfaceTest, SetPowerModeTest, TestSize.Level1) +{ + uint8_t mode = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, SetPowerMode(mode)); +} + +HWTEST_F(WifiIdlInterfaceTest, GetNameTest, TestSize.Level1) +{ + char ifname[32] = {0}; + int size = 32; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, GetName(ifname, size)); +} + +HWTEST_F(WifiIdlInterfaceTest, GetTypeTest, TestSize.Level1) +{ + int32_t type = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, GetType(&type)); +} + +HWTEST_F(WifiIdlInterfaceTest, GetStaCapabilitiesTest, TestSize.Level1) +{ + int32_t capabilities = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, GetStaCapabilities(&capabilities)); +} + +HWTEST_F(WifiIdlInterfaceTest, RunCmdTest, TestSize.Level1) +{ + char ifname[] = "wlan0"; + int32_t cmdId = 0; + unsigned char buff[] = "run cmd buffer"; + int32_t bufSize = strlen((const char *)buff); + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, RunCmd(ifname, cmdId, buff, bufSize)); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.h new file mode 100644 index 000000000..fbef8f303 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.h @@ -0,0 +1,37 @@ +/* + * 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_WIFI_IDL_INTERFACE_TEST_H +#define OHOS_WIFI_IDL_INTERFACE_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiIdlInterfaceTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.cpp new file mode 100644 index 000000000..07573407b --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.cpp @@ -0,0 +1,505 @@ +/* + * 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 "wifi_p2p_hal_interface_test.h" +#include +#include "wifi_p2p_hal_interface.h" +#include "wifi_p2p_msg.h" +#include "wifi_log.h" +#include "wifi_global_func.h" +#undef LOG_TAG +#define LOG_TAG "OHWIFI_IDLCLIENT_P2P_TEST" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +void onConnectSupplicant(int status) +{ + LOGD("onConnectSupplicant...status: %d\n", status); +} + +void onDeviceFound(const IdlP2pDeviceFound &info) +{ + LOGD("onDeviceFound...deviceCapabilities: %d\n", info.deviceCapabilities); +} + +void onDeviceLost(const std::string &address) +{ + LOGD("onDeviceLost...address: %s\n", address.c_str()); +} + +void onGoNegotiationRequest(const std::string &srcAddr, short passId) +{ + LOGD("onGoNegotiationRequest...srcAddr: %s, passId: %d\n", srcAddr.c_str(), passId); +} + +void onGoNegotiationSuccess() +{ + LOGD("onGoNegotiationSuccess...\n"); +} + +void onGoNegotiationFailure(int status) +{ + LOGD("onGoNegotiationFailure...status: %d\n", status); +} + +void onInvitationReceived(const IdlP2pInvitationInfo &info) +{ + LOGD("onInvitationReceived...operatingFrequency: %d\n", info.operatingFrequency); +} + +void onInvitationResult(const std::string &bssid, int status) +{ + LOGD("onInvitationResult...bssid: %s, status: %d\n", bssid.c_str(), status); +} + +void onGroupFormationSuccess() +{ + LOGD("onGroupFormationSuccess...\n"); +} + +void onGroupFormationFailure(const std::string &reason) +{ + LOGD("onGroupFormationFailure...reason: %s\n", reason.c_str()); +} + +void onGroupStarted(const IdlP2pGroupInfo &info) +{ + LOGD("onGroupStarted...frequency: %d\n", info.frequency); +} + +void onGroupRemoved(const std::string &groupIfName, bool isGo) +{ + LOGD("onGroupRemoved...groupIfName: %s, isGo: %d\n", groupIfName.c_str(), isGo); +} + +void onProvisionDiscoveryPbcRequest(const std::string &address) +{ + LOGD("onProvisionDiscoveryPbcRequest...address: %s\n", address.c_str()); +} + +void onProvisionDiscoveryPbcResponse(const std::string &address) +{ + LOGD("onProvisionDiscoveryPbcResponse...address: %s\n", address.c_str()); +} + +void onProvisionDiscoveryEnterPin(const std::string &address) +{ + LOGD("onProvisionDiscoveryEnterPin...address: %s\n", address.c_str()); +} + +void onProvisionDiscoveryShowPin(const std::string &address, const std::string &pin) +{ + LOGD("onProvisionDiscoveryShowPin...address: %s, pin: %s\n", address.c_str(), pin.c_str()); +} + +void onProvisionDiscoveryFailure() +{ + LOGD("onProvisionDiscoveryFailure...\n"); +} + +void onFindStopped() +{ + LOGD("onFindStopped...\n"); +} + +void onServiceDiscoveryResponse( + const std::string &srcAddress, short updateIndicator, const std::vector &tlvs) +{ + LOGD("onServiceDiscoveryResponse...address: %s, updateIndicator: %d, tlvsLength: %zu\n", + srcAddress.c_str(), + updateIndicator, + tlvs.size()); +} + +void onStaDeauthorized(const std::string &address) +{ + LOGD("onStaDeauthorized...address: %s\n", address.c_str()); +} + +void onStaAuthorized(const std::string &address) +{ + LOGD("onStaAuthorized...address: %s\n", address.c_str()); +} + +void connectSupplicantFailed() +{ + LOGD("connectSupplicantFailed...\n"); +} + +void onP2pServDiscReq(const IdlP2pServDiscReqInfo &info) +{ + LOGD("onP2pServDiscReq \n"); + LOGD(" service discovery freq: %d\n", info.freq); + LOGD(" service discovery dialogToken: %d\n", info.dialogToken); + LOGD(" service discovery updateIndic: %d\n", info.updateIndic); + LOGD(" service discovery mac: %s\n", info.mac.c_str()); +} + +void WifiP2pHalInterfaceTest::SetUpTestCase() +{ + P2pHalCallback callbacks; + callbacks.onConnectSupplicant = onConnectSupplicant; + callbacks.onDeviceLost = onDeviceLost; + callbacks.onGoNegotiationRequest = onGoNegotiationRequest; + callbacks.onGoNegotiationSuccess = onGoNegotiationSuccess; + callbacks.onGoNegotiationFailure = onGoNegotiationFailure; + callbacks.onInvitationReceived = onInvitationReceived; + callbacks.onInvitationResult = onInvitationResult; + callbacks.onGroupFormationSuccess = onGroupFormationSuccess; + callbacks.onGroupFormationFailure = onGroupFormationFailure; + callbacks.onGroupStarted = onGroupStarted; + callbacks.onGroupRemoved = onGroupRemoved; + callbacks.onProvisionDiscoveryPbcRequest = onProvisionDiscoveryPbcRequest; + callbacks.onProvisionDiscoveryPbcResponse = onProvisionDiscoveryPbcResponse; + callbacks.onProvisionDiscoveryEnterPin = onProvisionDiscoveryEnterPin; + callbacks.onProvisionDiscoveryShowPin = onProvisionDiscoveryShowPin; + callbacks.onProvisionDiscoveryFailure = onProvisionDiscoveryFailure; + callbacks.onFindStopped = onFindStopped; + callbacks.onServiceDiscoveryResponse = onServiceDiscoveryResponse; + callbacks.onStaDeauthorized = onStaDeauthorized; + callbacks.onStaAuthorized = onStaAuthorized; + callbacks.connectSupplicantFailed = connectSupplicantFailed; + callbacks.onP2pServDiscReq = onP2pServDiscReq; + WifiP2PHalInterface::GetInstance().RegisterP2pCallback(callbacks); +} + +void WifiP2pHalInterfaceTest::TearDownTestCase() +{ + P2pHalCallback callbacks; + WifiP2PHalInterface::GetInstance().RegisterP2pCallback(callbacks); +} + +HWTEST_F(WifiP2pHalInterfaceTest, P2pStart_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().StartP2p()); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetupWpsPbc_SUCCESS, TestSize.Level1) +{ + std::string groupInterface = "groupInterface"; + std::string bssid = "bssid"; + + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().StartWpsPbc(groupInterface, bssid)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetupWpsPin_SUCCESS, TestSize.Level1) +{ + std::string groupInterface = "groupInterface"; + std::string bssid; + std::string pin = "adc123456"; + std::string result; + + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_INVALID_PARAM, + WifiP2PHalInterface::GetInstance().StartWpsPin(groupInterface, bssid, pin, result)); + pin.clear(); + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, + WifiP2PHalInterface::GetInstance().StartWpsPin(groupInterface, bssid, pin, result)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, RemoveNetwork_SUCCESS, TestSize.Level1) +{ + int networkId = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().RemoveNetwork(networkId)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, ListNetworksTest, TestSize.Level1) +{ + std::map mapGroups; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().ListNetworks(mapGroups)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetWpsDeviceName_SUCCESS, TestSize.Level1) +{ + std::string name = "testName"; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SetP2pDeviceName(name)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetWpsDeviceType_SUCCESS, TestSize.Level1) +{ + std::string type = "testType"; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SetP2pDeviceType(type)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetWpsConfigMethods_SUCCESS, TestSize.Level1) +{ + std::string config = "testConfig"; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SetP2pConfigMethods(config)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetSsidPostfixName_SUCCESS, TestSize.Level1) +{ + std::string postfixName = "testPostfixName"; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SetP2pSsidPostfix(postfixName)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetGroupMaxIdle_SUCCESS, TestSize.Level1) +{ + std::string groupInterface = "testGroupName"; + size_t time = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SetP2pGroupIdle(groupInterface, time)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetPowerSave_SUCCESS, TestSize.Level1) +{ + std::string groupInterface; + bool enable = false; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SetP2pPowerSave(groupInterface, enable)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetWfdEnable_SUCCESS, TestSize.Level1) +{ + bool enable = false; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SetWfdEnable(enable)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetWfdDeviceConfig_SUCCESS, TestSize.Level1) +{ + std::string config; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SetWfdDeviceConfig(config)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, StartP2pFind_SUCCESS, TestSize.Level1) +{ + size_t timeout = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().P2pFind(timeout)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, StopP2pFind_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().P2pStopFind()); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetExtListen_SUCCESS, TestSize.Level1) +{ + bool enable = false; + size_t period = 0; + size_t interval = 0; + EXPECT_EQ( + WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().P2pConfigureListen(enable, period, interval)); + enable = true; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_INVALID_PARAM, + WifiP2PHalInterface::GetInstance().P2pConfigureListen(enable, period, interval)); + period = 65536; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_INVALID_PARAM, + WifiP2PHalInterface::GetInstance().P2pConfigureListen(enable, period, interval)); + period = 10; + interval = 65536; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_INVALID_PARAM, + WifiP2PHalInterface::GetInstance().P2pConfigureListen(enable, period, interval)); + interval = 60; + EXPECT_EQ( + WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().P2pConfigureListen(enable, period, interval)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetListenChannel_SUCCESS, TestSize.Level1) +{ + size_t channel = 0; + unsigned char regClass = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SetListenChannel(channel, regClass)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, P2pFlush_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().P2pFlush()); +} + +HWTEST_F(WifiP2pHalInterfaceTest, Connect_SUCCESS, TestSize.Level1) +{ + WifiP2pConfig config; + bool isJoinExistingGroup = false; + std::string pin; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_INVALID_PARAM, + WifiP2PHalInterface::GetInstance().Connect(config, isJoinExistingGroup, pin)); + config.SetDeviceAddress("00:00:00:00:00:00"); + WpsInfo wpsInfo; + wpsInfo.SetPin("12345678"); + wpsInfo.SetWpsMethod(WpsMethod::WPS_METHOD_PBC); + config.SetWpsInfo(wpsInfo); + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_INVALID_PARAM, + WifiP2PHalInterface::GetInstance().Connect(config, isJoinExistingGroup, pin)); + wpsInfo.SetPin(""); + config.SetWpsInfo(wpsInfo); + EXPECT_EQ( + WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().Connect(config, isJoinExistingGroup, pin)); + isJoinExistingGroup = true; + EXPECT_EQ( + WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().Connect(config, isJoinExistingGroup, pin)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, CancelConnect_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().CancelConnect()); +} + +HWTEST_F(WifiP2pHalInterfaceTest, ProvisionDiscovery_SUCCESS, TestSize.Level1) +{ + WifiP2pConfig config; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().ProvisionDiscovery(config)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, AddToGroup_SUCCESS, TestSize.Level1) +{ + bool isPersistent = false; + int networkId = 0; + int freq = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().GroupAdd(isPersistent, networkId, freq)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, RemoveGroup_SUCCESS, TestSize.Level1) +{ + std::string groupInterface; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().GroupRemove(groupInterface)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, Invite_SUCCESS, TestSize.Level1) +{ + WifiP2pGroupInfo group; + std::string deviceAddr; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().Invite(group, deviceAddr)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, Reinvoke_SUCCESS, TestSize.Level1) +{ + int networkId = 13; + std::string deviceAddr; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().Reinvoke(networkId, deviceAddr)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, GetDeviceAddress_SUCCESS, TestSize.Level1) +{ + std::string deviceAddress; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().GetDeviceAddress(deviceAddress)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, GetGroupCapability_SUCCESS, TestSize.Level1) +{ + std::string deviceAddress; + uint32_t capacity = 0; + EXPECT_EQ( + WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().GetGroupCapability(deviceAddress, capacity)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, P2pServiceAddTest, TestSize.Level1) +{ + WifiP2pServiceInfo info; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().P2pServiceAdd(info)); + std::vector vec; + vec.push_back("upnp 0"); + info.SetQueryList(vec); + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_FAILED, WifiP2PHalInterface::GetInstance().P2pServiceAdd(info)); + vec.clear(); + vec.push_back("upnpp 1 letusplaygame"); + info.SetQueryList(vec); + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_FAILED, WifiP2PHalInterface::GetInstance().P2pServiceAdd(info)); + vec.clear(); + vec.push_back("upnp 0 letusplaygames"); + vec.push_back("bonjour from china"); + info.SetQueryList(vec); + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().P2pServiceAdd(info)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, P2pServiceRemoveTest, TestSize.Level1) +{ + WifiP2pServiceInfo info; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().P2pServiceRemove(info)); + std::vector vec; + vec.push_back("upnp 0"); + info.SetQueryList(vec); + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_FAILED, WifiP2PHalInterface::GetInstance().P2pServiceRemove(info)); + vec.clear(); + vec.push_back("upnpp 1 letusplaygame"); + info.SetQueryList(vec); + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_FAILED, WifiP2PHalInterface::GetInstance().P2pServiceRemove(info)); + vec.clear(); + vec.push_back("upnp 0 letusplaygames"); + vec.push_back("bonjour from china"); + info.SetQueryList(vec); + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().P2pServiceRemove(info)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, FlushService_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().FlushService()); +} + +HWTEST_F(WifiP2pHalInterfaceTest, ReqServiceDiscovery_SUCCESS, TestSize.Level1) +{ + std::string macAddr; + std::vector tlvs; + std::string reqID; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_INVALID_PARAM, + WifiP2PHalInterface::GetInstance().ReqServiceDiscovery(macAddr, tlvs, reqID)); + macAddr = "00:00:00:00:00:00"; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_INVALID_PARAM, + WifiP2PHalInterface::GetInstance().ReqServiceDiscovery(macAddr, tlvs, reqID)); + tlvs.push_back('a'); + EXPECT_EQ( + WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().ReqServiceDiscovery(macAddr, tlvs, reqID)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, CancalReqServiceDiscovery_SUCCESS, TestSize.Level1) +{ + std::string id; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().CancelReqServiceDiscovery(id)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, StoreConfig_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SaveConfig()); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetRandomMacAddr_SUCCESS, TestSize.Level1) +{ + bool enable = false; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SetRandomMacAddr(enable)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetMiracastType_SUCCESS, TestSize.Level1) +{ + int type = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SetMiracastMode(type)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetPersistentReconnectTest, TestSize.Level1) +{ + int mode = 0; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SetPersistentReconnect(mode)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, RespServiceDiscoveryTest, TestSize.Level1) +{ + WifiP2pDevice device; + int frequency = 0; + int dialogToken = 0; + std::vector tlvs; + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_INVALID_PARAM, + WifiP2PHalInterface::GetInstance().RespServiceDiscovery(device, frequency, dialogToken, tlvs)); + tlvs.push_back(0x01); + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, + WifiP2PHalInterface::GetInstance().RespServiceDiscovery(device, frequency, dialogToken, tlvs)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, SetServiceDiscoveryExternalTest, TestSize.Level1) +{ + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SetServiceDiscoveryExternal(false)); +} + +HWTEST_F(WifiP2pHalInterfaceTest, P2pStop_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().StopP2p()); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.h new file mode 100644 index 000000000..f39f562b2 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.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_WIFI_P2P_HAL_INTERFACE_TEST_H +#define OHOS_WIFI_P2P_HAL_INTERFACE_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiP2pHalInterfaceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.cpp new file mode 100644 index 000000000..02e856fe0 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.cpp @@ -0,0 +1,363 @@ +/* + * 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 "wifi_sta_hal_interface_test.h" +#include "wifi_sta_hal_interface.h" +#include "wifi_supplicant_hal_interface.h" +#include "wifi_log.h" +#undef LOG_TAG +#define LOG_TAG "OHWIFI_IDLCLIENT_STA_TEST" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +void OnConnectChanged(int status, int networkId, const std::string &bssid) +{ + LOGD("OnConnectChanged status %d, networkid %d, bssid %s", status, networkId, bssid.c_str()); +} + +void OnWpaStateChanged(int status) +{ + LOGD("OnWpaStateChanged status %d", status); +} + +void OnWpaSsidWrongKey(int status) +{ + LOGD("OnWpaSsidWrongKey status %d", status); +} + +void OnWpsOverlap(int status) +{ + LOGD("OnWpsOverlap status %d", status); +} + +void OnWpsTimeOut(int status) +{ + LOGD("OnWpsTimeOut status %d", status); +} + +void OnScanNotify(int result) +{ + LOGD("OnScanNotify result %d", result); +} + +void WifiStaHalInterfaceTest::SetUpTestCase() +{ + WifiEventCallback callback; + callback.onConnectChanged = OnConnectChanged; + callback.onWpaStateChanged = OnWpaStateChanged; + callback.onWpaSsidWrongKey = OnWpaSsidWrongKey; + callback.onWpsOverlap = OnWpsOverlap; + callback.onWpsTimeOut = OnWpsTimeOut; + WifiStaHalInterface::GetInstance().RegisterStaEventCallback(callback); + + SupplicantEventCallback cbk; + cbk.onScanNotify = OnScanNotify; + WifiSupplicantHalInterface::GetInstance().RegisterSupplicantEventCallback(cbk); +} + +void WifiStaHalInterfaceTest::TearDownTestCase() +{ + WifiEventCallback callback; + WifiStaHalInterface::GetInstance().RegisterStaEventCallback(callback); + WifiSupplicantHalInterface::GetInstance().UnRegisterSupplicantEventCallback(); +} + +HWTEST_F(WifiStaHalInterfaceTest, StartWifiTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().StartWifi(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, ConnectTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().Connect(1); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, ReconnectTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().Reconnect(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, ReassociateTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().Reassociate(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, DisconnectTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().Disconnect(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, GetStaCapabilitiesTest, TestSize.Level1) +{ + unsigned int capabilities = 0; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().GetStaCapabilities(capabilities); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, GetStaDeviceMacAddressTest, TestSize.Level1) +{ + std::string mac; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().GetStaDeviceMacAddress(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, GetSupportFrequenciesTest, TestSize.Level1) +{ + std::vector freq; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().GetSupportFrequencies(0, freq); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, SetConnectMacAddrTest, TestSize.Level1) +{ + std::string mac = "abcdefghijklmn"; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().SetConnectMacAddr(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_INPUT_MAC_INVALID); + mac = "38:d2:69:ef:47:59"; + ret = WifiStaHalInterface::GetInstance().SetConnectMacAddr(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, SetScanMacAddressTest, TestSize.Level1) +{ + std::string mac = "abcdefghijklmn"; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().SetScanMacAddress(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_INPUT_MAC_INVALID); + mac = "38:d2:69:ef:47:59"; + ret = WifiStaHalInterface::GetInstance().SetScanMacAddress(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, DisconnectLastRoamingBssidTest, TestSize.Level1) +{ + std::string mac = "abcdefghijklmn"; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().DisconnectLastRoamingBssid(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_INPUT_MAC_INVALID); + mac = "38:d2:69:ef:47:59"; + ret = WifiStaHalInterface::GetInstance().DisconnectLastRoamingBssid(mac); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, GetSupportFeatureTest, TestSize.Level1) +{ + long feature = 0; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().GetSupportFeature(feature); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, SendRequestTest, TestSize.Level1) +{ + WifiStaRequest request; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().SendRequest(request); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, SetTxPowerTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().SetTxPower(0); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, ScanTest, TestSize.Level1) +{ + WifiScanParam scanParam; + scanParam.hiddenNetworkSsid.push_back("OHOS_testAp"); + scanParam.scanFreqs.push_back(2412); + scanParam.scanStyle = 0; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().Scan(scanParam); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, QueryScanInfosTest, TestSize.Level1) +{ + std::vector vec; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().QueryScanInfos(vec); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, GetNetworkListTest, TestSize.Level1) +{ + std::vector vec; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().GetNetworkList(vec); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, StartPnoScanTest, TestSize.Level1) +{ + WifiPnoScanParam scanParam; + scanParam.scanFreqs.push_back(2412); + scanParam.hiddenSsid.push_back("OHOS_testAp"); + scanParam.savedSsid.push_back("cmcc"); + WifiErrorNo ret = WifiStaHalInterface::GetInstance().StartPnoScan(scanParam); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, StopPnoScanTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().StopPnoScan(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, RemoveDeviceConfigTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().RemoveDevice(1); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, ClearDeviceConfigTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().ClearDeviceConfig(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, GetNextNetworkIdTest, TestSize.Level1) +{ + int id = 0; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().GetNextNetworkId(id); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, EnableNetworkTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().EnableNetwork(1); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, DisableNetworkTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().DisableNetwork(1); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, SetDeviceConfigTest, TestSize.Level1) +{ + WifiIdlDeviceConfig cfg; + cfg.psk = "1234567"; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().SetDeviceConfig(1, cfg); + EXPECT_TRUE(ret == WIFI_IDL_OPT_FAILED); + cfg.psk = "01234567890123456789012345678901234567890123456789012345678901234"; + ret = WifiStaHalInterface::GetInstance().SetDeviceConfig(1, cfg); + EXPECT_TRUE(ret == WIFI_IDL_OPT_FAILED); + cfg.psk = "12345678"; + ret = WifiStaHalInterface::GetInstance().SetDeviceConfig(1, cfg); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); + cfg.authAlgorithms = 8; + ret = WifiStaHalInterface::GetInstance().SetDeviceConfig(1, cfg); + EXPECT_TRUE(ret == WIFI_IDL_OPT_FAILED); + cfg.authAlgorithms = 7; + ret = WifiStaHalInterface::GetInstance().SetDeviceConfig(1, cfg); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); + cfg.ssid = "Honor"; + cfg.priority = 5; + cfg.scanSsid = 1; + cfg.wepKeyIdx = 2; + ret = WifiStaHalInterface::GetInstance().SetDeviceConfig(1, cfg); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, GetDeviceConfigTest, TestSize.Level1) +{ + WifiIdlGetDeviceConfig cfg; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().GetDeviceConfig(cfg); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, SaveDeviceConfigTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().SaveDeviceConfig(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, StartWpsPbcModeTest, TestSize.Level1) +{ + WifiIdlWpsConfig cfg; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().StartWpsPbcMode(cfg); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, StartWpsPinModeTest, TestSize.Level1) +{ + WifiIdlWpsConfig cfg; + int pinCode = 0; + cfg.pinCode = "0000"; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().StartWpsPinMode(cfg, pinCode); + EXPECT_TRUE(ret == WIFI_IDL_OPT_INVALID_PARAM); + cfg.pinCode = "12345678"; + ret = WifiStaHalInterface::GetInstance().StartWpsPinMode(cfg, pinCode); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, StopWpsTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().StopWps(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, GetRoamingCapabilitiesTest, TestSize.Level1) +{ + WifiIdlRoamCapability capability; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().GetRoamingCapabilities(capability); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, SetRoamConfigTest, TestSize.Level1) +{ + WifiIdlRoamConfig cfg; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().SetRoamConfig(cfg); + EXPECT_TRUE(ret == WIFI_IDL_OPT_FAILED); + cfg.blocklistBssids.push_back("00:00:00:00:00:00"); + cfg.trustlistBssids.push_back("10:00:00:00:00:00"); + ret = WifiStaHalInterface::GetInstance().SetRoamConfig(cfg); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, WpaAutoConnectTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().WpaAutoConnect(1); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); + ret = WifiStaHalInterface::GetInstance().WpaAutoConnect(0); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, WpaBlocklistClearTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().WpaBlocklistClear(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, GetConnectSignalInfoTest, TestSize.Level1) +{ + std::string endBssid; + WifiWpaSignalInfo info; + WifiErrorNo ret = WifiStaHalInterface::GetInstance().GetConnectSignalInfo(endBssid, info); + EXPECT_TRUE(ret == WIFI_IDL_OPT_INPUT_MAC_INVALID); + endBssid = "00:00:00:00:00:00"; + ret = WifiStaHalInterface::GetInstance().GetConnectSignalInfo(endBssid, info); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiStaHalInterfaceTest, StopWifiTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiStaHalInterface::GetInstance().StopWifi(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.h new file mode 100644 index 000000000..d9593a6b0 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.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_WIFI_STA_HAL_INTERFACE_TEST_H +#define OHOS_WIFI_STA_HAL_INTERFACE_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiStaHalInterfaceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.cpp new file mode 100644 index 000000000..94b177a14 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.cpp @@ -0,0 +1,89 @@ +/* + * 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 "wifi_supplicant_hal_interface_test.h" +#include "wifi_supplicant_hal_interface.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiSupplicantHalInterfaceTest, StartSupplicantTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiSupplicantHalInterface::GetInstance().StartSupplicant(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiSupplicantHalInterfaceTest, ConnectSupplicantTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiSupplicantHalInterface::GetInstance().ConnectSupplicant(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiSupplicantHalInterfaceTest, RequestToSupplicantTest, TestSize.Level1) +{ + std::string req = "abcd"; + WifiErrorNo ret = WifiSupplicantHalInterface::GetInstance().RequestToSupplicant(req); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiSupplicantHalInterfaceTest, RegisterSupplicantEventCallbackTest, TestSize.Level1) +{ + SupplicantEventCallback cbk; + WifiErrorNo ret = WifiSupplicantHalInterface::GetInstance().RegisterSupplicantEventCallback(cbk); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiSupplicantHalInterfaceTest, UnRegisterSupplicantEventCallbackTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiSupplicantHalInterface::GetInstance().UnRegisterSupplicantEventCallback(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiSupplicantHalInterfaceTest, SetPowerSaveTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiSupplicantHalInterface::GetInstance().SetPowerSave(true); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiSupplicantHalInterfaceTest, WpaSetCountryCodeTest, TestSize.Level1) +{ + std::string code; + WifiErrorNo ret = WifiSupplicantHalInterface::GetInstance().WpaSetCountryCode(code); + EXPECT_TRUE(ret != WIFI_IDL_OPT_OK); + code = "CN"; + ret = WifiSupplicantHalInterface::GetInstance().WpaSetCountryCode(code); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiSupplicantHalInterfaceTest, WpaGetCountryCodeTest, TestSize.Level1) +{ + std::string code; + WifiErrorNo ret = WifiSupplicantHalInterface::GetInstance().WpaGetCountryCode(code); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiSupplicantHalInterfaceTest, DisconnectSupplicantTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiSupplicantHalInterface::GetInstance().DisconnectSupplicant(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} + +HWTEST_F(WifiSupplicantHalInterfaceTest, StopSupplicantTest, TestSize.Level1) +{ + WifiErrorNo ret = WifiSupplicantHalInterface::GetInstance().StopSupplicant(); + EXPECT_TRUE(ret == WIFI_IDL_OPT_OK); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.h new file mode 100644 index 000000000..bfdbed2fd --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.h @@ -0,0 +1,37 @@ +/* + * 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_WIFI_SUPPLICANT_HAL_INTERFACE_TEST_H +#define OHOS_WIFI_SUPPLICANT_HAL_INTERFACE_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiSupplicantHalInterfaceTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/BUILD.gn new file mode 100644 index 000000000..6b020e7d1 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/BUILD.gn @@ -0,0 +1,110 @@ +# 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. + +import("//build/test.gni") +import("//foundation/appexecfwk/standard/appexecfwk.gni") + +################################################################################ + +SUBSYSTEM_DIR = "//foundation/communication/wifi" +module_output_path = "wifi_standard/manager_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/tests/wifi_standard/wifi_framework/wifi_manage/unittest", + ] +} + +ohos_unittest("manager_unittest") { + module_out_path = module_output_path + sources = [ + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/utils/wifi_common_event_helper.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.cpp", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.cpp", + "wifi_auth_center_test.cpp", + "wifi_config_center_test.cpp", + "wifi_internal_event_dispatcher_test.cpp", + "wifi_manage_test.cpp", + "wifi_manager_service_test.cpp", + "wifi_service_manager_test.cpp", + ] + + include_dirs = [ + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/include", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/utils", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/log", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/config", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_aware", + "$SUBSYSTEM_DIR/interfaces/innerkits/native_cpp/wifi_standard/interfaces", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "//utils/native/base/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//base/notification/ces_standard/cesfwk/innerkits/include", + "//base/notification/ces_standard/cesfwk/kits/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//foundation/aafwk/intent/interfaces/innerkits/base/include", + "//foundation/appexecfwk/adapter/interfaces/innerkits/appexecfwk_base/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + ] + + deps = [ + "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_client", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "//utils/native/base:utils", + ] + + ldflags = [ + "-fPIC", + "--coverage", + ] + + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + ] + configs = [ ":module_private_config" ] + + part_name = "wifi_standard" + subsystem_name = "communication" + testonly = true +} + +group("unittest") { + testonly = true + deps = [ ":manager_unittest" ] +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.cpp new file mode 100644 index 000000000..29498a58a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.cpp @@ -0,0 +1,203 @@ +/* + * 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 "wifi_auth_center_test.h" +#include "permission_def.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiAuthCenterTest, InitPermission_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(0, WifiAuthCenter::GetInstance().InitPermission(pid, uid)); +} + +static OHOS::Wifi::PermissionDef g_wifiPermissions[ARRAY_PERMISSION] = { + {"ohos.permission.GET_WIFI_INFO", USER_GRANT, NOT_RESTRICTED}, + {"ohos.permission.SET_WIFI_INFO", USER_GRANT, NOT_RESTRICTED}, + {"ohos.permission.GET_WIFI_CONFIG", USER_GRANT, NOT_RESTRICTED}, + {"ohos.permission.MANAGE_WIFI_CONNECTION", USER_GRANT, NOT_RESTRICTED}, + {"ohos.permission.MANAGE_WIFI_HOTSPOT", USER_GRANT, NOT_RESTRICTED}, + {"ohos.permission.MANAGE_ENHANCER_WIFI", USER_GRANT, NOT_RESTRICTED}, + {"ohos.permission.GET_WIFI_LOCAL_MAC", USER_GRANT, NOT_RESTRICTED}, + {"ohos.permission.LOCATION", USER_GRANT, NOT_RESTRICTED}, + {"ohos.permission.GET_P2P_DEVICE_LOCATION", USER_GRANT, NOT_RESTRICTED}, +}; + +HWTEST_F(WifiAuthCenterTest, ChangePermission_SUCCESS, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + EXPECT_EQ(0, WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckChangePermission_GRANTED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifySetWifiInfoPermission(pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckChangePermission_DENIED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {0}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifySetWifiInfoPermission(pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckAccessPermission_GRANTED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifyGetWifiInfoPermission(pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckAccessPermission_DENIED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {0}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifyGetWifiInfoPermission(pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckAccessScanInfosPermission_GRANTED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifyGetScanInfosPermission(pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckAccessScanInfosPermission_DENIED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {0}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifyGetScanInfosPermission(pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckGetLocalMacAddressPermission_GRANTED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifyGetWifiLocalMacPermission(pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckGetLocalMacAddressPermission_DENIED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {0}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifyGetWifiLocalMacPermission(pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckNetworkStackPermission_GRANTED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifyWifiConnectionPermission(pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckNetworkStackPermission_DENIED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {0}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifyWifiConnectionPermission(pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckNetworkStackOrSettingsPermission_GRANTED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifyWifiConnectionPermission(pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckNetworkStackOrSettingsPermission_DENIED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {0}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifyWifiConnectionPermission(pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckNetworkSettingsPermission_GRANTED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {1, 1, 1, 1, 1, 1, 1, 1, 1}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifyWifiConnectionPermission(pid, uid)); +} + +HWTEST_F(WifiAuthCenterTest, CheckNetworkSettingsPermission_DENIED, TestSize.Level1) +{ + std::map permissions; + int num[ARRAY_PERMISSION] = {0}; + for (int i = 0; i < ARRAY_PERMISSION; i++) { + permissions[g_wifiPermissions[i].name] = num[i]; + } + WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); + EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifyWifiConnectionPermission(pid, uid)); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.h new file mode 100644 index 000000000..fa5e87349 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.h @@ -0,0 +1,48 @@ +/* + * 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_WIFI_AUTH_CENTER_TEST_H +#define OHOS_WIFI_AUTH_CENTER_TEST_H + +#include +#include "wifi_auth_center.h" + +namespace OHOS { +namespace Wifi { +const int ARRAY_PERMISSION = 9; +const int PID_NUM_1001 = 1001; +const int UID_NUM_1001 = 1001; +class WifiAuthCenterTest : public testing::Test { +public: + static void SetUpTestCase() + { + WifiAuthCenter::GetInstance().Init(); + } + static void TearDownTestCase() + {} + virtual void SetUp() + { + pid = PID_NUM_1001; + uid = UID_NUM_1001; + } + virtual void TearDown() + {} + +public: + int pid; + int uid; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.cpp new file mode 100644 index 000000000..9ffa1fa6a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.cpp @@ -0,0 +1,586 @@ +/* + * 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 "wifi_config_center_test.h" +#include "wifi_global_func.h" +#include "wifi_internal_msg.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiConfigCenterTest, Init_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(0, WifiConfigCenter::GetInstance().Init()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetWifiMidState_SUCCESS, TestSize.Level1) +{ + WifiOprMidState state = OHOS::Wifi::WifiOprMidState::RUNNING; + WifiConfigCenter::GetInstance().SetWifiMidState(state); + EXPECT_EQ(state, WifiConfigCenter::GetInstance().GetWifiMidState()); +} + +HWTEST_F(WifiConfigCenterTest, SetWifiMidStateExp_SUCCESS, TestSize.Level1) +{ + WifiOprMidState cloState = OHOS::Wifi::WifiOprMidState::CLOSED; + WifiOprMidState runState = OHOS::Wifi::WifiOprMidState::RUNNING; + WifiConfigCenter::GetInstance().SetWifiMidState(cloState); + EXPECT_EQ(true, WifiConfigCenter::GetInstance().SetWifiMidState(cloState, runState)); +} + +HWTEST_F(WifiConfigCenterTest, SetWifiMidStateExp_FAILED, TestSize.Level1) +{ + WifiOprMidState cloState = OHOS::Wifi::WifiOprMidState::CLOSED; + WifiOprMidState runState = OHOS::Wifi::WifiOprMidState::RUNNING; + WifiConfigCenter::GetInstance().SetWifiMidState(cloState); + EXPECT_NE(true, WifiConfigCenter::GetInstance().SetWifiMidState(runState, cloState)); +} + +HWTEST_F(WifiConfigCenterTest, GetWifiStaIntervalTest, TestSize.Level1) +{ + WifiConfigCenter::GetInstance().SetWifiStaCloseTime(); + sleep(1); + double interval = WifiConfigCenter::GetInstance().GetWifiStaInterval(); + EXPECT_TRUE(interval >= 1000 && interval <= 2000); +} + +HWTEST_F(WifiConfigCenterTest, SetGetWifi_SUCCESS, TestSize.Level1) +{ + WifiOprMidState cloState = OHOS::Wifi::WifiOprMidState::CLOSED; + WifiSettings::GetInstance().SetWifiState(static_cast(cloState)); + EXPECT_EQ((int)cloState, WifiConfigCenter::GetInstance().GetWifiState()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetWifi_FAILED, TestSize.Level1) +{ + WifiOprMidState cloState = OHOS::Wifi::WifiOprMidState::CLOSED; + WifiOprMidState runState = OHOS::Wifi::WifiOprMidState::RUNNING; + WifiSettings::GetInstance().SetWifiState(static_cast(cloState)); + EXPECT_NE((int)runState, WifiConfigCenter::GetInstance().GetWifiState()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetScanAlwaysState_SUCCESS, TestSize.Level1) +{ + WifiSettings::GetInstance().SetScanAlwaysState(true); + EXPECT_EQ(true, WifiConfigCenter::GetInstance().IsScanAlwaysActive()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetScanAlwaysState_FAILED, TestSize.Level1) +{ + WifiSettings::GetInstance().SetScanAlwaysState(false); + EXPECT_NE(true, WifiConfigCenter::GetInstance().IsScanAlwaysActive()); +} + +HWTEST_F(WifiConfigCenterTest, GetScanInfoList_SUCCESS, TestSize.Level1) +{ + std::vector setInfo; + std::vector getInfo; + WifiScanInfo info1, info2; + info1.bssid = "asdfg"; + info2.bssid = "adsgds"; + setInfo.push_back(info1); + setInfo.push_back(info2); + getInfo.push_back(info1); + getInfo.push_back(info2); + WifiSettings::GetInstance().SaveScanInfoList(setInfo); + WifiConfigCenter::GetInstance().GetScanInfoList(getInfo); + EXPECT_EQ(setInfo.size(), getInfo.size()); + EXPECT_EQ(setInfo.at(0).bssid, getInfo.at(0).bssid); + EXPECT_EQ(setInfo.at(1).bssid, getInfo.at(1).bssid); +} + +HWTEST_F(WifiConfigCenterTest, GetScanInfoList_FAILED, TestSize.Level1) +{ + std::vector setInfo; + std::vector getInfo; + WifiScanInfo info1, info2; + info1.bssid = "asdfg"; + info2.bssid = "adsgds"; + setInfo.push_back(info1); + getInfo.push_back(info2); + WifiSettings::GetInstance().SaveScanInfoList(setInfo); + WifiConfigCenter::GetInstance().GetScanInfoList(getInfo); + EXPECT_EQ(setInfo.size(), getInfo.size()); + EXPECT_NE(setInfo.at(0).bssid, getInfo.at(0).bssid); +} + +HWTEST_F(WifiConfigCenterTest, GetScanControlInfo_SUCCESS, TestSize.Level1) +{ + ScanControlInfo setInfo, getInfo; + ScanIntervalMode scanIntervalMode; + int setInfoInterval, getInfoInterval; + scanIntervalMode.scanScene = SCAN_SCENE_ALL; + scanIntervalMode.scanMode = ScanMode::PNO_SCAN; + scanIntervalMode.isSingle = false; + scanIntervalMode.intervalMode = IntervalMode::INTERVAL_FIXED; + scanIntervalMode.interval = 20; + scanIntervalMode.count = 1; + setInfo.scanIntervalList.push_back(scanIntervalMode); + WifiConfigCenter::GetInstance().SetScanControlInfo(setInfo); + WifiConfigCenter::GetInstance().GetScanControlInfo(getInfo); + for (auto iter1 = setInfo.scanIntervalList.begin(); iter1 != setInfo.scanIntervalList.end(); iter1++) { + if (iter1->scanScene == SCAN_SCENE_ALL && iter1->scanMode == ScanMode::PNO_SCAN) { + setInfoInterval = iter1->interval; + } + } + for (auto iter2 = getInfo.scanIntervalList.begin(); iter2 != getInfo.scanIntervalList.end(); iter2++) { + if (iter2->scanScene == SCAN_SCENE_ALL && iter2->scanMode == ScanMode::PNO_SCAN) { + getInfoInterval = iter2->interval; + } + } + EXPECT_EQ(setInfoInterval, getInfoInterval); +} + +HWTEST_F(WifiConfigCenterTest, SetGetScanControlInfo_SUCCESS, TestSize.Level1) +{ + ScanControlInfo setInfo, getInfo; + ScanIntervalMode scanIntervalMode; + int setInfoInterval, getInfoInterval; + scanIntervalMode.scanScene = SCAN_SCENE_ALL; + scanIntervalMode.scanMode = ScanMode::PNO_SCAN; + scanIntervalMode.isSingle = false; + scanIntervalMode.intervalMode = IntervalMode::INTERVAL_FIXED; + scanIntervalMode.interval = 20; + scanIntervalMode.count = 1; + setInfo.scanIntervalList.push_back(scanIntervalMode); + WifiConfigCenter::GetInstance().SetScanControlInfo(setInfo); + WifiConfigCenter::GetInstance().GetScanControlInfo(getInfo); + for (auto iter1 = setInfo.scanIntervalList.begin(); iter1 != setInfo.scanIntervalList.end(); iter1++) { + if (iter1->scanScene == SCAN_SCENE_ALL && iter1->scanMode == ScanMode::PNO_SCAN) { + setInfoInterval = iter1->interval; + } + } + for (auto iter2 = getInfo.scanIntervalList.begin(); iter2 != getInfo.scanIntervalList.end(); iter2++) { + if (iter2->scanScene == SCAN_SCENE_ALL && iter2->scanMode == ScanMode::PNO_SCAN) { + getInfoInterval = iter2->interval; + } + } + EXPECT_EQ(setInfoInterval, getInfoInterval); +} + +HWTEST_F(WifiConfigCenterTest, GetIpInfo_SUCCESS, TestSize.Level1) +{ + IpInfo setInfo, getInfo; + setInfo.ipAddress = 100; + WifiSettings::GetInstance().SaveIpInfo(setInfo); + WifiConfigCenter::GetInstance().GetIpInfo(getInfo); + EXPECT_EQ(setInfo.ipAddress, getInfo.ipAddress); +} + +HWTEST_F(WifiConfigCenterTest, GetLinkedInfo_SUCCESS, TestSize.Level1) +{ + WifiLinkedInfo setInfo, getInfo; + setInfo.bssid = "sdfghf489375"; + WifiSettings::GetInstance().SaveLinkedInfo(setInfo); + WifiConfigCenter::GetInstance().GetLinkedInfo(getInfo); + EXPECT_EQ(setInfo.bssid, getInfo.bssid); +} + +HWTEST_F(WifiConfigCenterTest, SetGetMacAddress_SUCCESS, TestSize.Level1) +{ + std::string getMacAddr, setMacAddr; + setMacAddr = "192.168.1.2"; + WifiSettings::GetInstance().SetMacAddress(setMacAddr); + WifiConfigCenter::GetInstance().GetMacAddress(getMacAddr); + EXPECT_EQ(setMacAddr, getMacAddr); +} + +HWTEST_F(WifiConfigCenterTest, SetGetApMidState_SUCCESS, TestSize.Level1) +{ + WifiOprMidState setState; + setState = OHOS::Wifi::WifiOprMidState::OPENING; + WifiConfigCenter::GetInstance().SetApMidState(setState); + EXPECT_EQ(setState, WifiConfigCenter::GetInstance().GetApMidState()); +} + +HWTEST_F(WifiConfigCenterTest, SetApMidStateExp_SUCCESS, TestSize.Level1) +{ + WifiOprMidState setState, getState; + setState = OHOS::Wifi::WifiOprMidState::OPENING; + getState = OHOS::Wifi::WifiOprMidState::RUNNING; + WifiConfigCenter::GetInstance().SetApMidState(setState); + EXPECT_EQ(true, WifiConfigCenter::GetInstance().SetApMidState(setState, getState)); +} + +HWTEST_F(WifiConfigCenterTest, SetApMidStateExp_FAILED, TestSize.Level1) +{ + WifiOprMidState setState, getState; + setState = OHOS::Wifi::WifiOprMidState::OPENING; + getState = OHOS::Wifi::WifiOprMidState::RUNNING; + WifiConfigCenter::GetInstance().SetApMidState(setState); + EXPECT_NE(true, WifiConfigCenter::GetInstance().SetApMidState(getState, setState)); +} + +HWTEST_F(WifiConfigCenterTest, GetHotspotState_SUCCESS, TestSize.Level1) +{ + int state = 1; + WifiSettings::GetInstance().SetHotspotState(state); + EXPECT_EQ((int)state, WifiConfigCenter::GetInstance().GetHotspotState()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetHotspotConfig_SUCCESS, TestSize.Level1) +{ + HotspotConfig setConfig, getConfig; + setConfig.SetSsid("asdjhgfdksf"); + WifiConfigCenter::GetInstance().SetHotspotConfig(setConfig); + WifiConfigCenter::GetInstance().GetHotspotConfig(getConfig); + EXPECT_EQ(setConfig.GetSsid(), getConfig.GetSsid()); +} + +HWTEST_F(WifiConfigCenterTest, GetStationList_SUCCESS, TestSize.Level1) +{ + StationInfo info; + std::vector thisList, getList; + info.bssid = "24:6f:xx:xx:xx:11"; + thisList.push_back(info); + WifiSettings::GetInstance().ManageStation(info, MODE_ADD); + WifiConfigCenter::GetInstance().GetStationList(getList); + EXPECT_EQ(thisList.size(), getList.size()); + EXPECT_EQ(thisList.at(0).bssid, getList.at(0).bssid); +} + +HWTEST_F(WifiConfigCenterTest, GetBlockLists_SUCCESS, TestSize.Level1) +{ + StationInfo info; + std::vector thisList, getList; + info.bssid = "24:6f:xx:xx:xx:11"; + thisList.push_back(info); + WifiConfigCenter::GetInstance().AddBlockList(info); + WifiConfigCenter::GetInstance().GetBlockLists(getList); + EXPECT_EQ(thisList.size(), getList.size()); + EXPECT_EQ(thisList.at(0).bssid, getList.at(0).bssid); + EXPECT_EQ(0, WifiConfigCenter::GetInstance().DelBlockList(info)); +} + +HWTEST_F(WifiConfigCenterTest, AddDelBlockList_SUCCESS, TestSize.Level1) +{ + StationInfo info; + info.bssid = "24:6f:xx:xx:xx:11"; + EXPECT_EQ(0, WifiConfigCenter::GetInstance().AddBlockList(info)); + EXPECT_EQ(0, WifiConfigCenter::GetInstance().DelBlockList(info)); +} + +HWTEST_F(WifiConfigCenterTest, GetValidBands_SUCCESS, TestSize.Level1) +{ + std::vector bands; + EXPECT_EQ(0, WifiConfigCenter::GetInstance().GetValidBands(bands)); +} + +HWTEST_F(WifiConfigCenterTest, GetValidChannels_SUCCESS, TestSize.Level1) +{ + ChannelsTable channelsInfo; + EXPECT_EQ(0, WifiConfigCenter::GetInstance().GetValidChannels(channelsInfo)); +} + +HWTEST_F(WifiConfigCenterTest, SetGetScanMidState_SUCCESS, TestSize.Level1) +{ + WifiOprMidState state = OHOS::Wifi::WifiOprMidState::OPENING; + WifiConfigCenter::GetInstance().SetScanMidState(state); + EXPECT_EQ(state, WifiConfigCenter::GetInstance().GetScanMidState()); +} + +HWTEST_F(WifiConfigCenterTest, SetScanMidStateExp_SUCCESS, TestSize.Level1) +{ + WifiOprMidState state = OHOS::Wifi::WifiOprMidState::OPENING; + WifiConfigCenter::GetInstance().SetScanMidState(state); + EXPECT_EQ(true, WifiConfigCenter::GetInstance().SetScanMidState(state, OHOS::Wifi::WifiOprMidState::RUNNING)); +} + +HWTEST_F(WifiConfigCenterTest, GetSignalLevel_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ( + 0, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_1_2G - 1, static_cast(BandType::BAND_2GHZ))); + EXPECT_EQ( + 1, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_1_2G, static_cast(BandType::BAND_2GHZ))); + EXPECT_EQ( + 1, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_2_2G - 1, static_cast(BandType::BAND_2GHZ))); + EXPECT_EQ( + 2, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_2_2G, static_cast(BandType::BAND_2GHZ))); + EXPECT_EQ( + 2, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_3_2G - 1, static_cast(BandType::BAND_2GHZ))); + EXPECT_EQ( + 3, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_3_2G, static_cast(BandType::BAND_2GHZ))); + EXPECT_EQ( + 3, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_4_2G - 1, static_cast(BandType::BAND_2GHZ))); + EXPECT_EQ( + 4, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_4_2G, static_cast(BandType::BAND_2GHZ))); + EXPECT_EQ( + 0, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_1_5G - 1, static_cast(BandType::BAND_5GHZ))); + EXPECT_EQ( + 1, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_1_5G, static_cast(BandType::BAND_5GHZ))); + EXPECT_EQ( + 1, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_2_5G - 1, static_cast(BandType::BAND_5GHZ))); + EXPECT_EQ( + 2, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_2_5G, static_cast(BandType::BAND_5GHZ))); + EXPECT_EQ( + 2, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_3_5G - 1, static_cast(BandType::BAND_5GHZ))); + EXPECT_EQ( + 3, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_3_5G, static_cast(BandType::BAND_5GHZ))); + EXPECT_EQ( + 3, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_4_5G - 1, static_cast(BandType::BAND_5GHZ))); + EXPECT_EQ( + 4, WifiConfigCenter::GetInstance().GetSignalLevel(RSSI_LEVEL_4_5G, static_cast(BandType::BAND_5GHZ))); +} + +HWTEST_F(WifiConfigCenterTest, SetGetStaLastRunState_SUCCESS, TestSize.Level1) +{ + bool mode = true; + WifiConfigCenter::GetInstance().SetStaLastRunState(mode); + EXPECT_EQ(mode, WifiConfigCenter::GetInstance().GetStaLastRunState()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetScreenState_SUCCESS, TestSize.Level1) +{ + int mode = 1; + WifiConfigCenter::GetInstance().SetScreenState(mode); + EXPECT_EQ(mode, WifiConfigCenter::GetInstance().GetScreenState()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetAirplaneModeState_SUCCESS, TestSize.Level1) +{ + int mode = 1; + WifiConfigCenter::GetInstance().SetAirplaneModeState(mode); + EXPECT_EQ(mode, WifiConfigCenter::GetInstance().GetAirplaneModeState()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetAppRunningState_SUCCESS, TestSize.Level1) +{ + int mode = 1; + WifiConfigCenter::GetInstance().SetAppRunningState(mode); + EXPECT_EQ(mode, WifiConfigCenter::GetInstance().GetAppRunningState()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetPowerSavingModeState_SUCCESS, TestSize.Level1) +{ + int mode = 1; + WifiConfigCenter::GetInstance().SetPowerSavingModeState(mode); + EXPECT_EQ(mode, WifiConfigCenter::GetInstance().GetPowerSavingModeState()); +} + +HWTEST_F(WifiConfigCenterTest, SettingsInit_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(0, WifiSettings::GetInstance().Init()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetWifiStaCapabilities_SUCCESS, TestSize.Level1) +{ + int cap = 3; + EXPECT_EQ(0, WifiSettings::GetInstance().SetWifiStaCapabilities(cap)); + EXPECT_EQ(cap, WifiSettings::GetInstance().GetWifiStaCapabilities()); +} + +HWTEST_F(WifiConfigCenterTest, GetDeviceConfig_SUCCESS, TestSize.Level1) +{ + std::string bssid = "asdgdsklf"; + WifiDeviceConfig config, getConfig; + config.networkId = 15; + config.bssid = "asdgdsklf"; + WifiSettings::GetInstance().AddDeviceConfig(config); + WifiSettings::GetInstance().GetDeviceConfig(bssid, 1, getConfig); + EXPECT_EQ(0, WifiSettings::GetInstance().RemoveDevice(config.networkId)); + EXPECT_EQ(config.bssid, getConfig.bssid); + EXPECT_EQ(config.networkId, getConfig.networkId); +} + +HWTEST_F(WifiConfigCenterTest, GetHiddenDeviceConfig_SUCCESS, TestSize.Level1) +{ + WifiDeviceConfig config1, config2; + config1.networkId = 15; + config1.bssid = "asdgdsklf"; + config1.hiddenSSID = true; + config2.networkId = 16; + config2.bssid = "asdgdssfklf"; + config2.hiddenSSID = false; + std::vector configArr; + WifiSettings::GetInstance().AddDeviceConfig(config1); + WifiSettings::GetInstance().AddDeviceConfig(config2); + WifiSettings::GetInstance().GetHiddenDeviceConfig(configArr); + EXPECT_EQ(0, WifiSettings::GetInstance().RemoveDevice(config1.networkId)); + EXPECT_EQ(0, WifiSettings::GetInstance().RemoveDevice(config2.networkId)); + EXPECT_TRUE(1 == configArr.size()); + EXPECT_EQ(config1.networkId, configArr.at(0).networkId); + EXPECT_EQ(config1.bssid, configArr.at(0).bssid); + EXPECT_EQ(config1.hiddenSSID, configArr.at(0).hiddenSSID); +} + +HWTEST_F(WifiConfigCenterTest, SyncDeviceConfig_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(0, WifiSettings::GetInstance().SyncDeviceConfig()); +} + +HWTEST_F(WifiConfigCenterTest, ReloadDeviceConfig_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(0, WifiSettings::GetInstance().ReloadDeviceConfig()); +} + +HWTEST_F(WifiConfigCenterTest, SyncHotspotConfig_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(0, WifiSettings::GetInstance().SyncHotspotConfig()); +} + +HWTEST_F(WifiConfigCenterTest, ClearStationList_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(0, WifiSettings::GetInstance().ClearStationList()); +} + +HWTEST_F(WifiConfigCenterTest, SyncBlockList_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(0, WifiSettings::GetInstance().SyncBlockList()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetValidChannels_SUCCESS, TestSize.Level1) +{ + ChannelsTable setInfos, getInfos; + std::vector chan2G = {1324, 32, 324, 423, 43214}; + std::vector chan5G = {5435, 4353, 5432, 5432}; + chan2G.push_back(2145); + setInfos[BandType::BAND_2GHZ] = chan2G; + setInfos[BandType::BAND_5GHZ] = chan5G; + EXPECT_EQ(0, WifiSettings::GetInstance().SetValidChannels(setInfos)); + EXPECT_EQ(0, WifiSettings::GetInstance().GetValidChannels(getInfos)); + EXPECT_EQ(setInfos.size(), getInfos.size()); + EXPECT_EQ(setInfos.at(BandType::BAND_2GHZ).size(), getInfos.at(BandType::BAND_2GHZ).size()); + EXPECT_EQ(setInfos.at(BandType::BAND_5GHZ).size(), getInfos.at(BandType::BAND_5GHZ).size()); +} + +HWTEST_F(WifiConfigCenterTest, ClearValidChannels_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(0, WifiSettings::GetInstance().ClearValidChannels()); +} + +HWTEST_F(WifiConfigCenterTest, GetApMaxConnNum_SUCCESS, TestSize.Level1) +{ + WifiSettings::GetInstance().Init(); + EXPECT_EQ(MAX_AP_CONN, WifiSettings::GetInstance().GetApMaxConnNum()); +} + +HWTEST_F(WifiConfigCenterTest, EnableNetwork_SUCCESS, TestSize.Level1) +{ + int networkId = 15; + bool disableOthers = true; + EXPECT_EQ(true, WifiSettings::GetInstance().EnableNetwork(networkId, disableOthers)); +} + +HWTEST_F(WifiConfigCenterTest, SetGetUserLastSelectedNetworkId_SUCCESS, TestSize.Level1) +{ + int networkId = 15; + WifiSettings::GetInstance().SetUserLastSelectedNetworkId(networkId); + EXPECT_EQ(networkId, WifiSettings::GetInstance().GetUserLastSelectedNetworkId()); +} + +HWTEST_F(WifiConfigCenterTest, SyncWifiConfig_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(0, WifiSettings::GetInstance().SyncWifiConfig()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetDhcpIpType_SUCCESS, TestSize.Level1) +{ + int stat = 1234; + EXPECT_EQ(0, WifiSettings::GetInstance().SetDhcpIpType(stat)); + EXPECT_EQ(stat, WifiSettings::GetInstance().GetDhcpIpType()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetScoretacticsScoreSlope_SUCCESS, TestSize.Level1) +{ + int stat = 134; + EXPECT_EQ(0, WifiSettings::GetInstance().SetScoretacticsScoreSlope(stat)); + EXPECT_EQ(stat, WifiSettings::GetInstance().GetScoretacticsScoreSlope()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetScoretacticsSameBssidScore_SUCCESS, TestSize.Level1) +{ + bool stat = true; + EXPECT_EQ(0, WifiSettings::GetInstance().SetScoretacticsSameBssidScore(stat)); + EXPECT_EQ(stat, WifiSettings::GetInstance().GetScoretacticsSameBssidScore()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetScoretacticsSameNetworkScore_SUCCESS, TestSize.Level1) +{ + int stat = 1234; + EXPECT_EQ(0, WifiSettings::GetInstance().SetScoretacticsSameNetworkScore(stat)); + EXPECT_EQ(stat, WifiSettings::GetInstance().GetScoretacticsSameNetworkScore()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetScoretacticsFrequency5GHzScore_SUCCESS, TestSize.Level1) +{ + int stat = 234; + EXPECT_EQ(0, WifiSettings::GetInstance().SetScoretacticsFrequency5GHzScore(stat)); + EXPECT_EQ(stat, WifiSettings::GetInstance().GetScoretacticsFrequency5GHzScore()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetScoretacticsLastSelectionScore_SUCCESS, TestSize.Level1) +{ + int stat = 1234; + EXPECT_EQ(0, WifiSettings::GetInstance().SetScoretacticsLastSelectionScore(stat)); + EXPECT_EQ(stat, WifiSettings::GetInstance().GetScoretacticsLastSelectionScore()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetScoretacticsSecurityScore_SUCCESS, TestSize.Level1) +{ + int stat = 123; + EXPECT_EQ(0, WifiSettings::GetInstance().SetScoretacticsSecurityScore(stat)); + EXPECT_EQ(stat, WifiSettings::GetInstance().GetScoretacticsSecurityScore()); +} + +HWTEST_F(WifiConfigCenterTest, SetGetSavedDeviceAppraisalPriority_SUCCESS, TestSize.Level1) +{ + int stat = 532; + EXPECT_EQ(0, WifiSettings::GetInstance().SetSavedDeviceAppraisalPriority(stat)); + EXPECT_EQ(stat, WifiSettings::GetInstance().GetSavedDeviceAppraisalPriority()); +} + +HWTEST_F(WifiConfigCenterTest, GetP2pStateTest, TestSize.Level1) +{ + WifiSettings::GetInstance().SetP2pState(1); + EXPECT_TRUE(WifiConfigCenter::GetInstance().GetP2pState() == 1); +} + +HWTEST_F(WifiConfigCenterTest, SetGetP2pMidState_SUCCESS, TestSize.Level1) +{ + WifiOprMidState state = WifiOprMidState::RUNNING; + WifiConfigCenter::GetInstance().SetP2pMidState(state); + EXPECT_EQ(state, WifiConfigCenter::GetInstance().GetP2pMidState()); +} + +HWTEST_F(WifiConfigCenterTest, SetP2pMidStateExp_SUCCESS, TestSize.Level1) +{ + WifiOprMidState cloState = WifiOprMidState::CLOSED; + WifiOprMidState runState = WifiOprMidState::RUNNING; + WifiConfigCenter::GetInstance().SetP2pMidState(cloState); + EXPECT_EQ(true, WifiConfigCenter::GetInstance().SetP2pMidState(cloState, runState)); +} + +HWTEST_F(WifiConfigCenterTest, SetP2pMidStateExp_FAILED, TestSize.Level1) +{ + WifiOprMidState cloState = WifiOprMidState::CLOSED; + WifiOprMidState runState = WifiOprMidState::RUNNING; + WifiConfigCenter::GetInstance().SetP2pMidState(cloState); + EXPECT_NE(true, WifiConfigCenter::GetInstance().SetP2pMidState(runState, cloState)); +} + +HWTEST_F(WifiConfigCenterTest, GetCanOpenStaWhenAirplaneModeTest, TestSize.Level1) +{ + EXPECT_TRUE(WifiConfigCenter::GetInstance().GetCanOpenStaWhenAirplaneMode() == false); +} + +HWTEST_F(WifiConfigCenterTest, SetWifiStateWhenAirplaneModeTest, TestSize.Level1) +{ + WifiConfigCenter::GetInstance().SetWifiStateWhenAirplaneMode(false); + EXPECT_TRUE(WifiConfigCenter::GetInstance().GetWifiStateWhenAirplaneMode() == false); + WifiConfigCenter::GetInstance().SetWifiStateWhenAirplaneMode(true); + EXPECT_TRUE(WifiConfigCenter::GetInstance().GetWifiStateWhenAirplaneMode() == true); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.h new file mode 100644 index 000000000..f303d4851 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.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_WIFI_CONFIG_CENTER_TEST_H +#define OHOS_WIFI_CONFIG_CENTER_TEST_H +#include + +#include "wifi_config_center.h" + +namespace OHOS { +namespace Wifi { +class WifiConfigCenterTest : public testing::Test { +public: + static void SetUpTestCase() + { + WifiConfigCenter::GetInstance().Init(); + WifiSettings::GetInstance().Init(); + } + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.cpp new file mode 100644 index 000000000..77fa8d06a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.cpp @@ -0,0 +1,58 @@ +/* + * 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 "wifi_internal_event_dispatcher_test.h" +#include "wifi_internal_event_dispatcher.h" +#include "permission_def.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiInternalEventDispatcherTest, ThreadTest, TestSize.Level1) +{ + WifiEventCallbackMsg msg; + msg.msgCode = WIFI_CBK_MSG_STATE_CHANGE; + EXPECT_EQ(0, WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(msg)); + sleep(1); + msg.msgCode = WIFI_CBK_MSG_CONNECTION_CHANGE; + EXPECT_EQ(0, WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(msg)); + sleep(1); + msg.msgCode = WIFI_CBK_MSG_SCAN_STATE_CHANGE; + EXPECT_EQ(0, WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(msg)); + sleep(1); + msg.msgCode = WIFI_CBK_MSG_RSSI_CHANGE; + EXPECT_EQ(0, WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(msg)); + sleep(1); + msg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE; + EXPECT_EQ(0, WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(msg)); + sleep(1); + msg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_JOIN; + EXPECT_EQ(0, WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(msg)); + sleep(1); + msg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_LEAVE; + EXPECT_EQ(0, WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(msg)); + sleep(1); + msg.msgCode = WIFI_CBK_MSG_STREAM_DIRECTION; + EXPECT_EQ(0, WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(msg)); + sleep(1); + msg.msgCode = WIFI_CBK_MSG_WPS_STATE_CHANGE; + EXPECT_EQ(0, WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(msg)); + sleep(1); + msg.msgCode = 0xffff; + EXPECT_EQ(0, WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(msg)); + sleep(2); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.h new file mode 100644 index 000000000..73faf114e --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.h @@ -0,0 +1,37 @@ +/* + * 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_WIFI_INTERNAL_EVENT_DISPATCHER_TEST_H +#define OHOS_WIFI_INTERNAL_EVENT_DISPATCHER_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiInternalEventDispatcherTest : public testing::Test { +public: + static void SetupTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manage_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manage_test.cpp new file mode 100644 index 000000000..e7867ae26 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manage_test.cpp @@ -0,0 +1,21 @@ +/* + * 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 + +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.cpp new file mode 100644 index 000000000..7afe40a4b --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.cpp @@ -0,0 +1,241 @@ +/* + * 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 "wifi_manager_service_test.h" +#include "wifi_config_center.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiManagerServiceTest, StaOpenResTest, TestSize.Level1) +{ + StaServiceCallback cbk = WifiManager::GetInstance().GetStaCallback(); + ASSERT_TRUE(cbk.OnStaOpenRes != nullptr); + cbk.OnStaOpenRes(OperateResState::OPEN_WIFI_FAILED); + cbk.OnStaOpenRes(OperateResState::OPEN_WIFI_OPENING); + cbk.OnStaOpenRes(OperateResState::OPEN_WIFI_SUCCEED); + WifiSettings::GetInstance().SetAirplaneModeState(1); + cbk.OnStaOpenRes(OperateResState::OPEN_WIFI_SUCCEED); + cbk.OnStaOpenRes(OperateResState::OPEN_WIFI_DISABLED); + sleep(2); +} + +HWTEST_F(WifiManagerServiceTest, StaCloseResTest, TestSize.Level1) +{ + StaServiceCallback cbk = WifiManager::GetInstance().GetStaCallback(); + ASSERT_TRUE(cbk.OnStaOpenRes != nullptr); + ASSERT_TRUE(cbk.OnStaCloseRes != nullptr); + cbk.OnStaOpenRes(OperateResState::OPEN_WIFI_SUCCEED); + cbk.OnStaCloseRes(OperateResState::CLOSE_WIFI_FAILED); + cbk.OnStaCloseRes(OperateResState::CLOSE_WIFI_CLOSING); + cbk.OnStaCloseRes(OperateResState::CLOSE_WIFI_SUCCEED); + WifiSettings::GetInstance().SetAirplaneModeState(1); + WifiConfigCenter::GetInstance().SetP2pMidState(WifiOprMidState::RUNNING); + cbk.OnStaCloseRes(OperateResState::CLOSE_WIFI_SUCCEED); + sleep(2); +} + +HWTEST_F(WifiManagerServiceTest, StaConnChangedResTest, TestSize.Level1) +{ + StaServiceCallback cbk = WifiManager::GetInstance().GetStaCallback(); + ASSERT_TRUE(cbk.OnStaConnChanged != nullptr); + + WifiLinkedInfo info; + cbk.OnStaConnChanged(OperateResState::CONNECT_CONNECTING, info); + cbk.OnStaConnChanged(OperateResState::CONNECT_AP_CONNECTED, info); + cbk.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECTING, info); + cbk.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECTED, info); + sleep(2); +} + +HWTEST_F(WifiManagerServiceTest, StaWpsChangedResTest, TestSize.Level1) +{ + StaServiceCallback cbk = WifiManager::GetInstance().GetStaCallback(); + ASSERT_TRUE(cbk.OnWpsChanged != nullptr); + cbk.OnWpsChanged(WpsStartState::START_PIN_SUCCEED, 1); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, DealStreamChangedTest, TestSize.Level1) +{ + StaServiceCallback cbk = WifiManager::GetInstance().GetStaCallback(); + ASSERT_TRUE(cbk.OnStaStreamChanged != nullptr); + + cbk.OnStaStreamChanged(StreamDirection::STREAM_DIRECTION_UP); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, DealRssiChangedTest, TestSize.Level1) +{ + StaServiceCallback cbk = WifiManager::GetInstance().GetStaCallback(); + ASSERT_TRUE(cbk.OnStaRssiLevelChanged != nullptr); + + cbk.OnStaRssiLevelChanged(1); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, ScanOpenResTest, TestSize.Level1) +{ + IScanSerivceCallbacks cbk = WifiManager::GetInstance().GetScanCallback(); + ASSERT_TRUE(cbk.OnScanStartEvent != nullptr); + + cbk.OnScanStartEvent(); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, ScanCloseResTest, TestSize.Level1) +{ + IScanSerivceCallbacks cbk = WifiManager::GetInstance().GetScanCallback(); + ASSERT_TRUE(cbk.OnScanStopEvent != nullptr); + + cbk.OnScanStopEvent(); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, ScanFinishedResTest, TestSize.Level1) +{ + IScanSerivceCallbacks cbk = WifiManager::GetInstance().GetScanCallback(); + ASSERT_TRUE(cbk.OnScanFinishEvent != nullptr); + + cbk.OnScanFinishEvent(1); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, ScanInfoNotifyResTest, TestSize.Level1) +{ + IScanSerivceCallbacks cbk = WifiManager::GetInstance().GetScanCallback(); + ASSERT_TRUE(cbk.OnScanInfoEvent != nullptr); + + std::vector results; + cbk.OnScanInfoEvent(results); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, ApStateResTest, TestSize.Level1) +{ + IApServiceCallbacks cbk = WifiManager::GetInstance().GetApCallback(); + ASSERT_TRUE(cbk.OnApStateChangedEvent != nullptr); + + cbk.OnApStateChangedEvent(ApState::AP_STATE_STARTING); + cbk.OnApStateChangedEvent(ApState::AP_STATE_STARTED); + cbk.OnApStateChangedEvent(ApState::AP_STATE_CLOSING); + cbk.OnApStateChangedEvent(ApState::AP_STATE_CLOSED); + cbk.OnApStateChangedEvent(ApState::AP_STATE_IDLE); + cbk.OnApStateChangedEvent(ApState::AP_STATE_NONE); + sleep(2); +} + +HWTEST_F(WifiManagerServiceTest, ApJoinResTest, TestSize.Level1) +{ + IApServiceCallbacks cbk = WifiManager::GetInstance().GetApCallback(); + ASSERT_TRUE(cbk.OnHotspotStaJoinEvent != nullptr); + + StationInfo info; + cbk.OnHotspotStaJoinEvent(info); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, ApLeaveResTest, TestSize.Level1) +{ + IApServiceCallbacks cbk = WifiManager::GetInstance().GetApCallback(); + ASSERT_TRUE(cbk.OnHotspotStaLeaveEvent != nullptr); + + StationInfo info; + cbk.OnHotspotStaLeaveEvent(info); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, P2pStateChangeTest, TestSize.Level1) +{ + IP2pServiceCallbacks cbk = WifiManager::GetInstance().GetP2pCallback(); + ASSERT_TRUE(cbk.OnP2pStateChangedEvent != nullptr); + + cbk.OnP2pStateChangedEvent(P2pState::P2P_STATE_STARTING); + cbk.OnP2pStateChangedEvent(P2pState::P2P_STATE_STARTED); + cbk.OnP2pStateChangedEvent(P2pState::P2P_STATE_CLOSING); + cbk.OnP2pStateChangedEvent(P2pState::P2P_STATE_CLOSED); + cbk.OnP2pStateChangedEvent(P2pState::P2P_STATE_IDLE); + cbk.OnP2pStateChangedEvent(P2pState::P2P_STATE_NONE); + sleep(2); +} + +HWTEST_F(WifiManagerServiceTest, P2pPeersChangeTest, TestSize.Level1) +{ + IP2pServiceCallbacks cbk = WifiManager::GetInstance().GetP2pCallback(); + ASSERT_TRUE(cbk.OnP2pPeersChangedEvent != nullptr); + + std::vector peers; + cbk.OnP2pPeersChangedEvent(peers); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, P2pServiceChangeTest, TestSize.Level1) +{ + IP2pServiceCallbacks cbk = WifiManager::GetInstance().GetP2pCallback(); + ASSERT_TRUE(cbk.OnP2pServicesChangedEvent != nullptr); + + std::vector services; + cbk.OnP2pServicesChangedEvent(services); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, P2pConnectionChangeTest, TestSize.Level1) +{ + IP2pServiceCallbacks cbk = WifiManager::GetInstance().GetP2pCallback(); + ASSERT_TRUE(cbk.OnP2pConnectionChangedEvent != nullptr); + + WifiP2pInfo info; + cbk.OnP2pConnectionChangedEvent(info); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, P2pDeviceChangeTest, TestSize.Level1) +{ + IP2pServiceCallbacks cbk = WifiManager::GetInstance().GetP2pCallback(); + ASSERT_TRUE(cbk.OnP2pThisDeviceChangedEvent != nullptr); + + WifiP2pDevice info; + cbk.OnP2pThisDeviceChangedEvent(info); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, P2pDiscoveryChangeTest, TestSize.Level1) +{ + IP2pServiceCallbacks cbk = WifiManager::GetInstance().GetP2pCallback(); + ASSERT_TRUE(cbk.OnP2pDiscoveryChangedEvent != nullptr); + + cbk.OnP2pDiscoveryChangedEvent(true); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, P2pGroupsChangeTest, TestSize.Level1) +{ + IP2pServiceCallbacks cbk = WifiManager::GetInstance().GetP2pCallback(); + ASSERT_TRUE(cbk.OnP2pGroupsChangedEvent != nullptr); + + cbk.OnP2pGroupsChangedEvent(); + sleep(1); +} + +HWTEST_F(WifiManagerServiceTest, P2pActionChangeTest, TestSize.Level1) +{ + IP2pServiceCallbacks cbk = WifiManager::GetInstance().GetP2pCallback(); + ASSERT_TRUE(cbk.OnP2pActionResultEvent != nullptr); + + cbk.OnP2pActionResultEvent(P2pActionCallback::DiscoverDevices, WIFI_OPT_SUCCESS); + sleep(1); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.h new file mode 100644 index 000000000..295bae0af --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.h @@ -0,0 +1,42 @@ +/* + * 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_WIFI_MANAGER_SERVICE_TEST_H +#define OHOS_WIFI_MANAGER_SERVICE_TEST_H + +#include +#include "wifi_manager.h" + +namespace OHOS { +namespace Wifi { +class WifiManagerServiceTest : public testing::Test { +public: + static void SetupTestCase() + { + WifiManager::GetInstance().Init(); + } + static void TearDownTestCase() + { + WifiManager::GetInstance().Exit(); + } + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.cpp new file mode 100644 index 000000000..6a54deee5 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.cpp @@ -0,0 +1,434 @@ +/* + * 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 "wifi_mock_p2p_service.h" +#include "wifi_log.h" + +namespace OHOS { +namespace Wifi { +ErrCode WifiMockP2pService::EnableP2p() +{ + LOGI("Mock_p2p:EnableP2p"); + bool state = true; + mCallback.OnP2pStateChangedEvent(state); + WifiP2pDevice device; + device.SetDeviceName("DeviceName1"); + device.SetDeviceAddress("DeviceAddress1"); + device.SetPrimaryDeviceType("PrimaryDeviceType1"); + device.SetSecondaryDeviceType("SecondaryDeviceType1"); + device.SetP2pDeviceStatus(P2pDeviceStatus::PDS_INVITED); + + WifiP2pWfdInfo wfdInfo; + wfdInfo.SetWfdEnabled(false); + wfdInfo.SetDeviceInfo(TEST_ONE_THOUSAND); + wfdInfo.SetCtrlPort(TEST_ONE_THOUSAND); + wfdInfo.SetMaxThroughput(TEST_ONE_THOUSAND); + device.SetWfdInfo(wfdInfo); + + device.SetWpsConfigMethod(TEST_ONE_THOUSAND); + device.SetDeviceCapabilitys(TEST_ONE_THOUSAND); + device.SetGroupCapabilitys(TEST_ONE_THOUSAND); + mCallback.OnP2pThisDeviceChangedEvent(device); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::DisableP2p() +{ + LOGI("Mock_p2p:DisableP2p"); + bool state = false; + mCallback.OnP2pStateChangedEvent(state); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::DiscoverDevices() +{ + LOGI("Mock_p2p:DiscoverDevices"); + std::vector devices; + WifiP2pDevice device1; + device1.SetDeviceName("DeviceName1"); + device1.SetDeviceAddress("DeviceAddress1"); + device1.SetPrimaryDeviceType("PrimaryDeviceType1"); + device1.SetSecondaryDeviceType("SecondaryDeviceType1"); + device1.SetP2pDeviceStatus(P2pDeviceStatus::PDS_INVITED); + WifiP2pWfdInfo wfdInfo1; + wfdInfo1.SetWfdEnabled(false); + wfdInfo1.SetDeviceInfo(TEST_ONE_THOUSAND); + wfdInfo1.SetCtrlPort(TEST_ONE_THOUSAND); + wfdInfo1.SetMaxThroughput(TEST_ONE_THOUSAND); + device1.SetWfdInfo(wfdInfo1); + device1.SetWpsConfigMethod(TEST_ONE_THOUSAND); + device1.SetDeviceCapabilitys(TEST_ONE_THOUSAND); + device1.SetGroupCapabilitys(TEST_ONE_THOUSAND); + devices.push_back(device1); + WifiP2pDevice device2; + device2.SetDeviceName("DeviceName2"); + device2.SetDeviceAddress("DeviceAddress2"); + device2.SetPrimaryDeviceType("PrimaryDeviceType2"); + device2.SetSecondaryDeviceType("SecondaryDeviceType2"); + device2.SetP2pDeviceStatus(P2pDeviceStatus::PDS_INVITED); + WifiP2pWfdInfo wfdInfo2; + wfdInfo2.SetWfdEnabled(false); + wfdInfo2.SetDeviceInfo(TEST_TWO_THOUSAND); + wfdInfo2.SetCtrlPort(TEST_TWO_THOUSAND); + wfdInfo2.SetMaxThroughput(TEST_TWO_THOUSAND); + device2.SetWfdInfo(wfdInfo2); + device2.SetWpsConfigMethod(TEST_TWO_THOUSAND); + device2.SetDeviceCapabilitys(TEST_TWO_THOUSAND); + device2.SetGroupCapabilitys(TEST_TWO_THOUSAND); + devices.push_back(device2); + + mCallback.OnP2pPeersChangedEvent(devices); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::StopDiscoverDevices() +{ + LOGI("Mock_p2p:StopDiscoverDevices"); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::DiscoverServices() +{ + LOGI("Mock_p2p:DiscoverServices"); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::StopDiscoverServices() +{ + LOGI("Mock_p2p:StopDiscoverServices"); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::RequestService(const WifiP2pDevice &device, const WifiP2pServiceRequest &request) +{ + LOGI("Mock_p2p:RequestService"); + LOGI("request.GetProtocolType() = %d", static_cast(request.GetProtocolType())); + LOGI("request.GetTransactionId() = %d", request.GetTransactionId()); + std::vector query = request.GetQuery(); + for (auto it = query.begin(); it != query.end(); it++) { + LOGI("vec_query = %d", *it); + } + LOGI("device.GetDeviceName() = %s", device.GetDeviceName().c_str()); + LOGI("device.GetDeviceAddress() = %s", device.GetDeviceAddress().c_str()); + LOGI("device.GetPrimaryDeviceType() = %s", device.GetPrimaryDeviceType().c_str()); + LOGI("device.GetSecondaryDeviceType() = %s", device.GetSecondaryDeviceType().c_str()); + LOGI("device.GetP2pDeviceStatus() = %d", static_cast(device.GetP2pDeviceStatus())); + + LOGI("device.GetWfdInfo().GetWfdEnabled() = %s", device.GetWfdInfo().GetWfdEnabled() ? "true" : "false"); + LOGI("device.GetWfdInfo().GetDeviceInfo() = %d", device.GetWfdInfo().GetDeviceInfo()); + LOGI("device.GetWfdInfo().GetCtrlPort() = %d", device.GetWfdInfo().GetCtrlPort()); + LOGI("device.GetWfdInfo().GetMaxThroughput() = %d", device.GetWfdInfo().GetMaxThroughput()); + + LOGI("device.GetWpsConfigMethod() = %d", device.GetWpsConfigMethod()); + LOGI("device.GetDeviceCapabilitys() = %d", device.GetDeviceCapabilitys()); + LOGI("device.GetGroupCapabilitys() = %d", device.GetGroupCapabilitys()); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::PutLocalP2pService(const WifiP2pServiceInfo &srvInfo) +{ + LOGI("Mock_p2p:PutLocalP2pService"); + std::vector services; + LOGI("srvInfo.GetServiceName() = %s", srvInfo.GetServiceName().c_str()); + LOGI("srvInfo.GetDeviceAddress() = %s", srvInfo.GetDeviceAddress().c_str()); + LOGI("srvInfo.GetServicerProtocolType() = %d", static_cast(srvInfo.GetServicerProtocolType())); + services.emplace_back(srvInfo); + mCallback.OnP2pServicesChangedEvent(services); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo) +{ + LOGI("Mock_p2p:DeleteLocalP2pService"); + std::vector services; + LOGI("srvInfo.GetServiceName() = %s", srvInfo.GetServiceName().c_str()); + LOGI("srvInfo.GetDeviceAddress() = %s", srvInfo.GetDeviceAddress().c_str()); + LOGI("srvInfo.GetServicerProtocolType() = %d", static_cast(srvInfo.GetServicerProtocolType())); + services.emplace_back(srvInfo); + mCallback.OnP2pServicesChangedEvent(services); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::StartP2pListen(int period, int interval) +{ + LOGI("Mock_p2p:StartP2pListen"); + LOGI("period = %d interval = %d\n", period, interval); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::StopP2pListen() +{ + LOGI("Mock_p2p:StopP2pListen"); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::FormGroup(const WifiP2pConfig &config) +{ + LOGI("Mock_p2p:FormGroup"); + LOGI("config.GetDeviceAddress() = %s\n", config.GetDeviceAddress().c_str()); + LOGI("config.GetGoBand() = %d\n", config.GetGoBand()); + LOGI("config.GetNetId() = %d\n", config.GetNetId()); + LOGI("config.GetPassphrase() = %s\n", config.GetPassphrase().c_str()); + LOGI("config.GetGroupOwnerIntent() = %d\n", config.GetGroupOwnerIntent()); + LOGI("config.GetGroupName() = %s\n", config.GetGroupName().c_str()); + + LOGI("config.GetWpsInfo().GetWpsMethod() = %d\n", static_cast(config.GetWpsInfo().GetWpsMethod())); + LOGI("config.GetWpsInfo().GetBssid() = %s\n", config.GetWpsInfo().GetBssid().c_str()); + LOGI("config.GetWpsInfo().GetPin() = %s\n", config.GetWpsInfo().GetPin().c_str()); + + mCallback.OnP2pGroupsChangedEvent(); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::RemoveGroup() +{ + LOGI("Mock_p2p:RemoveGroup"); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::DeleteGroup(const WifiP2pGroupInfo &group) +{ + LOGI("Mock_p2p:DeleteGroup"); + LOGI("group.IsGroupOwner() = %s\n", group.IsGroupOwner() ? "true" : "false"); + + LOGI("group.GetOwner().GetDeviceName() = %s\n", group.GetOwner().GetDeviceName().c_str()); + LOGI("group.GetOwner().GetDeviceAddress() = %s\n", group.GetOwner().GetDeviceAddress().c_str()); + LOGI("group.GetOwner().GetPrimaryDeviceType() = %s\n", group.GetOwner().GetPrimaryDeviceType().c_str()); + LOGI("group.GetOwner().GetSecondaryDeviceType() = %s\n", group.GetOwner().GetSecondaryDeviceType().c_str()); + LOGI("group.GetOwner().GetP2pDeviceStatus() = %d\n", static_cast(group.GetOwner().GetP2pDeviceStatus())); + + LOGI("group.GetOwner().GetWfdInfo().GetWfdEnabled() = %s\n", + group.GetOwner().GetWfdInfo().GetWfdEnabled() ? "true" : "false"); + LOGI("group.GetOwner().GetWfdInfo().GetDeviceInfo() = %d\n", group.GetOwner().GetWfdInfo().GetDeviceInfo()); + LOGI("group.GetOwner().GetWfdInfo().GetCtrlPort() = %d\n", group.GetOwner().GetWfdInfo().GetCtrlPort()); + LOGI("group.GetOwner().GetWfdInfo().GetMaxThroughput() = %d\n", group.GetOwner().GetWfdInfo().GetMaxThroughput()); + + LOGI("group.GetOwner().GetWpsConfigMethod() = %d\n", group.GetOwner().GetWpsConfigMethod()); + LOGI("group.GetOwner().GetDeviceCapabilitys() = %d\n", group.GetOwner().GetDeviceCapabilitys()); + LOGI("group.GetOwner().GetGroupCapabilitys() = %d\n", group.GetOwner().GetGroupCapabilitys()); + + LOGI("group.GetPassphrase() = %s\n", group.GetPassphrase().c_str()); + LOGI("group.GetInterface() = %s\n", group.GetInterface().c_str()); + LOGI("group.GetGroupName() = %s\n", group.GetGroupName().c_str()); + LOGI("group.GetNetworkId() = %d\n", group.GetNetworkId()); + LOGI("group.GetFrequency() = %d\n", group.GetFrequency()); + LOGI("group.IsPersistent() = %s\n", group.IsPersistent() ? "true" : "false"); + LOGI("group.GetP2pGroupStatus() = %d\n", static_cast(group.GetP2pGroupStatus())); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::P2pConnect(const WifiP2pConfig &config) +{ + LOGI("Mock_p2p:P2pConnect"); + LOGI("config.GetDeviceAddress() = %s\n", config.GetDeviceAddress().c_str()); + LOGI("config.GetGoBand() = %d\n", config.GetGoBand()); + LOGI("config.GetNetId() = %d\n", config.GetNetId()); + LOGI("config.GetPassphrase() = %s\n", config.GetPassphrase().c_str()); + + LOGI("config.GetWpsInfo().GetWpsMethod() = %d\n", static_cast(config.GetWpsInfo().GetWpsMethod())); + LOGI("config.GetWpsInfo().GetBssid() = %s\n", config.GetWpsInfo().GetBssid().c_str()); + LOGI("config.GetWpsInfo().GetPin() = %s\n", config.GetWpsInfo().GetPin().c_str()); + + LOGI("config.GetGroupOwnerIntent() = %d\n", config.GetGroupOwnerIntent()); + LOGI("config.GetGroupName() = %s\n", config.GetGroupName().c_str()); + WifiP2pInfo connInfo; + connInfo.SetGroupFormed(true); + connInfo.SetIsGroupOwner(true); + connInfo.SetIsGroupOwnerAddress("IsGroupOwnerAddress"); + mCallback.OnP2pConnectionChangedEvent(connInfo); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::P2pDisConnect() +{ + LOGI("Mock_p2p:P2pDisConnect"); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::QueryP2pInfo(WifiP2pInfo &connInfo) +{ + LOGI("Mock_p2p:QueryP2pInfo"); + connInfo.SetGroupFormed(true); + connInfo.SetIsGroupOwner(true); + connInfo.SetIsGroupOwnerAddress("IsGroupOwnerAddress"); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::GetCurrentGroup(WifiP2pGroupInfo &group) +{ + LOGI("Mock_p2p:GetCurrentGroup"); + group.SetGroupName("GroupName"); + + WifiP2pDevice owner; + owner.SetDeviceName("DeviceName"); + owner.SetDeviceAddress("DeviceAddress"); + owner.SetPrimaryDeviceType("PrimaryDeviceType"); + owner.SetSecondaryDeviceType("SecondaryDeviceType"); + owner.SetP2pDeviceStatus(P2pDeviceStatus::PDS_INVITED); + WifiP2pWfdInfo wfdInfo; + wfdInfo.SetWfdEnabled(false); + wfdInfo.SetDeviceInfo(TEST_ONE_THOUSAND); + wfdInfo.SetCtrlPort(TEST_ONE_THOUSAND); + wfdInfo.SetMaxThroughput(TEST_ONE_THOUSAND); + owner.SetWfdInfo(wfdInfo); + owner.SetWpsConfigMethod(TEST_ONE_THOUSAND); + owner.SetDeviceCapabilitys(TEST_ONE_THOUSAND); + owner.SetGroupCapabilitys(TEST_ONE_THOUSAND); + group.SetOwner(owner); + group.SetIsGroupOwner(true); + + group.SetPassphrase("Passphrase"); + group.SetInterface("Interface"); + group.SetGroupName("GroupName"); + group.SetNetworkId(TEST_ONE_THOUSAND); + group.SetFrequency(TEST_ONE_THOUSAND); + group.SetIsPersistent(true); + group.SetP2pGroupStatus(P2pGroupStatus::GS_INVALID); + std::vector clientDevices; + clientDevices.push_back(owner); + group.SetClientDevices(clientDevices); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::GetP2pEnableStatus(int &status) +{ + LOGI("Mock_p2p:GetP2pEnableStatus"); + status = static_cast(P2pState::P2P_STATE_STARTING); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::GetP2pDiscoverStatus(int &status) +{ + LOGI("Mock_p2p:GetP2pDiscoverStatus"); + status = static_cast(P2pDiscoverState::P2P_DISCOVER_STARTING); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::GetP2pConnectedStatus(int &status) +{ + LOGI("Mock_p2p:GetP2pConnectedStatus"); + status = static_cast(P2pConnectedState::P2P_CONNECTED_STARTING); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::QueryP2pDevices(std::vector &devives) +{ + LOGI("Mock_p2p:QueryP2pDevices"); + WifiP2pDevice device1; + device1.SetDeviceName("DeviceName1"); + device1.SetDeviceAddress("DeviceAddress1"); + device1.SetPrimaryDeviceType("PrimaryDeviceType1"); + device1.SetSecondaryDeviceType("SecondaryDeviceType1"); + device1.SetP2pDeviceStatus(P2pDeviceStatus::PDS_INVITED); + WifiP2pWfdInfo wfdInfo1; + wfdInfo1.SetWfdEnabled(false); + wfdInfo1.SetDeviceInfo(TEST_ONE_THOUSAND); + wfdInfo1.SetCtrlPort(TEST_ONE_THOUSAND); + wfdInfo1.SetMaxThroughput(TEST_ONE_THOUSAND); + device1.SetWfdInfo(wfdInfo1); + device1.SetWpsConfigMethod(TEST_ONE_THOUSAND); + device1.SetDeviceCapabilitys(TEST_ONE_THOUSAND); + device1.SetGroupCapabilitys(TEST_ONE_THOUSAND); + devives.push_back(device1); + WifiP2pDevice device2; + device2.SetDeviceName("DeviceName2"); + device2.SetDeviceAddress("DeviceAddress2"); + device2.SetPrimaryDeviceType("PrimaryDeviceType2"); + device2.SetSecondaryDeviceType("SecondaryDeviceType2"); + device2.SetP2pDeviceStatus(P2pDeviceStatus::PDS_INVITED); + WifiP2pWfdInfo wfdInfo2; + wfdInfo2.SetWfdEnabled(false); + wfdInfo2.SetDeviceInfo(TEST_TWO_THOUSAND); + wfdInfo2.SetCtrlPort(TEST_TWO_THOUSAND); + wfdInfo2.SetMaxThroughput(TEST_TWO_THOUSAND); + device2.SetWfdInfo(wfdInfo2); + device2.SetWpsConfigMethod(TEST_TWO_THOUSAND); + device2.SetDeviceCapabilitys(TEST_TWO_THOUSAND); + device2.SetGroupCapabilitys(TEST_TWO_THOUSAND); + devives.push_back(device2); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::QueryP2pGroups(std::vector &groups) +{ + LOGI("Mock_p2p:QueryP2pGroups"); + WifiP2pGroupInfo group1; + group1.SetGroupName("GroupName1"); + WifiP2pDevice owner1; + owner1.SetDeviceName("DeviceName1"); + owner1.SetDeviceAddress("DeviceAddress1"); + owner1.SetPrimaryDeviceType("PrimaryDeviceType1"); + owner1.SetSecondaryDeviceType("SecondaryDeviceType1"); + owner1.SetP2pDeviceStatus(P2pDeviceStatus::PDS_INVITED); + WifiP2pWfdInfo wfdInfo1; + wfdInfo1.SetWfdEnabled(false); + wfdInfo1.SetDeviceInfo(TEST_ONE_THOUSAND); + wfdInfo1.SetCtrlPort(TEST_ONE_THOUSAND); + wfdInfo1.SetMaxThroughput(TEST_ONE_THOUSAND); + owner1.SetWfdInfo(wfdInfo1); + owner1.SetWpsConfigMethod(TEST_ONE_THOUSAND); + owner1.SetDeviceCapabilitys(TEST_ONE_THOUSAND); + owner1.SetGroupCapabilitys(TEST_ONE_THOUSAND); + group1.SetOwner(owner1); + group1.SetIsGroupOwner(true); + group1.SetPassphrase("Passphrase1"); + group1.SetInterface("Interface1"); + group1.SetGroupName("GroupName1"); + group1.SetNetworkId(TEST_ONE_THOUSAND); + group1.SetFrequency(TEST_ONE_THOUSAND); + group1.SetIsPersistent(true); + group1.SetP2pGroupStatus(P2pGroupStatus::GS_CREATED); + std::vector clientDevices1; + clientDevices1.push_back(owner1); + group1.SetClientDevices(clientDevices1); + groups.push_back(group1); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::QueryP2pServices(std::vector &services) +{ + LOGI("Mock_p2p:QueryP2pServices"); + OHOS::WifiP2pServiceInfo service1; + service1.SetServiceName("ServiceName1"); + service1.SetDeviceAddress("00:xx:xx:xx:xx:00"); + service1.SetServicerProtocolType(P2pServicerProtocolType::SERVICE_TYPE_ALL); + services.push_back(service1); + + OHOS::WifiP2pServiceInfo service2; + service2.SetServiceName("ServiceName2"); + service1.SetDeviceAddress("00:xx:xx:xx:xx:00"); + service1.SetServicerProtocolType(P2pServicerProtocolType::SERVICE_TYPE_ALL); + services.push_back(service2); + + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiMockP2pService::RegisterP2pServiceCallbacks(const IP2pServiceCallbacks &callbacks) +{ + mCallback = callbacks; + return WIFI_OPT_SUCCESS; +} + +extern "C" IP2pService *Create(void) +{ + return new (std::nothrow) WifiMockP2pService(); +} + +extern "C" void Destroy(IP2pService *p) +{ + delete p; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.h b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.h new file mode 100644 index 000000000..23f096944 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.h @@ -0,0 +1,60 @@ +/* + * 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_WIFI_MOCK_P2P_SERVICE_H +#define OHOS_WIFI_MOCK_P2P_SERVICE_H + +#include "wifi_p2p_msg.h" +#include "ip2p_service.h" +#include "ip2p_service_callbacks.h" + +namespace OHOS { +namespace Wifi { +const int TEST_ONE_THOUSAND = 1000; +const int TEST_TWO_THOUSAND = 2000; +class WifiMockP2pService : public IP2pService { +public: + ErrCode EnableP2p(); + ErrCode DisableP2p(); + ErrCode DiscoverDevices(); + ErrCode StopDiscoverDevices(); + ErrCode DiscoverServices(); + ErrCode StopDiscoverServices(); + ErrCode RequestService(const WifiP2pDevice &device, const WifiP2pServiceRequest &request); + ErrCode PutLocalP2pService(const WifiP2pServiceInfo &srvInfo); + ErrCode DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo); + ErrCode StartP2pListen(int period, int interval); + ErrCode StopP2pListen(); + ErrCode FormGroup(const WifiP2pConfig &config); + ErrCode RemoveGroup(); + ErrCode DeleteGroup(const WifiP2pGroupInfo &group); + ErrCode P2pConnect(const WifiP2pConfig &config); + ErrCode P2pDisConnect(); + ErrCode QueryP2pInfo(WifiP2pInfo &connInfo); + ErrCode GetCurrentGroup(WifiP2pGroupInfo &group); + ErrCode GetP2pEnableStatus(int &status); + ErrCode GetP2pDiscoverStatus(int &status); + ErrCode GetP2pConnectedStatus(int &status); + ErrCode QueryP2pDevices(std::vector &devives); + ErrCode QueryP2pGroups(std::vector &groups); + ErrCode QueryP2pServices(std::vector &services); + ErrCode RegisterP2pServiceCallbacks(const IP2pServiceCallbacks &callbacks); + +public: + IP2pServiceCallbacks mCallback; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.cpp new file mode 100644 index 000000000..afc84f1bb --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.cpp @@ -0,0 +1,102 @@ +/* + * 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 "wifi_service_manager_test.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiServiceManagerTest, CheckPreLoadServiceTest, TestSize.Level1) +{ + EXPECT_EQ(0, WifiServiceManager::GetInstance().CheckPreLoadService()); +} + +HWTEST_F(WifiServiceManagerTest, CheckAndEnforceService_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(0, WifiServiceManager::GetInstance().CheckAndEnforceService("StaService")); + EXPECT_EQ(0, WifiServiceManager::GetInstance().CheckAndEnforceService("ApService")); + EXPECT_EQ(0, WifiServiceManager::GetInstance().CheckAndEnforceService("ScanService")); + EXPECT_EQ(0, WifiServiceManager::GetInstance().CheckAndEnforceService("P2pService")); +} + +HWTEST_F(WifiServiceManagerTest, CheckAndEnforceService_FAILED, TestSize.Level1) +{ + EXPECT_EQ(-1, WifiServiceManager::GetInstance().CheckAndEnforceService("")); + EXPECT_EQ(-1, WifiServiceManager::GetInstance().CheckAndEnforceService("staservice")); + EXPECT_EQ(-1, WifiServiceManager::GetInstance().CheckAndEnforceService("any")); +} + +HWTEST_F(WifiServiceManagerTest, GetStaServiceInstTest, TestSize.Level1) +{ + EXPECT_TRUE(WifiServiceManager::GetInstance().GetStaServiceInst() == nullptr); + WifiServiceManager::GetInstance().CheckAndEnforceService("StaService"); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetStaServiceInst() != nullptr); + WifiServiceManager::GetInstance().UnloadService("StaService"); + WifiServiceManager::GetInstance().CheckAndEnforceService("StaService", false); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetStaServiceInst() != nullptr); +} + +HWTEST_F(WifiServiceManagerTest, GetScanServiceInstTest, TestSize.Level1) +{ + EXPECT_TRUE(WifiServiceManager::GetInstance().GetScanServiceInst() == nullptr); + WifiServiceManager::GetInstance().CheckAndEnforceService("ScanService"); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetScanServiceInst() != nullptr); + WifiServiceManager::GetInstance().UnloadService("ScanService"); + WifiServiceManager::GetInstance().CheckAndEnforceService("ScanService", false); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetScanServiceInst() != nullptr); +} + +HWTEST_F(WifiServiceManagerTest, GetApServiceInstTest, TestSize.Level1) +{ + EXPECT_TRUE(WifiServiceManager::GetInstance().GetApServiceInst() == nullptr); + WifiServiceManager::GetInstance().CheckAndEnforceService("ApService"); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetApServiceInst() != nullptr); + WifiServiceManager::GetInstance().UnloadService("ApService"); + WifiServiceManager::GetInstance().CheckAndEnforceService("ApService", false); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetApServiceInst() != nullptr); +} + +HWTEST_F(WifiServiceManagerTest, GetP2pServiceInstTest, TestSize.Level1) +{ + EXPECT_TRUE(WifiServiceManager::GetInstance().GetP2pServiceInst() == nullptr); + WifiServiceManager::GetInstance().CheckAndEnforceService("P2pService"); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetP2pServiceInst() != nullptr); + WifiServiceManager::GetInstance().UnloadService("P2pService"); + WifiServiceManager::GetInstance().CheckAndEnforceService("P2pService", false); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetP2pServiceInst() != nullptr); +} + +HWTEST_F(WifiServiceManagerTest, UnloadService, TestSize.Level1) +{ + WifiServiceManager::GetInstance().CheckAndEnforceService("StaService"); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetStaServiceInst() != nullptr); + WifiServiceManager::GetInstance().UnloadService("StaService"); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetStaServiceInst() == nullptr); +} + +HWTEST_F(WifiServiceManagerTest, UninstallAllService, TestSize.Level1) +{ + WifiServiceManager::GetInstance().CheckAndEnforceService("StaService"); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetStaServiceInst() != nullptr); + WifiServiceManager::GetInstance().CheckAndEnforceService("ApService"); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetApServiceInst() != nullptr); + WifiServiceManager::GetInstance().CheckAndEnforceService("P2pService"); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetP2pServiceInst() != nullptr); + WifiServiceManager::GetInstance().UninstallAllService(); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetStaServiceInst() == nullptr); + EXPECT_TRUE(WifiServiceManager::GetInstance().GetApServiceInst() == nullptr); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.h new file mode 100644 index 000000000..3d436f5d3 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.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_WIFI_SERVICE_MANAGER_TEST_H +#define OHOS_WIFI_SERVICE_MANAGER_TEST_H +#include + +#include "wifi_service_manager.h" + +namespace OHOS { +namespace Wifi { +class WifiServiceManagerTest : public testing::Test { +public: + static void SetUpTestCase() + { + WifiServiceManager::GetInstance().Init(); + } + static void TearDownTestCase() + {} + virtual void SetUp() + { + WifiServiceManager::GetInstance().UninstallAllService(); + } + virtual void TearDown() + { + WifiServiceManager::GetInstance().UninstallAllService(); + } + +public: +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn new file mode 100644 index 000000000..7e99e7aa5 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn @@ -0,0 +1,68 @@ +# 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. + +import("//build/test.gni") +SUBSYSTEM_DIR = "//foundation/communication" +module_output_path = "wifi_standard/ap_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/test", + ] +} + +ohos_unittest("WifiApServiceTest") { + module_out_path = module_output_path + sources = [ "wifi_ap_service_test.cpp" ] + + include_dirs = [ + "./", + "../..", + "../Mock/", + "//utils/native/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", + "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", + "//third_party/googletest/googlemock/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", + ] + + deps = [ + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat:WifiApNatManagerTest", + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test:WifiHotspotTest", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + part_name = "wifi_standard" + subsystem_name = "communication" +} +group("unittest") { + testonly = true + deps = [] + deps += [ ":WifiApServiceTest" ] +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_config_use.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_config_use.h new file mode 100644 index 000000000..5484ac371 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_config_use.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_MOCK_AP_CONFIG_USE_H +#define OHOS_MOCK_AP_CONFIG_USE_H + +#include +#include + +#include "ap_macro.h" +#include "wifi_msg.h" +#include "ap_config_use.h" +namespace OHOS { +namespace Wifi { +class MockApConfigUse : public ApConfigUse { +public: + MOCK_CONST_METHOD2( + TransformFrequencyIntoChannel, void(const std::vector &FreqVector, std::vector &ChanVector)); + MOCK_CONST_METHOD1(LogConfig, void(HotspotConfig &apConfig)); + MOCK_CONST_METHOD1(IsValid24GHz, bool(int freq)); + MOCK_CONST_METHOD1(IsValid5GHz, bool(int freq)); + MOCK_CONST_METHOD2(CheckBandChannel, void(HotspotConfig &apConfig, const ChannelsTable &validChanTable)); + MOCK_CONST_METHOD1(TransformFrequencyIntoChannel, int(int freq)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_idle_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_idle_state.h new file mode 100644 index 000000000..dd98a9c69 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_idle_state.h @@ -0,0 +1,37 @@ +/* + * 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_AP_IDLE_STATE_H +#define OHOS_MOCK_AP_IDLE_STATE_H + +#include +#include "wifi_msg.h" +#include "ap_idle_state.h" + +namespace OHOS { +namespace Wifi { +class ApStateMachine; +class MockApIdleState : public ApIdleState { +public: + MockApIdleState(ApStateMachine &apStateMachine) : ApIdleState(apStateMachine) + {} + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; + +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_monitor.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_monitor.h new file mode 100644 index 000000000..35a581bdf --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_monitor.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_MOCK_AP_MONITOR_H +#define OHOS_MOCK_AP_MONITOR_H +#include + +#include "wifi_msg.h" +#include "ap_macro.h" +#include "ap_monitor.h" + +namespace OHOS { +namespace Wifi { +class MockApMonitor : public ApMonitor { +public: + MOCK_CONST_METHOD2(StationChangeEvent, void(StationInfo &staInfo, const int event)); + MOCK_CONST_METHOD1(OnHotspotStateEvent, void(int state)); + MOCK_METHOD0(StartMonitor, void()); + MOCK_METHOD0(StopMonitor, void()); +}; + +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_root_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_root_state.h new file mode 100644 index 000000000..fe27098c4 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_root_state.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_AP_ROOT_STATE_H +#define OHOS_MOCK_AP_ROOT_STATE_H + +#include +#include "wifi_msg.h" +#include "ap_root_state.h" + +namespace OHOS { +namespace Wifi { +class ApStateMachine; +class MockApRootState : public ApRootState { +public: + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; /* ApRootState */ +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_service.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_service.h new file mode 100644 index 000000000..2f8675b1a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_service.h @@ -0,0 +1,42 @@ +/* + * 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_AP_SERVICE_H +#define OHOS_MOCK_AP_SERVICE_H + +#include +#include "wifi_internal_msg.h" +#include "wifi_msg.h" +#include "ap_macro.h" +#include "ap_service.h" +namespace OHOS { +namespace Wifi { +class MockApService : public ApService { +public: + MockApService(ApStateMachine &apStateMachine) : ApService(apStateMachine) + {} + MOCK_METHOD0(EnableHotspot, ErrCode()); + MOCK_METHOD0(DisableHotspot, ErrCode()); + MOCK_METHOD1(AddBlockList, ErrCode(const StationInfo &stationInfo)); + MOCK_METHOD1(DelBlockList, ErrCode(const StationInfo &stationInfo)); + MOCK_METHOD1(SetHotspotConfig, ErrCode(const HotspotConfig &hotspotConfig)); + MOCK_METHOD1(DisconnetStation, ErrCode(const StationInfo &stationInfo)); + MOCK_METHOD1(GetValidBands, ErrCode(std::vector &bands)); + MOCK_METHOD2(GetValidChannels, ErrCode(BandType band, std::vector &validchannel)); + MOCK_METHOD1(RegisterApServiceCallbacks, ErrCode(const IApServiceCallbacks &callbacks)); +}; +} /* namespace Wifi */ +} /* namespace OHOS */ +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_started_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_started_state.h new file mode 100644 index 000000000..c129c0d9e --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_started_state.h @@ -0,0 +1,37 @@ +/* + * 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_AP_STARTED_STATE_H +#define OHOS_MOCK_AP_STARTED_STATE_H + +#include +#include "wifi_msg.h" +#include "ap_started_state.h" + +namespace OHOS { +namespace Wifi { +class MockApStartedState : public ApStartedState { +public: + MockApStartedState(ApStateMachine &apStateMachine, ApConfigUse &apConfigUse, ApMonitor &apMonitor) + : ApStartedState(apStateMachine, apConfigUse, apMonitor) + {} + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; + +} // namespace OHOS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_state_machine.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_state_machine.h new file mode 100644 index 000000000..ce4ddd55f --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_state_machine.h @@ -0,0 +1,41 @@ +/* + * 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_AP_STATE_MACHINE_H +#define OHOS_MOCK_AP_STATE_MACHINE_H + +#include +#include "internal_message.h" +#include "wifi_msg.h" +#include "ap_state_machine.h" + +namespace OHOS { +namespace Wifi { +class MockApStateMachine : public ApStateMachine { +public: + MockApStateMachine(ApStationsManager &apStationsManager, ApRootState &apRootState, ApIdleState &apIdleState, + ApStartedState &apStartedState, ApMonitor &apMonitor) + : ApStateMachine(apStationsManager, apRootState, apIdleState, apStartedState, apMonitor) + {} + MOCK_METHOD1(OnApStateChange, void(ApState)); + MOCK_METHOD1(BroadCastStationJoin, void(const StationInfo &staInfo)); + MOCK_METHOD1(BroadCastStationLeave, void(const StationInfo &staInfo)); + MOCK_METHOD1(RegisterApServiceCallbacks, ErrCode(const IApServiceCallbacks &callbacks)); + MOCK_METHOD0(StartDhcpServer, bool()); + MOCK_METHOD0(StopDhcpServer, bool()); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_stations_manager.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_stations_manager.h new file mode 100644 index 000000000..a3d54d176 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_stations_manager.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_MOCK_AP_STATIONS_MANAGER_H +#define OHOS_MOCK_AP_STATIONS_MANAGER_H + +#include +#include +#include +#include "wifi_msg.h" +#include "ap_stations_manager.h" + +namespace OHOS { +namespace Wifi { +class MockApStationsManager : public ApStationsManager { +public: + MOCK_CONST_METHOD1(AddBlockList, bool(const StationInfo &staInfo)); + MOCK_CONST_METHOD1(DelBlockList, bool(const StationInfo &staInfo)); + MOCK_CONST_METHOD0(EnableAllBlockList, bool()); + MOCK_CONST_METHOD1(StationLeave, void(const std::string &mac)); + MOCK_CONST_METHOD1(StationJoin, void(const StationInfo &staInfo)); + MOCK_CONST_METHOD1(DisConnectStation, bool(const StationInfo &staInfo)); + MOCK_CONST_METHOD0(GetAllConnectedStations, std::vector()); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.cpp new file mode 100644 index 000000000..1425a00e6 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.cpp @@ -0,0 +1,90 @@ +/* + * 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 "mock_network_interface.h" + +namespace OHOS { +namespace Wifi { +namespace NetworkInterface { +bool IsValidInterfaceName(const std::string &interfaceName) +{ + return MockNetworkInterface::GetInstance().IsValidInterfaceName(interfaceName); +} + +void Dump(const std::string &interfaceName) +{ + MockNetworkInterface::GetInstance().Dump(interfaceName); +} + +bool FetchInterfaceConfig( + const std::string &interfaceName, MacAddress &Mac, Ipv4Address &IPv4, std::vector &vecIPv6) +{ + return MockNetworkInterface::GetInstance().FetchInterfaceConfig(interfaceName, Mac, IPv4, vecIPv6); +} + +bool GetIpv4Address(const std::string &interfaceName, Ipv4Address &IPv4) +{ + return MockNetworkInterface::GetInstance().GetIpv4Address(interfaceName, IPv4); +} + +bool GetAllIpv6Address(const std::string &interfaceName, std::vector &vecIPv6) +{ + return MockNetworkInterface::GetInstance().GetAllIpv6Address(interfaceName, vecIPv6); +} + +bool IsExistAddressForInterface(const std::string &interfaceName, const BaseAddress &address) +{ + return MockNetworkInterface::GetInstance().IsExistAddressForInterface(interfaceName, address); +} + +bool AddIpAddress(const std::string &interfaceName, const BaseAddress &IpAddress) +{ + return MockNetworkInterface::GetInstance().AddIpAddress(interfaceName, IpAddress); +} + +bool DelIpAddress(const std::string &interfaceName, const BaseAddress &IpAddress) +{ + return MockNetworkInterface::GetInstance().DelIpAddress(interfaceName, IpAddress); +} + +bool ClearAllIpAddress(const std::string &interfaceName) +{ + return MockNetworkInterface::GetInstance().ClearAllIpAddress(interfaceName); +} + +bool FetchIpAddress( + const std::string &interfaceName, std::vector &vecIPv4, std::vector &vecIPv6) +{ + return MockNetworkInterface::GetInstance().FetchIpAddress(interfaceName, vecIPv4, vecIPv6); +} + +bool SaveIpAddress(struct ifaddrs *ifa, Ipv4Address &ipv4, std::vector &vecIPv6) +{ + return MockNetworkInterface::GetInstance().SaveIpAddress(ifa, ipv4, vecIPv6); +} + +bool IpAddressChange(const std::string &interface, const BaseAddress &IpAddress, bool Action, bool Dad) +{ + return MockNetworkInterface::GetInstance().IpAddressChange(interface, IpAddress, Action, Dad); +} +} /* namespace NetworkInterface */ + +MockNetworkInterface &MockNetworkInterface::GetInstance() +{ + static MockNetworkInterface gMockNetworkInterface; + return gMockNetworkInterface; +}; +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.h new file mode 100644 index 000000000..64fada9d1 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.h @@ -0,0 +1,56 @@ +/* + * 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_NETWORK_INTERFACE_H +#define OHOS_MOCK_NETWORK_INTERFACE_H + +#include + +#include "ipv4_address.h" +#include "ipv6_address.h" +#include "mac_address.h" +#include +#include + +namespace OHOS { +namespace Wifi { +class MockNetworkInterface { +public: + MOCK_METHOD1(IsValidInterfaceName, bool(const std::string &interfaceName)); + MOCK_METHOD1(Dump, void(const std::string &interfaceName)); + + MOCK_METHOD4(FetchInterfaceConfig, + bool(const std::string &interfaceName, MacAddress &Mac, Ipv4Address &IPv4, std::vector &vecIPv6)); + MOCK_METHOD2(GetIpv4Address, bool(const std::string &interfaceName, Ipv4Address &IPv4)); + MOCK_METHOD2(GetAllIpv6Address, bool(const std::string &interfaceName, std::vector &vecIPv6)); + MOCK_METHOD2(IsExistAddressForInterface, bool(const std::string &interfaceName, const BaseAddress &address)); + MOCK_METHOD2(AddIpAddress, bool(const std::string &interfaceName, const BaseAddress &IpAddress)); + MOCK_METHOD2(DelIpAddress, bool(const std::string &interfaceName, const BaseAddress &IpAddress)); + MOCK_METHOD1(ClearAllIpAddress, bool(const std::string &interfaceName)); + MOCK_METHOD3(FetchIpAddress, + bool(const std::string &interfaceName, std::vector &vecIPv4, std::vector &vecIPv6)); + MOCK_METHOD3(SaveIpAddress, bool(struct ifaddrs *ifa, Ipv4Address &ipv4, std::vector &vecIPv6)); + MOCK_METHOD4( + IpAddressChange, bool(const std::string &interface, const BaseAddress &IpAddress, bool Action, bool Dad)); + static MockNetworkInterface &GetInstance(void); + +private: + MockNetworkInterface(){} + ~MockNetworkInterface(){} +}; +} // namespace Wifi +} // namespace OHOS + +#endif /* OHOS_NETWORK_INTERFACE_H */ \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_pendant.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_pendant.h new file mode 100644 index 000000000..d264f5972 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_pendant.h @@ -0,0 +1,93 @@ +/* + * 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_AP_PENDANT_H +#define OHOS_MOCK_AP_PENDANT_H +#include "mock_ap_service.h" +#include "mock_ap_monitor.h" +#include "mock_ap_config_use.h" +#include "mock_ap_stations_manager.h" + +#include "mock_ap_root_state.h" +#include "mock_ap_idle_state.h" +#include "mock_ap_started_state.h" +#include "mock_ap_state_machine.h" +#include "mock_ap_service.h" + +namespace OHOS { +namespace Wifi { + +class MockPendant { +public: + MockPendant() + : m_MockApRootState(), + m_MockApIdleState(m_MockApStateMachine), + m_MockApStartedState(m_MockApStateMachine, m_MockApConfigUse, m_MockApMonitor), + m_MockApService(m_MockApStateMachine), + m_MockApStateMachine( + m_MockApStationsManager, m_MockApRootState, m_MockApIdleState, m_MockApStartedState, m_MockApMonitor), + m_MockApConfigUse(), + m_MockApStationsManager() + {} + +public: + MockApRootState &GetMockApRootState() + { + return m_MockApRootState; + } + MockApIdleState &GetMockApIdleState() + { + return m_MockApIdleState; + } + MockApStartedState &GetMockApStartedState() + { + return m_MockApStartedState; + } + MockApService &GetMockApService() + { + return m_MockApService; + } + MockApStateMachine &GetMockApStateMachine() + { + return m_MockApStateMachine; + } + MockApMonitor &GetMockApMonitor() + { + return m_MockApMonitor; + } + MockApConfigUse &GetMockApConfigUse() + { + return m_MockApConfigUse; + } + MockApStationsManager &GetMockApStationsManager() + { + return m_MockApStationsManager; + } + +private: + MockApRootState m_MockApRootState; + MockApIdleState m_MockApIdleState; + MockApStartedState m_MockApStartedState; + + MockApService m_MockApService; + MockApStateMachine m_MockApStateMachine; + MockApMonitor m_MockApMonitor; + + MockApConfigUse m_MockApConfigUse; + MockApStationsManager m_MockApStationsManager; +}; +} // namespace Wifi +} // namespace OHOS +#endif // OHOS_MOCK_AP_PENDANT_H diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.cpp new file mode 100644 index 000000000..acddb40d5 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.cpp @@ -0,0 +1,54 @@ +/* + * 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 "mock_system_interface.h" +using namespace OHOS; +using namespace Wifi; + +static bool mockTag = false; + +MockSystemInterface &MockSystemInterface::GetInstance() +{ + static MockSystemInterface gMockSystemInterface; + return gMockSystemInterface; +}; + +MockSystemInterface::MockSystemInterface() +{} + +void MockSystemInterface::SetMockFlag(bool flag) +{ + mockTag = flag; +} + +bool MockSystemInterface::GetMockFlag(void) +{ + return mockTag; +} + +#ifdef __cplusplus +extern "C" { +#endif + +int __real_system(const char *__command); +int __wrap_system(const char *__command) +{ + if (mockTag) { + return MockSystemInterface::GetInstance().system(__command); + } else { + return __real_system(__command); + } +} +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.h new file mode 100644 index 000000000..ce47d2adf --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.h @@ -0,0 +1,42 @@ +/* + * 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_SYSTEM_INTERFACE_H +#define OHOS_MOCK_SYSTEM_INTERFACE_H + +#include +#include +#include + +namespace OHOS { +namespace Wifi { +class MockSystemInterface { +public: + MOCK_METHOD1(system, int(const char *__command)); + + static MockSystemInterface &GetInstance(void); + static void SetMockFlag(bool flag); + static bool GetMockFlag(void); + +private: + MockSystemInterface(); + ~MockSystemInterface(){} +}; +} // namespace Wifi +} // namespace OHOS + +extern "C" {} + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.cpp new file mode 100644 index 000000000..12beb18eb --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.cpp @@ -0,0 +1,26 @@ +/* + * 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 "mock_wifi_ap_hal_interface.h" + +namespace OHOS { +namespace Wifi { +WifiApHalInterface &WifiApHalInterface::GetInstance(void) +{ + static WifiApHalInterface inst; + return inst; +} +} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.h new file mode 100644 index 000000000..6cd3dbdb1 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.h @@ -0,0 +1,74 @@ +/* + * 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_WIFI_AP_HAL_INTERFACE_H +#define OHOS_MOCK_WIFI_AP_HAL_INTERFACE_H +#include "wifi_msg.h" +#include +#include +#include +#include + +#include "i_wifi_struct.h" +#include "wifi_error_no.h" +#include "wifi_msg.h" +#include +#include +#include + +namespace OHOS { +namespace Wifi { +typedef struct IWifiApMonitorEventCallback { + std::function onStaJoinOrLeave; + std::function onApEnableOrDisable; +} IWifiApMonitorEventCallback; +class MockWifiApHalInterface { +public: + virtual ~MockWifiApHalInterface() = default; + virtual WifiErrorNo StartAp(void) = 0; + virtual WifiErrorNo StopAp(void) = 0; + virtual WifiErrorNo StopAp1(void) = 0; + virtual WifiErrorNo SetSoftApConfig(const HotspotConfig &config) = 0; + virtual WifiErrorNo GetStationList(std::vector &result) = 0; + virtual WifiErrorNo SetHotspotConfig(const int &channel, const std::string &mscb) = 0; + virtual WifiErrorNo AddBlockByMac(const std::string &mac) = 0; + virtual WifiErrorNo DelBlockByMac(const std::string &mac) = 0; + virtual WifiErrorNo RemoveStation(const std::string &mac) = 0; + virtual WifiErrorNo GetFrequenciesByBand(int band, std::vector &frequencies) = 0; + virtual WifiErrorNo RegisterApEvent(IWifiApMonitorEventCallback callback) = 0; + virtual WifiErrorNo SetWifiCountryCode(const std::string &code) = 0; + virtual WifiErrorNo DisconnectStaByMac(const std::string &mac) = 0; +}; + +class WifiApHalInterface : public MockWifiApHalInterface { +public: + static WifiApHalInterface &GetInstance(void); + MOCK_METHOD0(StartAp, WifiErrorNo(void)); + MOCK_METHOD0(StopAp1, WifiErrorNo(void)); + MOCK_METHOD0(StopAp, WifiErrorNo(void)); + MOCK_METHOD1(SetSoftApConfig, WifiErrorNo(const HotspotConfig &config)); + MOCK_METHOD1(GetStationList, WifiErrorNo(std::vector &result)); + MOCK_METHOD2(SetHotspotConfig, WifiErrorNo(const int &channel, const std::string &mscb)); + MOCK_METHOD1(AddBlockByMac, WifiErrorNo(const std::string &mac)); + MOCK_METHOD1(DelBlockByMac, WifiErrorNo(const std::string &mac)); + MOCK_METHOD1(RemoveStation, WifiErrorNo(const std::string &mac)); + MOCK_METHOD2(GetFrequenciesByBand, WifiErrorNo(int band, std::vector &frequencies)); + MOCK_METHOD1(RegisterApEvent, WifiErrorNo(IWifiApMonitorEventCallback callback)); + MOCK_METHOD1(SetWifiCountryCode, WifiErrorNo(const std::string &code)); + MOCK_METHOD1(DisconnectStaByMac, WifiErrorNo(const std::string &mac)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_nat_manager.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_nat_manager.h new file mode 100644 index 000000000..0dd519086 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_nat_manager.h @@ -0,0 +1,33 @@ +/* + * 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_WIFI_AP_NAT_MANAGER_H +#define OHOS_MOCK_WIFI_AP_NAT_MANAGER_H + +#include + +#include +#include "wifi_ap_nat_manager.h" + +namespace OHOS { +namespace Wifi { +class MockWifiApNatManager : public WifiApNatManager { +public: + MOCK_CONST_METHOD3( + EnableInterfaceNat, bool(bool enable, std::string inInterfaceName, std::string outInterfaceName)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.cpp new file mode 100644 index 000000000..afa823f4a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.cpp @@ -0,0 +1,26 @@ +/* + * 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 "mock_wifi_settings.h" + +namespace OHOS { +namespace Wifi { +WifiSettings &WifiSettings::GetInstance() +{ + static WifiSettings gWifiSettings; + return gWifiSettings; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.h new file mode 100644 index 000000000..e86e83733 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.h @@ -0,0 +1,82 @@ +/* + * 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_WIFI_SETTINGS_H +#define OHOS_MOCK_WIFI_SETTINGS_H +#include +#include +#include + +#include "wifi_msg.h" +#include + +namespace OHOS { +namespace Wifi { + +const int MODE_ADD = 0; +const int MODE_DEL = 1; +const int MODE_UPDATE = 2; + +using ChannelsTable = std::map>; + +class MockWifiSettings { +public: + virtual ~MockWifiSettings() = default; + virtual int SetCountryCode(const std::string &countryCode) = 0; + virtual int GetCountryCode(std::string &countryCode) = 0; + virtual int GetHotspotState() = 0; + virtual int SetHotspotState(int state) = 0; + virtual int SetHotspotConfig(const HotspotConfig &config) = 0; + virtual int GetHotspotConfig(HotspotConfig &config) = 0; + virtual int GetStationList(std::vector &results) = 0; + virtual int ManageStation(const StationInfo &info, int mode) = 0; /* add / update / remove */ + virtual int ClearStationList() = 0; + virtual int GetBlockList(std::vector &results) = 0; + virtual int ManageBlockList(const StationInfo &info, int mode) = 0; /* add / remove */ + virtual int FindConnStation(const StationInfo &info) = 0; + virtual int GetValidBands(std::vector &bands) = 0; + virtual int SetValidChannels(const ChannelsTable &channelsInfo) = 0; + virtual int GetValidChannels(ChannelsTable &channelsInfo) = 0; + virtual int ClearValidChannels() = 0; + virtual int GetApMaxConnNum() = 0; +}; + +class WifiSettings : public MockWifiSettings { +public: + WifiSettings() = default; + ~WifiSettings() = default; + static WifiSettings &GetInstance(void); + + MOCK_METHOD1(SetCountryCode, int(const std::string &countryCode)); + MOCK_METHOD1(GetCountryCode, int(std::string &countryCode)); + MOCK_METHOD0(GetHotspotState, int()); + MOCK_METHOD1(SetHotspotState, int(int)); + MOCK_METHOD1(SetHotspotConfig, int(const HotspotConfig &config)); + MOCK_METHOD1(GetHotspotConfig, int(HotspotConfig &config)); + MOCK_METHOD1(GetStationList, int(std::vector &results)); + MOCK_METHOD2(ManageStation, int(const StationInfo &info, int mode)); + MOCK_METHOD0(ClearStationList, int()); + MOCK_METHOD1(GetBlockList, int(std::vector &results)); + MOCK_METHOD2(ManageBlockList, int(const StationInfo &info, int mode)); + MOCK_METHOD1(FindConnStation, int(const StationInfo &info)); + MOCK_METHOD1(GetValidBands, int(std::vector &bands)); + MOCK_METHOD1(SetValidChannels, int(const ChannelsTable &channelsInfo)); + MOCK_METHOD1(GetValidChannels, int(ChannelsTable &channelsInfo)); + MOCK_METHOD0(ClearValidChannels, int()); + MOCK_METHOD0(GetApMaxConnNum, int()); +}; +} /* namespace Wifi */ +} /* namespace OHOS */ +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.cpp new file mode 100644 index 000000000..46c303466 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.cpp @@ -0,0 +1,57 @@ +/* + * 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 "operator_overload.h" + +namespace OHOS { +namespace Wifi { +bool operator==(const StationInfo &a, const StationInfo &b) +{ + if (a.deviceName != b.deviceName) { + return false; + } + if (a.bssid != b.bssid) { + return false; + } + if (a.ipAddr != b.ipAddr) { + return false; + } + return true; +} + +bool operator==(const HotspotConfig &a, const HotspotConfig &b) +{ + if (a.GetSsid() != b.GetSsid()) { + return false; + } + if (a.GetPreSharedKey() != b.GetPreSharedKey()) { + return false; + } + if (a.GetSecurityType() != b.GetSecurityType()) { + return false; + } + if (a.GetBand() != b.GetBand()) { + return false; + } + if (a.GetChannel() != b.GetChannel()) { + return false; + } + if (a.GetMaxConn() != b.GetMaxConn()) { + return false; + } + return true; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.h new file mode 100644 index 000000000..3a63a5b10 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.h @@ -0,0 +1,27 @@ +/* + * 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_OPERATOR_OVERLOAD_H +#define OHOS_OPERATOR_OVERLOAD_H + +#include "wifi_msg.h" + +namespace OHOS { +namespace Wifi { +bool operator==(const StationInfo &a, const StationInfo &b); +bool operator==(const HotspotConfig &a, const HotspotConfig &b); +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.cpp new file mode 100644 index 000000000..e3d7891fd --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.cpp @@ -0,0 +1,23 @@ +/* + * 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 "global_test.h" +void GlobalTest::SetUp() +{ + printf("GlobalTest SetUp\n"); +} +void GlobalTest::TearDown() +{ + printf("GlobalTest TearDown\n"); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.h new file mode 100644 index 000000000..65afff0de --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.h @@ -0,0 +1,24 @@ +/* + * 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 GLOBAL_TEST_H +#define GLOBAL_TEST_H +#include +class GlobalTest : public testing::Environment { +public: + virtual void SetUp(); + virtual void TearDown(); +}; +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/BUILD.gn new file mode 100644 index 000000000..cc4a8d0d7 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/BUILD.gn @@ -0,0 +1,82 @@ +# 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. + +import("//build/test.gni") +SUBSYSTEM_DIR = "//foundation/communication" +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/test/wifi_ap_dhcp_nat", + ] +} + +ohos_unittest("WifiApNatManagerTest") { + module_out_path = "wifi_standard/ap_test" + sources = [ + "../Mock/mock_network_interface.cpp", + "../Mock/mock_system_interface.cpp", + "../global_test.cpp", + "../wifi_ap_test.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.cpp", + "wifi_ap_nat_manager_test.cpp", + ] + + include_dirs = [ + "./", + "../../", + "../Mock/", + "//utils/native/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", + "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", + "//third_party/googletest/googlemock/include", + "//third_party/googletest/googletest/include", + ] + ldflags = [ + "-fPIC", + "-Wl,-E", + "-Wl,--wrap=system", + "--coverage", + ] + deps = [ + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + part_name = "wifi_standard" + subsystem_name = "communication" +} +group("unittest") { + testonly = true + deps = [] + deps += [ ":WifiApNatManagerTest" ] +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/global_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/global_test.cpp new file mode 100644 index 000000000..e3d7891fd --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/global_test.cpp @@ -0,0 +1,23 @@ +/* + * 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 "global_test.h" +void GlobalTest::SetUp() +{ + printf("GlobalTest SetUp\n"); +} +void GlobalTest::TearDown() +{ + printf("GlobalTest TearDown\n"); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/global_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/global_test.h new file mode 100644 index 000000000..65afff0de --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/global_test.h @@ -0,0 +1,24 @@ +/* + * 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 GLOBAL_TEST_H +#define GLOBAL_TEST_H +#include +class GlobalTest : public testing::Environment { +public: + virtual void SetUp(); + virtual void TearDown(); +}; +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/wifi_ap_nat_manager_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/wifi_ap_nat_manager_test.cpp new file mode 100644 index 000000000..79d18f41c --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/wifi_ap_nat_manager_test.cpp @@ -0,0 +1,159 @@ +/* + * 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 "wifi_ap_nat_manager.h" +#include "mock_network_interface.h" +#include "mock_system_interface.h" + +#include +#include + +#include + +using ::testing::_; +using ::testing::Return; + +namespace OHOS { +namespace Wifi { +class WifiApNatManager_test : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: + bool WrapSetForwarding(bool enable) + { + return mApNatManager.SetForwarding(enable); + } + bool WrapSetInterfaceRoute(bool enable) + { + return mApNatManager.SetInterfaceRoute(enable); + } + bool WrapSetInterfaceNat(bool enable, const std::string &outInterfaceName) + { + return mApNatManager.SetInterfaceNat(enable, outInterfaceName); + } + bool WrapWriteDataToFile(const std::string &fileName, const std::string &content) + { + return mApNatManager.WriteDataToFile(fileName, content); + } + bool WrapExecCommand(const std::vector &vecCommandArg) + { + return mApNatManager.ExecCommand(vecCommandArg); + } + +public: + std::string ifc1 = "wlan1"; + std::string ifc2 = "wlan2"; + std::string badifc = "wlan!!"; + WifiApNatManager mApNatManager; +}; + +TEST_F(WifiApNatManager_test, EnableInterfaceNat_SUCCESS) +{ + int fd = 10; + MockSystemInterface::SetMockFlag(true); + EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillOnce(Return(-1)).WillRepeatedly(Return(fd)); + EXPECT_CALL(MockNetworkInterface::GetInstance(), IsValidInterfaceName(_)).WillRepeatedly(Return(true)); + EXPECT_TRUE(mApNatManager.EnableInterfaceNat(true, ifc1, ifc2)); + EXPECT_FALSE(mApNatManager.EnableInterfaceNat(true, ifc1, ifc1)); + + EXPECT_CALL(MockNetworkInterface::GetInstance(), IsValidInterfaceName(_)) + .WillOnce(Return(true)) + .WillRepeatedly(Return(false)); + + EXPECT_FALSE(mApNatManager.EnableInterfaceNat(true, badifc, ifc1)); + EXPECT_FALSE(mApNatManager.EnableInterfaceNat(true, std::string(""), ifc1)); +} + +TEST_F(WifiApNatManager_test, DisableInterfaceNat_SUCCESS) +{ + int fd = 10; + MockSystemInterface::SetMockFlag(true); + EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillOnce(Return(-1)).WillRepeatedly(Return(fd)); + EXPECT_CALL(MockNetworkInterface::GetInstance(), IsValidInterfaceName(_)).WillRepeatedly(Return(true)); + EXPECT_TRUE(mApNatManager.EnableInterfaceNat(false, ifc1, ifc2)); + EXPECT_FALSE(mApNatManager.EnableInterfaceNat(false, ifc1, ifc1)); + + EXPECT_CALL(MockNetworkInterface::GetInstance(), IsValidInterfaceName(_)) + .WillOnce(Return(true)) + .WillRepeatedly(Return(false)); + + EXPECT_FALSE(mApNatManager.EnableInterfaceNat(false, badifc, ifc1)); + EXPECT_FALSE(mApNatManager.EnableInterfaceNat(false, std::string(""), ifc1)); +} + +TEST_F(WifiApNatManager_test, SetForwarding_SUCCESS) +{ + EXPECT_TRUE(WrapSetForwarding(true)); + EXPECT_TRUE(WrapSetForwarding(false)); +} + +TEST_F(WifiApNatManager_test, SetInterfaceRoute_SUCCESS) +{ + int fd = 10; + MockSystemInterface::SetMockFlag(true); + EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillOnce(Return(-1)).WillRepeatedly(Return(fd)); + EXPECT_TRUE(WrapSetInterfaceRoute(true)); + EXPECT_TRUE(WrapSetInterfaceRoute(false)); +} + +TEST_F(WifiApNatManager_test, SetInterfaceNat_SUCCESS) +{ + int fd = 10; + MockSystemInterface::SetMockFlag(true); + EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillOnce(Return(-1)).WillRepeatedly(Return(fd)); + EXPECT_TRUE(WrapSetInterfaceNat(true, ifc2)); + EXPECT_TRUE(WrapSetInterfaceNat(false, ifc2)); +} + +TEST_F(WifiApNatManager_test, WriteDataToFile_SUCCESS) +{ + std::string filename = "./test.txt"; + std::string context = "1234567890"; + + MockSystemInterface::SetMockFlag(true); + + /* EXPECT_CALL(MockSystemInterface::GetInstance(), write(_, _, _)) + .WillOnce(Return(-1)) + .WillRepeatedly(Return(context.size())); */ +// EXPECT_CALL(MockSystemInterface::GetInstance(), close(_)).WillRepeatedly(Return(1)); + + EXPECT_TRUE(WrapWriteDataToFile(filename, context)); + EXPECT_TRUE(WrapWriteDataToFile(filename, context)); + EXPECT_TRUE(WrapWriteDataToFile(filename, context)); + + MockSystemInterface::SetMockFlag(false); +} + +TEST_F(WifiApNatManager_test, ExecCommand_SUCCESS) +{ + MockSystemInterface::SetMockFlag(true); + std::vector str; + EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillOnce(Return(true)).WillRepeatedly(Return(-1)); + + EXPECT_TRUE(WrapExecCommand(str)); + EXPECT_FALSE(WrapExecCommand(str)); + + MockSystemInterface::SetMockFlag(false); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/wifi_ap_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/wifi_ap_test.cpp new file mode 100644 index 000000000..e2e4b1c03 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/wifi_ap_test.cpp @@ -0,0 +1,25 @@ +/* + * 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 "global_test.h" +#include + +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + testing::Environment *env = new GlobalTest(); + testing::AddGlobalTestEnvironment(env); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_service_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_service_test.cpp new file mode 100644 index 000000000..23081d776 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_service_test.cpp @@ -0,0 +1,43 @@ +/* + * 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 "wifi_log.h" + +#define SIZE_ARRAY(arr) sizeof((arr)) / sizeof((arr)[0]) + +const std::string ApTestMember[] = { + "WifiHotspotTest", + "WifiApNatManagerTest", +}; + +int main() +{ + const size_t num = 11; + for (size_t i = 0; i < SIZE_ARRAY(ApTestMember); i++) { + std::string cmd = "./"; + const std::string &cmdTest = ApTestMember[i]; + + cmd += cmdTest; + int ret = system(cmd.c_str()); + if (ret == num) { + std::cout << "====================Error: " << cmdTest + << ", Segmentation fault!====================" << std::endl; + } + } + + return 0; +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_test.cpp new file mode 100644 index 000000000..e2e4b1c03 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_test.cpp @@ -0,0 +1,25 @@ +/* + * 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 "global_test.h" +#include + +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + testing::Environment *env = new GlobalTest(); + testing::AddGlobalTestEnvironment(env); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/BUILD.gn new file mode 100644 index 000000000..874995c69 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/BUILD.gn @@ -0,0 +1,108 @@ +# 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. + +import("//build/test.gni") +SUBSYSTEM_DIR = "//foundation/communication" +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/test/wifi_hotspot_test", + ] +} +ohos_unittest("WifiHotspotTest") { + module_out_path = "wifi_standard/ap_test" + sources = [ + "../Mock/mock_network_interface.cpp", + "../Mock/mock_system_interface.cpp", + "../Mock/mock_wifi_ap_hal_interface.cpp", + "../Mock/mock_wifi_settings.cpp", + "../Mock/operator_overload.cpp", + "../global_test.cpp", + "../wifi_ap_test.cpp", + "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.cpp", + "ap_config_use_test.cpp", + "ap_idle_state_test.cpp", + "ap_monitor_test.cpp", + "ap_root_state_test.cpp", + "ap_service_test.cpp", + "ap_started_state_test.cpp", + "ap_state_machine_test.cpp", + "ap_stations_manager_test.cpp", + ] + ldflags = [ + "-fPIC", + "-Wl,-E", + "-Wl,--wrap=system", + "--coverage", + ] + include_dirs = [ + "./", + "../../", + "../Mock/", + "//utils/native/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", + "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", + "//third_party/googletest/googlemock/include", + "//third_party/googletest/googletest/include", + ] + + deps = [ + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + part_name = "wifi_standard" + subsystem_name = "communication" +} +group("unittest") { + testonly = true + deps = [] + deps += [ ":WifiHotspotTest" ] +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_config_use_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_config_use_test.cpp new file mode 100644 index 000000000..5ef03b534 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_config_use_test.cpp @@ -0,0 +1,226 @@ +/* + * 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 "mock_wifi_settings.h" +#include "mock_wifi_ap_hal_interface.h" +#include "operator_overload.h" +#include "ap_config_use.h" + +using namespace OHOS; +using ::testing::_; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::StrEq; + +namespace OHOS { +namespace Wifi { +std::vector allowed5GFreq, allowed2GFreq; +std::vector allowed5GChan, allowed2GChan; +std::vector allowedFreqCom; +std::map> ChanTbs; + +class ApConfigUse_Test : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + const int testFreq1 = 2412; + const int testFreq2 = 2417; + const int testFreq3 = 2472; + const int testFreq4 = 2484; + const int testFreq5 = 5170; + const int testFreq6 = 5745; + const int testFreq7 = 5825; + + allowed2GFreq.push_back(testFreq1); + allowed2GFreq.push_back(testFreq2); + allowed2GFreq.push_back(testFreq3); + allowed2GFreq.push_back(testFreq4); + allowed5GFreq.push_back(testFreq5); + allowed5GFreq.push_back(testFreq6); + allowed5GFreq.push_back(testFreq7); + + const int testChannel1 = 1; + const int testChannel2 = 2; + const int testChannel3 = 13; + const int testChannel4 = 14; + + const int testChannel5 = 34; + const int testChannel6 = 149; + const int testChannel7 = 14; + + allowed2GChan.push_back(testChannel1); + allowed2GChan.push_back(testChannel2); + allowed2GChan.push_back(testChannel3); + allowed2GChan.push_back(testChannel4); + + allowed5GChan.push_back(testChannel5); + allowed5GChan.push_back(testChannel6); + allowed5GChan.push_back(testChannel7); + + ChanTbs[BandType::BAND_2GHZ] = allowed2GChan; + ChanTbs[BandType::BAND_5GHZ] = allowed5GChan; + + pApConfigUse = new ApConfigUse(); + } + virtual void TearDown() + { + allowed2GFreq.clear(); + allowed5GFreq.clear(); + allowed2GChan.clear(); + allowed5GChan.clear(); + + delete pApConfigUse; + } + +public: + ApConfigUse *pApConfigUse; +}; + +/* TransformFrequencyIntoChannel */ +TEST_F(ApConfigUse_Test, TransformFrequencyIntoChannel) +{ + const int testFreq1 = 2412; + const int testFreq2 = 2417; + const int testFreq13 = 2472; + const int testFreq14 = 2484; + + const int testFreq01 = 2411; + const int testFreq02 = 2485; + const int testFreq03 = 2473; + const int testFreq04 = 5826; + const int testFreq05 = 5169; + + const int testChannel34 = 5170; + const int testChannel149 = 5745; + const int testChannel165 = 5825; + + /* 2.4G success */ + EXPECT_EQ(1, pApConfigUse->TransformFrequencyIntoChannel(testFreq1)); + EXPECT_EQ(2, pApConfigUse->TransformFrequencyIntoChannel(testFreq2)); + EXPECT_EQ(13, pApConfigUse->TransformFrequencyIntoChannel(testFreq13)); + EXPECT_EQ(14, pApConfigUse->TransformFrequencyIntoChannel(testFreq14)); + /* 5G success */ + EXPECT_EQ(34, pApConfigUse->TransformFrequencyIntoChannel(testChannel34)); + EXPECT_EQ(149, pApConfigUse->TransformFrequencyIntoChannel(testChannel149)); + EXPECT_EQ(165, pApConfigUse->TransformFrequencyIntoChannel(testChannel165)); + /* 2.4G failed */ + EXPECT_EQ(-1, pApConfigUse->TransformFrequencyIntoChannel(testFreq01)); + EXPECT_EQ(-1, pApConfigUse->TransformFrequencyIntoChannel(testFreq02)); + EXPECT_EQ(-1, pApConfigUse->TransformFrequencyIntoChannel(testFreq03)); + /* 5G failed */ + EXPECT_EQ(-1, pApConfigUse->TransformFrequencyIntoChannel(testFreq04)); + EXPECT_EQ(-1, pApConfigUse->TransformFrequencyIntoChannel(testFreq05)); +} +/* TransformFrequencyIntoChannel_overload */ +TEST_F(ApConfigUse_Test, TransformFrequencyIntoChannel_1) +{ + const int testFreq1 = 2412; + const int testFreq2 = 2417; + const int testFreq3 = 2472; + const int testFreq4 = 2484; + const int testFreq5 = 5170; + const int testFreq6 = 5745; + const int testFreq7 = 5825; + const int testFreq = -1; + std::vector FreqVector; + FreqVector.push_back(testFreq1); + FreqVector.push_back(testFreq2); + FreqVector.push_back(testFreq3); + FreqVector.push_back(testFreq4); + FreqVector.push_back(testFreq5); + FreqVector.push_back(testFreq6); + FreqVector.push_back(testFreq7); + FreqVector.push_back(testFreq); + std::vector FreqVector1 = FreqVector; + + int buf[] = {1, 2, 13, 14, 34, 149, 165}; + std::vector ChanVector; + pApConfigUse->TransformFrequencyIntoChannel(FreqVector, ChanVector); + for (unsigned long i = 0; i < (sizeof(buf) / 4); ++i) { + EXPECT_EQ(buf[i], ChanVector[i]); + } + EXPECT_EQ(FreqVector1, FreqVector); +} +/* SetConfig */ +TEST_F(ApConfigUse_Test, LogConfig_SUCCESS) +{ + HotspotConfig apConfig; + apConfig.SetBand(BandType::BAND_2GHZ); + HotspotConfig apConfig1 = apConfig; + pApConfigUse->LogConfig(apConfig); + EXPECT_EQ(apConfig1, apConfig); +} + +/* IsValid24GHz */ +TEST_F(ApConfigUse_Test, IsValid24GHz) +{ + EXPECT_FALSE(pApConfigUse->IsValid24GHz(2400)); + EXPECT_FALSE(pApConfigUse->IsValid24GHz(2500)); + EXPECT_TRUE(pApConfigUse->IsValid24GHz(2412)); + EXPECT_TRUE(pApConfigUse->IsValid24GHz(2484)); + EXPECT_FALSE(pApConfigUse->IsValid24GHz(2499)); +} +/* IsValid5GHz */ +TEST_F(ApConfigUse_Test, IsValid5GHz) +{ + EXPECT_FALSE(pApConfigUse->IsValid5GHz(4900)); + EXPECT_FALSE(pApConfigUse->IsValid5GHz(5169)); + EXPECT_TRUE(pApConfigUse->IsValid5GHz(5170)); + EXPECT_TRUE(pApConfigUse->IsValid5GHz(5825)); + EXPECT_FALSE(pApConfigUse->IsValid5GHz(5827)); +} + +/* CheckBandChannel */ +TEST_F(ApConfigUse_Test, CheckBandChannel_1) +{ + HotspotConfig apConfig; + apConfig.SetBand(BandType::BAND_2GHZ); + apConfig.SetChannel(2); + HotspotConfig apConfig1 = apConfig; + std::vector band_2G_channel = {1, 2, 3, 4, 5, 6, 7}; + std::vector band_5G_channel = {149, 168, 169}; + ChannelsTable ChannelsTb = {{BandType::BAND_2GHZ, band_2G_channel}, {BandType::BAND_5GHZ, band_5G_channel}}; + + pApConfigUse->CheckBandChannel(apConfig, ChannelsTb); + EXPECT_EQ(apConfig1, apConfig); +} +TEST_F(ApConfigUse_Test, CheckBandChannel_2) +{ + HotspotConfig apConfig; + apConfig.SetBand(BandType::BAND_2GHZ); + apConfig.SetChannel(9); + std::vector band_2G_channel = {1, 2, 3, 4, 5, 6, 7}; + std::vector band_5G_channel = {149, 168, 169}; + ChannelsTable ChannelsTb = {{BandType::BAND_2GHZ, band_2G_channel}, {BandType::BAND_5GHZ, band_5G_channel}}; + pApConfigUse->CheckBandChannel(apConfig, ChannelsTb); + EXPECT_EQ(apConfig.GetChannel(), 6); + EXPECT_EQ(apConfig.GetBand(), BandType::BAND_2GHZ); +} +TEST_F(ApConfigUse_Test, CheckBandChannel_3) +{ + HotspotConfig apConfig; + ChannelsTable ChannelsTb; + pApConfigUse->CheckBandChannel(apConfig, ChannelsTb); + EXPECT_EQ(apConfig.GetChannel(), 6); + EXPECT_EQ(apConfig.GetBand(), BandType::BAND_2GHZ); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_idle_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_idle_state_test.cpp new file mode 100644 index 000000000..73a20c24d --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_idle_state_test.cpp @@ -0,0 +1,93 @@ +/* + * 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 "ap_define.h" +#include "ap_idle_state.h" +#include "mock_pendant.h" +#include "mock_wifi_ap_hal_interface.h" + +using namespace OHOS; +using ::testing::_; +using ::testing::Return; + +namespace OHOS { +namespace Wifi { +class ApIdleState_test : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockPendant = new MockPendant(); + + pMockPendant->GetMockApStateMachine().InitialStateMachine(); + pApIdleState = new ApIdleState(pMockPendant->GetMockApStateMachine()); + } + virtual void TearDown() + { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + delete pApIdleState; + pApIdleState = nullptr; + delete pMockPendant; + pMockPendant = nullptr; + } + +public: + MockPendant *pMockPendant; + ApIdleState *pApIdleState; +}; + +TEST_F(ApIdleState_test, ExecuteStateMsg_SUCCESS) +{ + InternalMessage *msg = new InternalMessage(); + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_UPDATE_HOTSPOTCONFIG_RESULT)); + EXPECT_TRUE(pApIdleState->ExecuteStateMsg(msg)); + + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_START_HOTSPOT)); + EXPECT_TRUE(pApIdleState->ExecuteStateMsg(msg)); + delete msg; +} + +TEST_F(ApIdleState_test, ExecuteStateMsg_FAILED) +{ + InternalMessage *msg = new InternalMessage(); + + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_SET_HOTSPOT_CONFIG)); + EXPECT_FALSE(pApIdleState->ExecuteStateMsg(msg)); + + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_DISCONNECT_STATION)); + EXPECT_FALSE(pApIdleState->ExecuteStateMsg(msg)); + + msg = nullptr; + EXPECT_FALSE(pApIdleState->ExecuteStateMsg(msg)); + + delete msg; +} + +TEST_F(ApIdleState_test, GoInState) +{ + pApIdleState->GoInState(); +} +TEST_F(ApIdleState_test, GoOutState) +{ + pApIdleState->GoOutState(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_monitor_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_monitor_test.cpp new file mode 100644 index 000000000..dcef929cc --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_monitor_test.cpp @@ -0,0 +1,128 @@ +/* + * 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 "ap_monitor.h" +#include "operator_overload.h" +#include "mock_wifi_ap_hal_interface.h" + +using namespace OHOS; +using ::testing::_; +using ::testing::An; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::TypedEq; + +namespace OHOS { +namespace Wifi { +const std::string Mac = "AA:BB:CC:DD:EE:FF"; +StationInfo staInfo = { + "test_deviceName", + Mac.c_str(), + "127.0.0.1", +}; +const int AP_ENABLE = 109; +const int AP_DISABLE = 110; +const int AP_FAILED = 111; +class ApMonitor_Test : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pApMonitor = new ApMonitor(); + } + virtual void TearDown() + { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + delete pApMonitor; + } + +public: + void WraUnregisterHandler(const std::string &iface) + { + pApMonitor->UnregisterHandler(iface); + return; + } + +public: + ApMonitor *pApMonitor; +}; + +/* StationChangeEvent */ + +TEST_F(ApMonitor_Test, StationChangeEvent_JOIN) +{ + const int type = 105; + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + pApMonitor->StartMonitor(); + WifiApConnectionNofify cInfo; + cInfo.type = type; + cInfo.mac = "AA:BB:CC:DD:EE:FF"; + pApMonitor->OnStaJoinOrLeave(cInfo); +} +TEST_F(ApMonitor_Test, StationChangeEvent_LEAVE) +{ + const int type = 106; + WifiApConnectionNofify cInfo; + cInfo.type = type; + cInfo.mac = "AA:BB:CC:DD:EE:FF"; + pApMonitor->OnStaJoinOrLeave(cInfo); +} +TEST_F(ApMonitor_Test, StationChangeEvent_NULL) +{ + WifiApConnectionNofify cInfo; + pApMonitor->OnStaJoinOrLeave(cInfo); +} +/* OnHotspotStateEvent */ +TEST_F(ApMonitor_Test, OnHotspotStateEvent_ENABLE) +{ + pApMonitor->OnHotspotStateEvent(AP_ENABLE); +} + +TEST_F(ApMonitor_Test, OnHotspotStateEvent_DISABLE) +{ + pApMonitor->OnHotspotStateEvent(AP_DISABLE); +} +TEST_F(ApMonitor_Test, OnHotspotStateEvent_FAILED) +{ + pApMonitor->OnHotspotStateEvent(AP_FAILED); +} + +/* StartMonitor */ +TEST_F(ApMonitor_Test, StartMonitor_SUCCESS) +{ + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + pApMonitor->StartMonitor(); +} + +/* StopMonitor */ +TEST_F(ApMonitor_Test, StopMonitor_SUCCESS) +{ + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(An())) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + pApMonitor->StopMonitor(); +} +/* UnregisterHandler */ +TEST_F(ApMonitor_Test, UnregisterHandler_SUCCESS) +{ + WraUnregisterHandler("wlan1"); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_root_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_root_state_test.cpp new file mode 100644 index 000000000..907b1744b --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_root_state_test.cpp @@ -0,0 +1,77 @@ +/* + * 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 "ap_define.h" +#include "mock_ap_state_machine.h" +#include "ap_root_state.h" + +using namespace OHOS; + +namespace OHOS { +namespace Wifi { +class ApRootState_test : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pApRootState = new ApRootState(); + } + virtual void TearDown() + { + delete pApRootState; + } + +public: + ApRootState *pApRootState; +}; + +TEST_F(ApRootState_test, ExecuteStateMsg_SUCCESS) +{ + InternalMessage *msg = new InternalMessage(); + + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_UPDATE_HOTSPOTCONFIG_RESULT)); + EXPECT_TRUE(pApRootState->ExecuteStateMsg(msg)); + + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_START_HOTSPOT)); + EXPECT_TRUE(pApRootState->ExecuteStateMsg(msg)); + + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_SET_HOTSPOT_CONFIG)); + EXPECT_TRUE(pApRootState->ExecuteStateMsg(msg)); + + delete msg; +} + +TEST_F(ApRootState_test, ExecuteStateMsg_FAILED) +{ + InternalMessage *msg = nullptr; + EXPECT_FALSE(pApRootState->ExecuteStateMsg(msg)); +} + +TEST_F(ApRootState_test, GoInState) +{ + pApRootState->GoInState(); +} +TEST_F(ApRootState_test, GoOutState) +{ + pApRootState->GoOutState(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_service_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_service_test.cpp new file mode 100644 index 000000000..745f1eab2 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_service_test.cpp @@ -0,0 +1,171 @@ +/* + * 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 "ap_service.h" +#include "mock_wifi_settings.h" +#include "mock_pendant.h" +#include "operator_overload.h" +#include "mock_wifi_ap_hal_interface.h" +#include "i_ap_service_callbacks.h" + +using namespace OHOS; +using ::testing::_; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::StrEq; +using ::testing::TypedEq; + +namespace OHOS { +namespace Wifi { +const StationInfo staInfo = { + "test_deviceName", + "AA:BB:CC:DD:EE:FF", + "127.0.0.1", +}; +class ApService_test : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockPendant = new MockPendant(); + pApStateMachine = &(pMockPendant->GetMockApStateMachine()); + pApStateMachine->InitialStateMachine(); + pApService = new ApService(*pApStateMachine); + + const int testMaxConn = 10; + const int channel = 6; + apInfo.SetSsid(std::string("TEST")); + apInfo.SetPreSharedKey(std::string("123456789")); + apInfo.SetSecurityType(KeyMgmt::WPA2_PSK); + apInfo.SetBand(BandType::BAND_2GHZ); + apInfo.SetChannel(channel); + apInfo.SetMaxConn(testMaxConn); + } + virtual void TearDown() + { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + delete pApService; + pApService = nullptr; + delete pMockPendant; + pMockPendant = nullptr; + } + +public: + ErrCode WarpRegisterApServiceCallbacks(const IApServiceCallbacks &callbacks) + { + return pApService->RegisterApServiceCallbacks(callbacks); + } + +public: + MockPendant *pMockPendant; + MockApStateMachine *pApStateMachine; + ApService *pApService; + HotspotConfig apInfo; +}; +/* EnableHotspot */ +TEST_F(ApService_test, EnableHotspot_SUCCESS) +{ + EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->EnableHotspot()); +} +/* DisableHotspot */ +TEST_F(ApService_test, DisableHotspotSUCCESS) +{ + EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->DisableHotspot()); +} +/* SetHotspotConfig */ +TEST_F(ApService_test, SetHotspotConfig_SUCCESS) +{ + EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->SetHotspotConfig(apInfo)); +} +/* AddBlockList */ +TEST_F(ApService_test, AddBlockList_SUCCESS) +{ + EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->AddBlockList(staInfo)); +} +/* DelBlockList */ +TEST_F(ApService_test, DelBlockList_SUCCESS) +{ + EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->DelBlockList(staInfo)); +} +/* DisconnetStation */ +TEST_F(ApService_test, DisconnetStation_SUCCESS) +{ + EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->DisconnetStation(staInfo)); +} + +/* GetValidBands */ +TEST_F(ApService_test, GetValidBands_SUCCESS) +{ + std::vector vecSta; + std::vector temp = { + BandType::BAND_2GHZ, + BandType::BAND_5GHZ, + }; + + EXPECT_CALL(WifiSettings::GetInstance(), GetValidBands(Eq(vecSta))) + .WillOnce(DoAll(SetArgReferee<0>(temp), Return(0))); + EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->GetValidBands(vecSta)); + EXPECT_EQ(temp, vecSta); +} +TEST_F(ApService_test, GetValidBands_FAILED) +{ + std::vector vecSta; + std::vector temp = { + BandType::BAND_2GHZ, + BandType::BAND_5GHZ, + }; + + EXPECT_CALL(WifiSettings::GetInstance(), GetValidBands(Eq(vecSta))) + .WillOnce(DoAll(SetArgReferee<0>(temp), Return(-1))); + EXPECT_EQ(ErrCode::WIFI_OPT_FAILED, pApService->GetValidBands(vecSta)); +} + +/* GetValidChannels */ +TEST_F(ApService_test, GetValidChannels_SUCCESS) +{ + std::vector vecChannels; + std::vector band_2G_channel = {1, 2, 3, 4, 5, 6, 7}; + std::vector band_5G_channel = {149, 168, 169}; + ChannelsTable temp = {{BandType::BAND_2GHZ, band_2G_channel}, {BandType::BAND_5GHZ, band_5G_channel}}; + + EXPECT_CALL(WifiSettings::GetInstance(), GetValidChannels(_)).WillOnce(DoAll(SetArgReferee<0>(temp), Return(0))); + EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->GetValidChannels(BandType::BAND_2GHZ, vecChannels)); + EXPECT_EQ(vecChannels, band_2G_channel); + vecChannels.clear(); + + EXPECT_CALL(WifiSettings::GetInstance(), GetValidChannels(_)).WillOnce(DoAll(SetArgReferee<0>(temp), Return(0))); + EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->GetValidChannels(BandType::BAND_5GHZ, vecChannels)); + EXPECT_EQ(vecChannels, band_5G_channel); + vecChannels.clear(); + + EXPECT_CALL(WifiSettings::GetInstance(), GetValidChannels(_)).WillOnce(DoAll(SetArgReferee<0>(temp), Return(1))); + EXPECT_EQ(ErrCode::WIFI_OPT_FAILED, pApService->GetValidChannels(BandType::BAND_5GHZ, vecChannels)); +} + +/* RegisterApServiceCallbacks */ +TEST_F(ApService_test, RegisterApServiceCallbacks_SUCCESS) +{ + IApServiceCallbacks callbacks; + EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, WarpRegisterApServiceCallbacks(callbacks)); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_started_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_started_state_test.cpp new file mode 100644 index 000000000..8412fe097 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_started_state_test.cpp @@ -0,0 +1,462 @@ +/* + * 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 "ap_define.h" +#include "ap_started_state.h" + +#include "mock_pendant.h" + +#include "mock_wifi_ap_hal_interface.h" +#include "mock_wifi_ap_nat_manager.h" +#include "mock_wifi_settings.h" +#include "mock_network_interface.h" +#include "mock_system_interface.h" + +#include "mock_ap_monitor.h" +#include "operator_overload.h" +#include "wifi_log.h" + +using ::testing::_; +using ::testing::A; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::StrEq; + +namespace OHOS { +namespace Wifi { +const std::string mac = "AA:BB:CC:DD:EE:FF"; +static StationInfo staInfo = { + "test_deviceName", + mac.c_str(), + "127.0.0.1", +}; + +HotspotConfig apcfg; +ChannelsTable channelTbs; +const int TEST_AP_CHANNEL = 6; +const int TEST_MAX_CONN = 10; + +std::vector valueList = { + { + "test_deviceName", + "DA:BB:CC:DD:EE:FF", + "127.0.0.3", + }, + { + "test_deviceName", + "DA:BB:CC:DD:EE:FF", + "127.0.0.3", + }, +}; + +class ApStartedState_test : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + WifiSettings::GetInstance(); + WifiApHalInterface::GetInstance(); + + pMockPendant = new MockPendant(); + pMockApMonitor = &(pMockPendant->GetMockApMonitor()); + pMockApStationsManager = &(pMockPendant->GetMockApStationsManager()); + pMockApStateMachine = &(pMockPendant->GetMockApStateMachine()); + pMockApConfigUse = &(pMockPendant->GetMockApConfigUse()); + pMockApStateMachine->InitialStateMachine(); + pMockApNatManager = new MockWifiApNatManager(); + + pApStartedState = new ApStartedState(*pMockApStateMachine, *pMockApConfigUse, *pMockApMonitor); + + msg = new InternalMessage(); + apcfg.SetSsid(std::string("UnitTestAp")); + apcfg.SetPreSharedKey(std::string("123456789")); + apcfg.SetSecurityType(KeyMgmt::WPA2_PSK); + apcfg.SetBand(BandType::BAND_2GHZ); + apcfg.SetChannel(TEST_AP_CHANNEL); + apcfg.SetMaxConn(TEST_MAX_CONN); + WrapHotspotConfig() = apcfg; + + std::vector band_2G_channel = {1, 2, 3, 4, 5, 6, 7}; + std::vector band_5G_channel = {149, 168, 169}; + channelTbs = {{BandType::BAND_2GHZ, band_2G_channel}, {BandType::BAND_5GHZ, band_5G_channel}}; + } + virtual void TearDown() + { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + delete pApStartedState; + + delete pMockPendant; + + pApStartedState = nullptr; + + pMockPendant = nullptr; + pMockApStateMachine = nullptr; + pMockApConfigUse = nullptr; + pMockApMonitor = nullptr; + pMockApStationsManager = nullptr; + + delete pMockApNatManager; + pMockApNatManager = nullptr; + + delete msg; + } + +public: + bool WrapStartAp() const + { + return pApStartedState->StartAp(); + } + bool WrapStopAp() const + { + return WrapStartAp(); + } + bool WrapSetConfig(HotspotConfig &apConfig) + { + return pApStartedState->SetConfig(apConfig); + } + bool WrapSetConfig() const + { + return pApStartedState->SetConfig(); + } + void WrapOnApStateChange(const ApState &state) + { + pApStartedState->OnApStateChange(state); + } + void WrapStartMonitor() const + { + pApStartedState->StartMonitor(); + } + void WrapStopMonitor() const + { + pApStartedState->StopMonitor(); + } + bool WrapStartDhcpServer() const + { + return pMockApStateMachine->StartDhcpServer(); + } + bool WrapStopDhcpServer() const + { + return pMockApStateMachine->StopDhcpServer(); + } + bool WrapEnableInterfaceNat() const + { + return pApStartedState->EnableInterfaceNat(); + } + bool WrapDisableInterfaceNat() const + { + return pApStartedState->DisableInterfaceNat(); + } + +public: + void WrapProcessCmdFail(InternalMessage &message) + { + pApStartedState->ProcessCmdFail(message); + } + void WrapProcessCmdStationJoin(InternalMessage &message) + { + pApStartedState->ProcessCmdStationJoin(message); + } + void WrapProcessCmdStationLeave(InternalMessage &message) + { + pApStartedState->ProcessCmdStationLeave(message); + } + void WrapProcessCmdSetHotspotConfig(InternalMessage &message) + { + pApStartedState->ProcessCmdSetHotspotConfig(message); + } + void WrapProcessCmdUpdateConfigResult(InternalMessage &message) + { + pApStartedState->ProcessCmdUpdateConfigResult(message); + } + void WrapProcessCmdAddBlockList(InternalMessage &message) + { + pApStartedState->ProcessCmdAddBlockList(message); + } + void WrapProcessCmdDelBlockList(InternalMessage &message) + { + pApStartedState->ProcessCmdDelBlockList(message); + } + void WrapProcessCmdStopHotspot(InternalMessage &message) + { + pApStartedState->ProcessCmdStopHotspot(message); + } + void WrapProcessCmdDisconnectStation(InternalMessage &message) + { + pApStartedState->ProcessCmdDisconnectStation(message); + } + +public: + HotspotConfig &WrapHotspotConfig() + { + return pApStartedState->m_hotspotConfig; + } + +public: + InternalMessage *msg; + + ApStartedState *pApStartedState; + + MockPendant *pMockPendant; + + MockApStationsManager *pMockApStationsManager; + MockApStateMachine *pMockApStateMachine; + MockApMonitor *pMockApMonitor; + MockApConfigUse *pMockApConfigUse; + MockWifiApNatManager *pMockApNatManager; +}; +TEST_F(ApStartedState_test, GoInState_SUCCESS) +{ + std::vector results; + EXPECT_CALL(MockNetworkInterface::GetInstance(), FetchIpAddress(_, _, _)).WillRepeatedly(Return(true)); + EXPECT_CALL(MockNetworkInterface::GetInstance(), AddIpAddress(_, _)).WillRepeatedly(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(A())).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiApHalInterface::GetInstance(), StartAp()).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + std::string countryCode = "CN"; + EXPECT_CALL(WifiSettings::GetInstance(), GetCountryCode(Eq(""))) + .WillRepeatedly(DoAll(testing::SetArgReferee<0>(countryCode), Return(0))); + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetWifiCountryCode(Eq(countryCode))) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), GetHotspotConfig(A())) + .WillRepeatedly(DoAll(SetArgReferee<0>(apcfg), Return(0))); + EXPECT_CALL(WifiApHalInterface::GetInstance(), GetFrequenciesByBand(_, _)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SetValidChannels(_)).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg))) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(*pMockApStateMachine, StartDhcpServer()).WillRepeatedly(Return(true)); + EXPECT_CALL(*pMockApNatManager, EnableInterfaceNat(Eq(true), StrEq(IN_INTERFACE), StrEq(OUT_INTERFACE))) + .WillRepeatedly(Return(true)); + EXPECT_CALL(*pMockApConfigUse, TransformFrequencyIntoChannel(_, _)).WillRepeatedly(Return()); + EXPECT_CALL(*pMockApMonitor, StartMonitor()).WillRepeatedly(Return()); + EXPECT_CALL(*pMockApConfigUse, CheckBandChannel(Eq(apcfg), _)).WillRepeatedly(Return()); + EXPECT_CALL(*pMockApConfigUse, LogConfig(Eq(apcfg))).WillRepeatedly(Return()); + EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(results))) + .WillRepeatedly(DoAll(SetArgReferee<0>(valueList), Return(ErrCode::WIFI_OPT_SUCCESS))); + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(StrEq("DA:BB:CC:DD:EE:FF"))) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + pApStartedState->GoInState(); +} +TEST_F(ApStartedState_test, GoInState_FAILED1) +{ + std::vector results; + EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(A())).WillRepeatedly(Return(0)); + EXPECT_CALL(*pMockApMonitor, StartMonitor()).WillRepeatedly(Return()); + EXPECT_CALL(WifiApHalInterface::GetInstance(), StartAp()).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pApStartedState->GoInState(); + + EXPECT_CALL(WifiApHalInterface::GetInstance(), StartAp()).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), GetCountryCode(StrEq(""))).WillRepeatedly(Return(1)); + pApStartedState->GoInState(); + + EXPECT_CALL(WifiSettings::GetInstance(), GetCountryCode(StrEq(""))) + .WillRepeatedly(DoAll(SetArgReferee<0>("CN"), Return(0))); + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetWifiCountryCode(StrEq("CN"))) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pApStartedState->GoInState(); + + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetWifiCountryCode(StrEq("CN"))) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), GetHotspotConfig(A())).WillRepeatedly(Return(1)); + pApStartedState->GoInState(); + + EXPECT_CALL(WifiSettings::GetInstance(), GetHotspotConfig(A())) + .WillRepeatedly(DoAll(SetArgReferee<0>(apcfg), Return(0))); + EXPECT_CALL(WifiApHalInterface::GetInstance(), GetFrequenciesByBand(_, _)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(*pMockApConfigUse, TransformFrequencyIntoChannel(_, _)).WillRepeatedly(Return()); + EXPECT_CALL(WifiSettings::GetInstance(), SetValidChannels(_)).WillRepeatedly(Return(1)); + pApStartedState->GoInState(); + + EXPECT_CALL(WifiSettings::GetInstance(), SetValidChannels(_)).WillRepeatedly(Return(0)); + EXPECT_CALL(*pMockApConfigUse, CheckBandChannel(_, _)).WillRepeatedly(Return()); + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg))) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pApStartedState->GoInState(); + + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg))) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(*pMockApConfigUse, LogConfig(Eq(apcfg))).WillRepeatedly(Return()); + EXPECT_CALL(*pMockApStateMachine, StartDhcpServer()).WillRepeatedly(Return(false)); + pApStartedState->GoInState(); + + EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(results))) + .WillRepeatedly(DoAll(SetArgReferee<0>(valueList), Return(ErrCode::WIFI_OPT_FAILED))); + pApStartedState->GoInState(); + + EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(results))) + .WillRepeatedly(DoAll(SetArgReferee<0>(valueList), Return(ErrCode::WIFI_OPT_SUCCESS))); + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(StrEq("DA:BB:CC:DD:EE:FF"))) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + pApStartedState->GoInState(); + + EXPECT_CALL(WifiSettings::GetInstance(), GetHotspotConfig(A())).WillRepeatedly(Return(1)); + EXPECT_CALL(*pMockApStateMachine, StartDhcpServer()).WillRepeatedly(Return(true)); + EXPECT_CALL(*pMockApNatManager, EnableInterfaceNat(_, _, _)).WillRepeatedly(Return(false)); + pApStartedState->GoInState(); +} +TEST_F(ApStartedState_test, GoOutState_SUCCESS) +{ + EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillRepeatedly(Return(true)); + + EXPECT_CALL(MockNetworkInterface::GetInstance(), IsValidInterfaceName(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(MockNetworkInterface::GetInstance(), ClearAllIpAddress(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(A())).WillRepeatedly(Return(0)); + EXPECT_CALL(*pMockApNatManager, EnableInterfaceNat(Eq(false), _, _)).WillRepeatedly(Return(true)); + EXPECT_CALL(*pMockApStateMachine, StopDhcpServer()).WillRepeatedly(Return(true)); + EXPECT_CALL(WifiApHalInterface::GetInstance(), StopAp()).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), ClearStationList()).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ClearValidChannels()).WillRepeatedly(Return(0)); + EXPECT_CALL(*pMockApMonitor, StopMonitor()).WillRepeatedly(Return()); + pApStartedState->GoOutState(); +} +TEST_F(ApStartedState_test, GoOutState_FAILED) +{ + EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(A())).WillRepeatedly(Return(0)); + EXPECT_CALL(*pMockApNatManager, EnableInterfaceNat(Eq(false), _, _)).WillRepeatedly(Return(false)); + EXPECT_CALL(*pMockApStateMachine, StopDhcpServer()).WillRepeatedly(Return(false)); + EXPECT_CALL(WifiApHalInterface::GetInstance(), StopAp()).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiSettings::GetInstance(), ClearStationList()).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ClearValidChannels()).WillRepeatedly(Return(0)); + EXPECT_CALL(*pMockApMonitor, StopMonitor()).WillRepeatedly(Return()); + pApStartedState->GoOutState(); +} +TEST_F(ApStartedState_test, ExecuteStateMsg_SUCCESS) +{ + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_FAIL)); + EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); + + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(_)).WillRepeatedly(Return(ErrCode::WIFI_OPT_FAILED)); + msg->ClearMessageBody(); + StationInfo staInfo; + msg->SetMessageObj(staInfo); + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_STATION_JOIN)); + msg->AddStringMessageBody(staInfo.deviceName); + msg->AddStringMessageBody(staInfo.bssid); + msg->AddStringMessageBody(staInfo.ipAddr); + EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); + + msg->ClearMessageBody(); + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_STATION_LEAVE)); + msg->AddStringMessageBody(staInfo.deviceName); + msg->AddStringMessageBody(staInfo.bssid); + msg->AddStringMessageBody(staInfo.ipAddr); + EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); + + msg->ClearMessageBody(); + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_SET_HOTSPOT_CONFIG)); + msg->AddStringMessageBody(apcfg.GetSsid()); + msg->AddStringMessageBody(apcfg.GetPreSharedKey()); + msg->AddIntMessageBody(static_cast(apcfg.GetSecurityType())); + msg->AddIntMessageBody(static_cast(apcfg.GetBand())); + msg->AddIntMessageBody(apcfg.GetChannel()); + msg->AddIntMessageBody(apcfg.GetMaxConn()); + + EXPECT_CALL(*pMockApConfigUse, LogConfig(Eq(apcfg))).WillRepeatedly(Return()); + EXPECT_CALL(WifiApHalInterface::GetInstance(), GetFrequenciesByBand(_, _)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(*pMockApConfigUse, TransformFrequencyIntoChannel(_, _)).WillRepeatedly(Return()); + EXPECT_CALL(WifiSettings::GetInstance(), SetValidChannels(_)).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg))) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(*pMockApConfigUse, CheckBandChannel(Eq(apcfg), _)).WillRepeatedly(Return()); + EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); + + msg->ClearMessageBody(); + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_SET_HOTSPOT_CONFIG)); + msg->AddStringMessageBody(apcfg.GetSsid()); + msg->AddStringMessageBody(apcfg.GetPreSharedKey()); + msg->AddIntMessageBody(static_cast(apcfg.GetSecurityType())); + msg->AddIntMessageBody(static_cast(apcfg.GetBand())); + msg->AddIntMessageBody(apcfg.GetChannel()); + msg->AddIntMessageBody(apcfg.GetMaxConn()); + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg))) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); +} + +TEST_F(ApStartedState_test, ExecuteStateMsg_SUCCESS2) +{ + msg->ClearMessageBody(); + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_UPDATE_HOTSPOTCONFIG_RESULT)); + msg->AddStringMessageBody(apcfg.GetSsid()); + msg->AddStringMessageBody(apcfg.GetPreSharedKey()); + msg->AddIntMessageBody(static_cast(apcfg.GetSecurityType())); + msg->AddIntMessageBody(static_cast(apcfg.GetBand())); + msg->AddIntMessageBody(apcfg.GetChannel()); + msg->AddIntMessageBody(apcfg.GetMaxConn()); + msg->SetParam1(1); + EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotConfig(Eq(apcfg))).WillRepeatedly(Return(1)); + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_UPDATE_HOTSPOTCONFIG_RESULT)); + + EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); + msg->SetParam1(0); + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_UPDATE_HOTSPOTCONFIG_RESULT)); + EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); + + msg->ClearMessageBody(); + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_ADD_BLOCK_LIST)); + msg->AddStringMessageBody(apcfg.GetSsid()); + msg->AddStringMessageBody(apcfg.GetPreSharedKey()); + msg->AddIntMessageBody(static_cast(apcfg.GetSecurityType())); + msg->AddIntMessageBody(static_cast(apcfg.GetBand())); + msg->AddIntMessageBody(apcfg.GetChannel()); + msg->AddIntMessageBody(apcfg.GetMaxConn()); + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(Eq(staInfo.bssid))) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + msg->ClearMessageBody(); + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_ADD_BLOCK_LIST)); + msg->AddStringMessageBody(staInfo.deviceName); + msg->AddStringMessageBody(staInfo.bssid); + msg->AddStringMessageBody(staInfo.ipAddr); + EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); + + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_DEL_BLOCK_LIST)); + msg->AddStringMessageBody(staInfo.deviceName); + msg->AddStringMessageBody(staInfo.bssid); + msg->AddStringMessageBody(staInfo.ipAddr); + EXPECT_CALL(WifiApHalInterface::GetInstance(), DelBlockByMac(Eq(staInfo.bssid))) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_STOP_HOTSPOT)); + EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); + + msg->ClearMessageBody(); + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_DISCONNECT_STATION)); + msg->AddStringMessageBody(staInfo.deviceName); + msg->AddStringMessageBody(staInfo.bssid); + msg->AddStringMessageBody(staInfo.ipAddr); + EXPECT_CALL(WifiApHalInterface::GetInstance(), DisconnectStaByMac(Eq(staInfo.bssid))) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); +} +TEST_F(ApStartedState_test, ExecuteStateMsg_FAILED) +{ + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_START_HOTSPOT)); + EXPECT_FALSE(pApStartedState->ExecuteStateMsg(msg)); + + msg = nullptr; + EXPECT_FALSE(pApStartedState->ExecuteStateMsg(msg)); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_state_machine_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_state_machine_test.cpp new file mode 100644 index 000000000..da1621e7c --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_state_machine_test.cpp @@ -0,0 +1,170 @@ +/* + * 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 "ap_define.h" +#include "ap_state_machine.h" +#include "wifi_log.h" +#include "mock_wifi_settings.h" +#include "mock_pendant.h" +#include "mock_wifi_ap_hal_interface.h" +#include "operator_overload.h" + +using ::testing::_; +using ::testing::Eq; +using ::testing::Return; +namespace OHOS { +namespace Wifi { +class ApStateMachine_test : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockPendant = new MockPendant(); + pMockApStationsManager = &(pMockPendant->GetMockApStationsManager()); + pMockApRootState = &(pMockPendant->GetMockApRootState()); + pMockApIdleState = &(pMockPendant->GetMockApIdleState()); + pMockApStartedState = &(pMockPendant->GetMockApStartedState()); + pMockApMonitor = &(pMockPendant->GetMockApMonitor()); + + pMockPendant->GetMockApStateMachine().InitialStateMachine(); + + pApStateMachine = new ApStateMachine( + *pMockApStationsManager, *pMockApRootState, *pMockApIdleState, *pMockApStartedState, *pMockApMonitor); + + pApStateMachine->InitialStateMachine(); + RegisterApServiceCallbacks(); + } + virtual void TearDown() + { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + delete pApStateMachine; + + delete pMockPendant; + pMockPendant = nullptr; + pApStateMachine = nullptr; + pMockApStationsManager = nullptr; + pMockApRootState = nullptr; + pMockApIdleState = nullptr; + pMockApStartedState = nullptr; + pMockApMonitor = nullptr; + } + +public: + ErrCode RegisterApServiceCallbacks() + { + std::function OnStationEvent = [&](const StationInfo &sta) { m_sta = sta; }; + + IApServiceCallbacks callbacks = {[&](ApState state) { mBState = state; }, OnStationEvent, OnStationEvent}; + return pApStateMachine->RegisterApServiceCallbacks(callbacks); + } + ErrCode UnRegisterApServiceCallbacks() + { + IApServiceCallbacks callbacks; + return pApStateMachine->RegisterApServiceCallbacks(callbacks); + } + +public: + void WrapOnApStateChange(ApState state) + { + EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(Eq(static_cast(state)))).WillOnce(Return(0)); + pApStateMachine->OnApStateChange(state); + } + void WrapOnApStateChangeFail(ApState state) + { + EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(Eq(static_cast(state)))).WillOnce(Return(1)); + pApStateMachine->OnApStateChange(state); + } + + void WrapBroadCastStationJoin(const StationInfo &staInfo) + { + pApStateMachine->BroadCastStationChange(staInfo, ApStatemachineEvent::CMD_STATION_JOIN); + } + + void WrapBroadCastStationLeave(const StationInfo &staInfo) + { + pApStateMachine->BroadCastStationChange(staInfo, ApStatemachineEvent::CMD_STATION_LEAVE); + } + void WrapBroadCastStationChangeDefult(const StationInfo &staInfo) + { + pApStateMachine->BroadCastStationChange(staInfo, ApStatemachineEvent::CMD_START_HOTSPOT); + } + void WarpRegisterEventHandler() const + { + pApStateMachine->RegisterEventHandler(); + } + +public: + MockPendant *pMockPendant; + MockApStationsManager *pMockApStationsManager; + MockApRootState *pMockApRootState; + MockApIdleState *pMockApIdleState; + MockApStartedState *pMockApStartedState; + MockApMonitor *pMockApMonitor; + + ApStateMachine *pApStateMachine; + ApState mBState; + StationInfo m_sta; +}; +TEST_F(ApStateMachine_test, OnApStateChange) +{ + ApState BroadState = ApState::AP_STATE_IDLE; + WrapOnApStateChange(BroadState); + + BroadState = ApState::AP_STATE_STARTING; + WrapOnApStateChange(BroadState); + + BroadState = ApState::AP_STATE_STARTED; + WrapOnApStateChange(BroadState); + + BroadState = ApState::AP_STATE_CLOSING; + WrapOnApStateChange(BroadState); + + BroadState = ApState::AP_STATE_CLOSED; + WrapOnApStateChange(BroadState); + + BroadState = ApState::AP_STATE_CLOSED; + WrapOnApStateChangeFail(BroadState); +} + +TEST_F(ApStateMachine_test, BroadCastStationJoin) +{ + const StationInfo BroadCastStation = {"test1", "aa:bb:cc:dd:ee:ff", "127.0.0.1"}; + WrapBroadCastStationJoin(BroadCastStation); + EXPECT_EQ(BroadCastStation, m_sta); +} + +TEST_F(ApStateMachine_test, BroadCastStationLeave) +{ + const StationInfo BroadCastStation = {"test1", "aa:bb:cc:dd:ee:ff", "127.0.0.1"}; + WrapBroadCastStationLeave(BroadCastStation); + EXPECT_EQ(BroadCastStation, m_sta); +} +TEST_F(ApStateMachine_test, BroadCastStationChange_DEFAULT) +{ + const StationInfo BroadCastStation = {"test1", "aa:bb:cc:dd:ee:ff", "127.0.0.1"}; + WrapBroadCastStationChangeDefult(BroadCastStation); +} +TEST_F(ApStateMachine_test, RegisterEventHandler) +{ + WarpRegisterEventHandler(); +} +} // namespace Wifi +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_stations_manager_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_stations_manager_test.cpp new file mode 100644 index 000000000..13e3ef82d --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_stations_manager_test.cpp @@ -0,0 +1,352 @@ +/* + * 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 "mock_wifi_ap_hal_interface.h" +#include "mock_ap_service.h" +#include "mock_wifi_settings.h" +#include "operator_overload.h" + +#include "ap_stations_manager.h" + +using namespace OHOS; +using ::testing::_; +using ::testing::An; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::StrEq; + +namespace OHOS { +namespace Wifi { +const std::string Mac = "AA:BB:CC:DD:EE:FF"; +static StationInfo staInfo = { + "test_deviceName", + Mac.c_str(), + "127.0.0.1", +}; +StationInfo value1 = { + "test_deviceName", + "AA:BB:CC:DD:EE:FF", + "127.0.0.2", +}; +StationInfo value2 = { + "test_deviceName", + "AA:BB:CC:DD:EE:FF", + "127.0.0.3", +}; +class ApStationsManager_test : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pApStaMgr = new ApStationsManager(); + } + virtual void TearDown() + { + delete pApStaMgr; + pApStaMgr = nullptr; + } + +public: + bool WrapAddAssociationStation(const StationInfo &info) + { + return pApStaMgr->AddAssociationStation(info); + } + bool WrapDelAssociationStation(const StationInfo &info) + { + return pApStaMgr->DelAssociationStation(info); + } + +public: + ApStationsManager *pApStaMgr; +}; +/* AddBlockList */ +TEST_F(ApStationsManager_test, AddBlockList_SUCCESS) +{ + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(StrEq(staInfo.bssid))) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + + EXPECT_TRUE(pApStaMgr->AddBlockList(staInfo)); +} +TEST_F(ApStationsManager_test, AddBlockList_FAILED) +{ + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(StrEq(staInfo.bssid))) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + + EXPECT_FALSE(pApStaMgr->AddBlockList(staInfo)); +} + +/* DelBlockList */ +TEST_F(ApStationsManager_test, DelBlockList_SUCCESS) +{ + EXPECT_CALL(WifiApHalInterface::GetInstance(), DelBlockByMac(StrEq(staInfo.bssid))) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + + EXPECT_TRUE(pApStaMgr->DelBlockList(staInfo)); +} +TEST_F(ApStationsManager_test, DelBlockList_FAILED) +{ + EXPECT_CALL(WifiApHalInterface::GetInstance(), DelBlockByMac(StrEq(staInfo.bssid))) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + + EXPECT_FALSE(pApStaMgr->DelBlockList(staInfo)); +} + +/* EnableAllBlockList */ +TEST_F(ApStationsManager_test, EnableAllBlockList_SUCCESS) +{ + std::vector value; + std::vector valueCom; + value.push_back(value1); + value.push_back(value2); + EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(valueCom))) + .WillOnce(DoAll(testing::SetArgReferee<0>(value), Return(0))); + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(An())) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pApStaMgr->EnableAllBlockList()); +} +TEST_F(ApStationsManager_test, EnableAllBlockList_FAILED0) +{ + std::vector value; + std::vector valueCom; + value.push_back(value1); + value.push_back(value2); + EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(valueCom))) + .WillOnce(DoAll(testing::SetArgReferee<0>(value), Return(-1))); + EXPECT_FALSE(pApStaMgr->EnableAllBlockList()); +} +TEST_F(ApStationsManager_test, EnableAllBlockList_FAILED1) +{ + std::vector value; + std::vector valueCom; + value.push_back(value1); + value.push_back(value2); + EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(valueCom)) + .WillOnce(DoAll(testing::SetArgReferee<0>(value), Return(0))); + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(An())) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_FALSE(pApStaMgr->EnableAllBlockList()); +} + +/* StationLeave */ +TEST_F(ApStationsManager_test, StationLeave) +{ + StationInfo value3 = { + "test_deviceName", + "DA:BB:CC:DD:EE:FF", + "127.0.0.3", + }; + std::vector valueList; + std::vector valueCom; + valueList.push_back(value2); + valueList.push_back(value1); + valueList.push_back(value3); + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value2), Eq(1))).WillOnce(Return(0)); + pApStaMgr->StationLeave(value1.bssid); +} +TEST_F(ApStationsManager_test, StationLeave1) +{ + std::vector valueList; + std::vector valueCom; + StationInfo value3 = { + "test_deviceName", + "DA:BB:CC:DD:EE:FF", + "127.0.0.3", + }; + valueList.push_back(value2); + valueList.push_back(value1); + valueList.push_back(value3); + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(1))); + pApStaMgr->StationLeave(value1.bssid); + EXPECT_STREQ("AA:BB:CC:DD:EE:FF", Mac.c_str()); +} +TEST_F(ApStationsManager_test, StationLeave2) +{ + std::vector valueList; + std::vector valueCom; + StationInfo value3 = { + "test_deviceName", + "DA:BB:CC:DD:EE:FF", + "127.0.0.3", + }; + valueList.push_back(value3); + valueList.push_back(value1); + valueList.push_back(value2); + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value1), Eq(1))).WillOnce(Return(1)); + pApStaMgr->StationLeave(value1.bssid); + EXPECT_STREQ("AA:BB:CC:DD:EE:FF", Mac.c_str()); +} + +/* StationJoin */ +TEST_F(ApStationsManager_test, StationJoin1) +{ + std::vector valueCom; + std::vector valueList; + StationInfo value3 = { + "test_deviceName", + "AA:BB:CC:DD:EE:FF", + "127.0.0.4", + }; + valueList.push_back(value2); + valueList.push_back(value1); + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(1))); + pApStaMgr->StationJoin(value3); +} +TEST_F(ApStationsManager_test, StationJoin2) +{ + std::vector valueList; + std::vector valueCom; + StationInfo value3 = { + "test_deviceName", + "DA:BB:CC:DD:EE:FF", + "127.0.0.4", + }; + valueList.push_back(value1); + valueList.push_back(value2); + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value3), 0)).WillOnce(Return(0)); + pApStaMgr->StationJoin(value3); +} +TEST_F(ApStationsManager_test, StationJoin3) +{ + std::vector valueList; + std::vector valueCom; + StationInfo value3 = { + "test_deviceName", + "AA:BB:CC:DD:EE:FF", + "127.0.0.4", + }; + valueList.push_back(value2); + valueList.push_back(value1); + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value3), 0)).WillOnce(Return(1)); + pApStaMgr->StationJoin(value3); +} +TEST_F(ApStationsManager_test, StationJoin4) +{ + std::vector valueList; + std::vector valueCom; + StationInfo value3 = { + "test_deviceName", + "AA:BB:CC:DD:EE:FF", + "127.0.0.4", + }; + valueList.push_back(value1); + valueList.push_back(value2); + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value3), 0)).WillOnce(Return(0)); + pApStaMgr->StationJoin(value3); +} +TEST_F(ApStationsManager_test, StationJoin5) +{ + std::vector valueList; + std::vector valueCom; + StationInfo value3 = { + OHOS::Wifi::GETTING_INFO, + "AA:BB:CC:DD:EE:FF", + OHOS::Wifi::GETTING_INFO, + }; + valueList.push_back(value1); + valueList.push_back(value2); + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value1), 0)).WillOnce(Return(0)); + pApStaMgr->StationJoin(value3); +} +/* DisConnectStation */ +TEST_F(ApStationsManager_test, DisConnectStion_SUCCESS) +{ + EXPECT_CALL(WifiApHalInterface::GetInstance(), DisconnectStaByMac(StrEq(Mac))) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + + EXPECT_TRUE(pApStaMgr->DisConnectStation(staInfo)); +} +TEST_F(ApStationsManager_test, DisConnectStion_FAILED) +{ + EXPECT_CALL(WifiApHalInterface::GetInstance(), DisconnectStaByMac(StrEq(Mac))) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + + EXPECT_FALSE(pApStaMgr->DisConnectStation(staInfo)); +} + +/* GetAllConnectedStations */ +TEST_F(ApStationsManager_test, GetAllConnectedStations_SUCCESS) +{ + std::vector staMacList; + std::vector staMacListCom; + std::string staMacList1 = "test_deviceName1"; + std::string staMacList2 = "test_deviceName2"; + staMacList.push_back(staMacList1); + staMacList.push_back(staMacList2); + EXPECT_CALL(WifiApHalInterface::GetInstance(), GetStationList(Eq(staMacListCom))) + .WillOnce(DoAll(testing::SetArgReferee<0>(staMacList), Return(WifiErrorNo::WIFI_IDL_OPT_OK))); + + EXPECT_EQ(staMacList, pApStaMgr->GetAllConnectedStations()); +} +TEST_F(ApStationsManager_test, GetAllConnectedStations_FAILED) +{ + std::vector staMacList; + std::vector staMacListCom; + std::string staMacList1 = "test_deviceName1"; + std::string staMacList2 = "test_deviceName2"; + staMacList.push_back(staMacList1); + staMacList.push_back(staMacList2); + EXPECT_CALL(WifiApHalInterface::GetInstance(), GetStationList(Eq(staMacListCom))) + .WillOnce(DoAll(testing::SetArgReferee<0>(staMacList), Return(WifiErrorNo::WIFI_IDL_OPT_FAILED))); + staMacList.erase(staMacList.begin()); + EXPECT_NE(staMacList, pApStaMgr->GetAllConnectedStations()); +} + +/* AddAssociationStation */ +TEST_F(ApStationsManager_test, AddAssociationStation_SUCCESS) +{ + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(staInfo), Eq(0))).WillOnce(Return(0)); + EXPECT_TRUE(WrapAddAssociationStation(staInfo)); +} +TEST_F(ApStationsManager_test, AddAssociationStation_FAILED) +{ + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(staInfo), Eq(0))).WillOnce(Return(-1)); + EXPECT_FALSE(WrapAddAssociationStation(staInfo)); +} + +/* DelAssociationStation */ +TEST_F(ApStationsManager_test, DelAssociationStation_SUCCESS) +{ + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(staInfo), Eq(1))).WillOnce(Return(0)); + EXPECT_TRUE(WrapDelAssociationStation(staInfo)); +} +TEST_F(ApStationsManager_test, DelAssociationStation_FAILED) +{ + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(staInfo), Eq(1))).WillOnce(Return(-1)); + EXPECT_FALSE(WrapDelAssociationStation(staInfo)); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/global_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/global_test.cpp new file mode 100644 index 000000000..e3d7891fd --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/global_test.cpp @@ -0,0 +1,23 @@ +/* + * 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 "global_test.h" +void GlobalTest::SetUp() +{ + printf("GlobalTest SetUp\n"); +} +void GlobalTest::TearDown() +{ + printf("GlobalTest TearDown\n"); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/global_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/global_test.h new file mode 100644 index 000000000..65afff0de --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/global_test.h @@ -0,0 +1,24 @@ +/* + * 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 GLOBAL_TEST_H +#define GLOBAL_TEST_H +#include +class GlobalTest : public testing::Environment { +public: + virtual void SetUp(); + virtual void TearDown(); +}; +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/wifi_ap_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/wifi_ap_test.cpp new file mode 100644 index 000000000..e2e4b1c03 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/wifi_ap_test.cpp @@ -0,0 +1,25 @@ +/* + * 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 "global_test.h" +#include + +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + testing::Environment *env = new GlobalTest(); + testing::AddGlobalTestEnvironment(env); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/BUILD.gn new file mode 100644 index 000000000..1dc4744aa --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/BUILD.gn @@ -0,0 +1,169 @@ +# 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. + +import("//build/test.gni") +SUBSYSTEM_DIR = "//foundation/communication" +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test", + ] +} + +ohos_unittest("wifi_p2p_test") { + module_out_path = "wifi_standard/p2p_test" + sources = [ + "./Mock/mock_wifi_p2p_hal_interface.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_received_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_request_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_default_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabled_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabling_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabling_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_formation_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_info.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_request.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_response.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_txt_record.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_manager.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_request_list.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_response_list.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_temp_disc_event.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_request.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_response.cpp", + "authorizing_negotiation_request_state_test.cpp", + "group_formed_state_test.cpp", + "group_negotiation_state_test.cpp", + "invitation_recelved_state_test.cpp", + "invitation_request_state_test.cpp", + "p2p_default_state_test.cpp", + "p2p_disabled_state_test.cpp", + "p2p_disabling_state_test.cpp", + "p2p_enabled_state_test.cpp", + "p2p_enabling_state_test.cpp", + "p2p_group_formation_state_test.cpp", + "p2p_group_join_state_test.cpp", + "p2p_group_operating_state_test.cpp", + "p2p_idle_state_test.cpp", + "p2p_inviting_state_test.cpp", + "p2p_monitor_test.cpp", + "p2p_state_machine_test.cpp", + "provision_discovery_state_test.cpp", + "wifi_p2p_device_manager_test.cpp", + "wifi_p2p_dns_sd_service_info_test.cpp", + "wifi_p2p_dns_sd_service_request_test.cpp", + "wifi_p2p_dns_sd_service_response_test.cpp", + "wifi_p2p_group_info_proxy_test.cpp", + "wifi_p2p_group_manager_test.cpp", + "wifi_p2p_service_manager_test.cpp", + "wifi_p2p_service_request_list_test.cpp", + "wifi_p2p_service_response_list_test.cpp", + "wifi_p2p_service_test.cpp", + "wifi_p2p_upnp_service_info_test.cpp", + "wifi_p2p_upnp_service_request_test.cpp", + "wifi_p2p_upnp_service_response_test.cpp", + + #"./Mock/mock_wifi_settings.cpp", + + "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.cpp", + "global_test.cpp", + "wifi_p2p_test_entry.cpp", + + #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/mock_ui/system_ui.cpp", + #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/libaxprintf/xprint.c", + #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/libaxprintf/log.c", + #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/mock_ui/alert_dialog.cpp", + #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/mock_ui/handle_message.cpp", + #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/mock_ui/tcp_client.cpp", + #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/mock_ui/tcp_server.cpp", + ] + + include_dirs = [ + "./", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p", + "./Mock", + "//utils/native/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", + "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", + + #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/libaxprintf", + #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/mock_ui", + "//third_party/googletest/googlemock/include", + "//third_party/googletest/googletest/include", + ] + + deps = [ + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", + + #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all:all_test", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + part_name = "wifi_standard" + subsystem_name = "communication" +} + +group("unittest") { + testonly = true + deps = [] + deps += [ ":wifi_p2p_test" ] +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_authorizing_negotiation_request_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_authorizing_negotiation_request_state.h new file mode 100644 index 000000000..d08ab3911 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_authorizing_negotiation_request_state.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 MOCK_AUTHORIZING_NEGOTIATION_REQUEST_STATE +#define MOCK_AUTHORIZING_NEGOTIATION_REQUEST_STATE +#include +#include "authorizing_negotiation_request_state.h" +namespace OHOS { +namespace Wifi { +class MockAuthorizingNegotiationRequestState : public AuthorizingNegotiationRequestState { +public: + MockAuthorizingNegotiationRequestState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : AuthorizingNegotiationRequestState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockAuthorizingNegotiationRequestState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_formed_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_formed_state.h new file mode 100644 index 000000000..f05e63a89 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_formed_state.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 MOCK_GROUP_FORMED_STATE_H +#define MOCK_GROUP_FORMED_STATE_H +#include +#include "group_formed_state.h" +namespace OHOS { +namespace Wifi { +class MockGroupFormedState : public GroupFormedState { +public: + MockGroupFormedState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : GroupFormedState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockGroupFormedState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_negotiation_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_negotiation_state.h new file mode 100644 index 000000000..e57677066 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_negotiation_state.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 MOCK_GROUP_NEGOTIATION_STATE_H +#define MOCK_GROUP_NEGOTIATION_STATE_H +#include +#include "group_negotiation_state.h" +namespace OHOS { +namespace Wifi { +class MockGroupNegotiationState : public GroupNegotiationState { +public: + MockGroupNegotiationState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : GroupNegotiationState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockGroupNegotiationState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_recelved_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_recelved_state.h new file mode 100644 index 000000000..132e22549 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_recelved_state.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 MOCK_INVITATION_RECELVED_STATE_H +#define MOCK_INVITATION_RECELVED_STATE_H +#include +#include "invitation_received_state.h" +namespace OHOS { +namespace Wifi { +class MockInvitationReceivedState : public InvitationReceivedState { +public: + MockInvitationReceivedState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : InvitationReceivedState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockInvitationReceivedState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_request_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_request_state.h new file mode 100644 index 000000000..1f434653a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_request_state.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 MOCK_INVITATION_REQUEST_STATE_H +#define MOCK_INVITATION_REQUEST_STATE_H +#include +#include "invitation_request_state.h" +namespace OHOS { +namespace Wifi { +class MockInvitationRequestState : public InvitationRequestState { +public: + MockInvitationRequestState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : InvitationRequestState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockInvitationRequestState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_default_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_default_state.h new file mode 100644 index 000000000..224e13206 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_default_state.h @@ -0,0 +1,32 @@ +/* + * 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 MOCK_P2P_DEFAULT_STATE_H +#define MOCK_P2P_DEFAULT_STATE_H +#include +#include "p2p_default_state.h" +namespace OHOS { +namespace Wifi { +class MockP2pDefaultState : public P2pDefaultState { +public: + MockP2pDefaultState(P2pStateMachine &p2pStateMachine) : P2pDefaultState(p2pStateMachine) + {} + ~MockP2pDefaultState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabled_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabled_state.h new file mode 100644 index 000000000..b212f63a4 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabled_state.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 MOCK_P2P_DISABLED_STATE_H +#define MOCK_P2P_DISABLED_STATE_H +#include +#include "p2p_disabled_state.h" +namespace OHOS { +namespace Wifi { +class MockP2pDisabledState : public P2pDisabledState { +public: + MockP2pDisabledState(P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, + WifiP2pDeviceManager &deviceManager, WifiP2pServiceManager &serviceManager) + : P2pDisabledState(p2pStateMachine, groupManager, deviceManager, serviceManager) + {} + ~MockP2pDisabledState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabling_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabling_state.h new file mode 100644 index 000000000..227cd2a4f --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabling_state.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 MOCK_P2P_DISABLING_STATE_H +#define MOCK_P2P_DISABLING_STATE_H +#include +#include "p2p_disabling_state.h" +namespace OHOS { +namespace Wifi { +class MockP2pDisablingState : public P2pDisablingState { +public: + MockP2pDisablingState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : P2pDisablingState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockP2pDisablingState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabled_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabled_state.h new file mode 100644 index 000000000..e0585c9f1 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabled_state.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 MOCK_P2P_ENABLED_STATE_H +#define MOCK_P2P_ENABLED_STATE_H +#include +#include "p2p_enabled_state.h" +namespace OHOS { +namespace Wifi { +class MockP2pEnabledState : public P2pEnabledState { +public: + MockP2pEnabledState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : P2pEnabledState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockP2pEnabledState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabling_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabling_state.h new file mode 100644 index 000000000..57ba99af6 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabling_state.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 MOCK_P2P_ENABLING_STATE_H +#define MOCK_P2P_ENABLING_STATE_H +#include +#include "p2p_enabling_state.h" +namespace OHOS { +namespace Wifi { +class MockP2pEnablingState : public P2pEnablingState { +public: + MockP2pEnablingState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : P2pEnablingState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockP2pEnablingState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_formation_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_formation_state.h new file mode 100644 index 000000000..39da71754 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_formation_state.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 MOCK_P2P_GROUP_FORMATION_STATE_H +#define MOCK_P2P_GROUP_FORMATION_STATE_H +#include +#include "p2p_group_formation_state.h" +namespace OHOS { +namespace Wifi { +class MockP2pGroupFormationState : public P2pGroupFormationState { +public: + MockP2pGroupFormationState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : P2pGroupFormationState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockP2pGroupFormationState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_join_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_join_state.h new file mode 100644 index 000000000..1cecadfa0 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_join_state.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 MOCK_P2P_GROUP_JOIN_STATE_H +#define MOCK_P2P_GROUP_JOIN_STATE_H +#include +#include "p2p_group_join_state.h" +namespace OHOS { +namespace Wifi { +class MockP2pGroupJoinState : public P2pGroupJoinState { +public: + MockP2pGroupJoinState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : P2pGroupJoinState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockP2pGroupJoinState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_operating_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_operating_state.h new file mode 100644 index 000000000..51d1c34c0 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_operating_state.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 MOCK_P2P_GROUP_OPERATING_STATE_H +#define MOCK_P2P_GROUP_OPERATING_STATE_H +#include +#include "p2p_group_operating_state.h" +namespace OHOS { +namespace Wifi { +class MockP2pGroupOperatingState : public P2pGroupOperatingState { +public: + MockP2pGroupOperatingState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : P2pGroupOperatingState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockP2pGroupOperatingState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_idle_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_idle_state.h new file mode 100644 index 000000000..c87c69a11 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_idle_state.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 MOCK_P2P_IDLE_STATE_H +#define MOCK_P2P_IDLE_STATE_H +#include +#include "p2p_idle_state.h" +namespace OHOS { +namespace Wifi { +class MockP2pIdleState : public P2pIdleState { +public: + MockP2pIdleState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : P2pIdleState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockP2pIdleState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_inviting_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_inviting_state.h new file mode 100644 index 000000000..c50471438 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_inviting_state.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 MOCK_P2P_INVITING_STATE_H +#define MOCK_P2P_INVITING_STATE_H +#include +#include "p2p_inviting_state.h" +namespace OHOS { +namespace Wifi { +class MockP2pInvitingState : public P2pInvitingState { +public: + MockP2pInvitingState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : P2pInvitingState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockP2pInvitingState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_monitor.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_monitor.h new file mode 100644 index 000000000..c2d442d81 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_monitor.h @@ -0,0 +1,32 @@ +/* + * 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_P2P_MONITOR_H +#define OHOS_MOCK_P2P_MONITOR_H + +#include +#include "p2p_monitor.h" +namespace OHOS { +namespace Wifi { +class MockP2pMonitor : public P2pMonitor { +public: + MOCK_METHOD0(Initialize, void()); + MOCK_METHOD1(MonitorBegins, void(const std::string &iface)); + MOCK_METHOD1(MonitorEnds, void(const std::string &iface)); + MOCK_METHOD2(RegisterIfaceHandler, void(const std::string &iface, const std::function &handler)); + MOCK_METHOD1(UnregisterHandler, void(const std::string &iface)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_state_machine.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_state_machine.h new file mode 100644 index 000000000..84818765e --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_state_machine.h @@ -0,0 +1,43 @@ +/* + * 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_P2P_STATE_MACHINE_H +#define OHOS_MOCK_P2P_STATE_MACHINE_H +#include +#include "p2p_state_machine.h" + +namespace OHOS { +namespace Wifi { +class MockP2pStateMachine : public P2pStateMachine { +public: + MockP2pStateMachine(P2pMonitor &p2pMonitor, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager, + WifiP2pServiceManager &svrManager, AuthorizingNegotiationRequestState &authorizingNegotlationRequestState, + GroupFormedState &groupFormedState, GroupNegotiationState &groupNegotiationState, + InvitationReceivedState &invltationRecelvedState, InvitationRequestState &invitationRequestState, + P2pDefaultState &defaultState, P2pDisabledState &disabledState, P2pDisablingState &disablingState, + P2pEnabledState &enabledState, P2pEnablingState &enablingState, P2pGroupFormationState &groupFormationState, + P2pGroupJoinState &groupJoinState, P2pGroupOperatingState &groupOperatingState, P2pIdleState &idleState, + P2pInvitingState &invitingState, ProvisionDiscoveryState &provisionDiscoveryState) + : P2pStateMachine(p2pMonitor, groupManager, deviceManager, svrManager, authorizingNegotlationRequestState, + groupFormedState, groupNegotiationState, invltationRecelvedState, invitationRequestState, defaultState, + disabledState, disablingState, enabledState, enablingState, groupFormationState, groupJoinState, + groupOperatingState, idleState, invitingState, provisionDiscoveryState) + {} + ~MockP2pStateMachine() = default; + MOCK_METHOD0(Initialize, void()); + MOCK_METHOD1(IsConfigUnusable, P2pConfigErrCode(const WifiP2pConfig &config)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_provision_discovery_state.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_provision_discovery_state.h new file mode 100644 index 000000000..f79e25abc --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_provision_discovery_state.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 MOCK_PRIVISION_DISCOVERY_STATE_H +#define MOCK_PRIVISION_DISCOVERY_STATE_H +#include +#include "provision_discovery_state.h" +namespace OHOS { +namespace Wifi { +class MockProvisionDiscoveryState : public ProvisionDiscoveryState { +public: + MockProvisionDiscoveryState( + P2pStateMachine &p2pStateMachine, WifiP2pGroupManager &groupManager, WifiP2pDeviceManager &deviceManager) + : ProvisionDiscoveryState(p2pStateMachine, groupManager, deviceManager) + {} + ~MockProvisionDiscoveryState() = default; + MOCK_METHOD0(GoInState, void()); + MOCK_METHOD0(GoOutState, void()); + MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.cpp new file mode 100644 index 000000000..c710986c0 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.cpp @@ -0,0 +1,21 @@ +/* + * 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 "mock_wifi_p2p_device_manager.h" + +namespace OHOS { +namespace Wifi { +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.h new file mode 100644 index 000000000..e12b67a3e --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.h @@ -0,0 +1,56 @@ +/* + * 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_WIFIP2PDEVICEMANAGER_H +#define OHOS_MOCK_WIFIP2PDEVICEMANAGER_H + +#include +#include + +#include "wifi_msg.h" + +namespace OHOS { +namespace Wifi { +class MockWifiP2PDeviceManager { +public: + virtual void Initialize(void) = 0; + virtual bool AddDevice(const WifiP2pDevice &device) = 0; + virtual bool RemoveDevice(const WifiP2pDevice &device) = 0; + virtual int ClearAll(); + virtual int GetDevicesList(std::vector &devices) = 0; + virtual bool UpdateDeviceSupplicantInf(const WifiP2pDevice &device) = 0; + virtual bool UpdateDevice(const WifiP2pDevice &device) = 0; + virtual bool UpdateDeviceGroupCap(const WifiP2pDevice &device) = 0; + virtual bool UpdateDeviceStatus(const WifiP2pDevice &device) = 0; + virtual WifiP2pDevice GetDevices(std::string deviceAddress) = 0; + MockWifiP2PDeviceManager() = default; + virtual ~MockWifiP2PDeviceManager() = default; +}; + +class WifiP2PDeviceManager : public MockWifiP2PDeviceManager { +public: + MOCK_METHOD0(Initialize, void()); + MOCK_METHOD1(AddDevice, bool(const WifiP2pDevice &device)); + MOCK_METHOD1(RemoveDevice, bool(const WifiP2pDevice &device)); + MOCK_METHOD0(ClearAll, int()); + MOCK_METHOD1(GetDevicesList, int(std::vector &devices)); + MOCK_METHOD1(UpdateDeviceSupplicantInf, bool(const WifiP2pDevice &device)); + MOCK_METHOD1(UpdateDevice, bool(const WifiP2pDevice &device)); + MOCK_METHOD1(UpdateDeviceGroupCap, bool(const WifiP2pDevice &device)); + MOCK_METHOD1(UpdateDeviceStatus, bool(const WifiP2pDevice &device)); + MOCK_METHOD1(GetDevices, WifiP2pDevice(std::string deviceAddress)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.cpp new file mode 100644 index 000000000..305780642 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.cpp @@ -0,0 +1,26 @@ +/* + * 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 "mock_wifi_p2p_hal_interface.h" + +namespace OHOS { +namespace Wifi { +WifiP2PHalInterface &WifiP2PHalInterface::GetInstance() +{ + static WifiP2PHalInterface inst; + return inst; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.h new file mode 100644 index 000000000..50cb43ec5 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.h @@ -0,0 +1,140 @@ +/* + * 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_WIFIP2PHALINTERFACE_H +#define OHOS_MOCK_WIFIP2PHALINTERFACE_H +#include +#include +#include +#include +#include "wifi_msg.h" +#include "wifi_error_no.h" +#include "wifi_idl_struct.h" +#include "wifi_p2p_event_callback.h" + +namespace OHOS { +namespace Wifi { +class MockWifiP2PHalInterface { +public: + virtual ~MockWifiP2PHalInterface() = default; + virtual WifiErrorNo StartP2p(void) const = 0; + virtual WifiErrorNo StopP2p(void) const = 0; + virtual WifiErrorNo ListNetworks(std::map &value) const = 0; + virtual WifiErrorNo StartWpsPbc(const std::string &groupInterface, const std::string &bssid) const = 0; + virtual WifiErrorNo StartWpsPin(const std::string &groupInterface, const std::string &address, + const std::string &pin, std::string &result) const = 0; + virtual WifiErrorNo RemoveNetwork(int networkId) const = 0; + virtual WifiErrorNo SetP2pDeviceName(const std::string &name) const = 0; + virtual WifiErrorNo SetP2pDeviceType(const std::string &type) const = 0; + virtual WifiErrorNo SetP2pConfigMethods(const std::string &config) const = 0; + virtual WifiErrorNo SetP2pSsidPostfix(const std::string &postfixName) const = 0; + virtual WifiErrorNo SetP2pGroupIdle(const std::string &groupInterface, size_t time) const = 0; + virtual WifiErrorNo SetP2pPowerSave(const std::string &groupInterface, bool enable) const = 0; + virtual WifiErrorNo SetWfdEnable(bool enable) const = 0; + virtual WifiErrorNo SetWfdDeviceConfig(const std::string &config) const = 0; + virtual WifiErrorNo P2pFind(size_t timeout) const = 0; + virtual WifiErrorNo P2pStopFind() const = 0; + virtual WifiErrorNo P2pConfigureListen(bool enable, size_t period, size_t interval) const = 0; + virtual WifiErrorNo SetListenChannel(size_t channel, unsigned char regClass) const = 0; + virtual WifiErrorNo P2pFlush() const = 0; + virtual WifiErrorNo Connect(const WifiP2pConfig &config, bool isJoinExistingGroup, std::string &pin) const = 0; + virtual WifiErrorNo CancelConnect() const = 0; + virtual WifiErrorNo ProvisionDiscovery(const WifiP2pConfig &config) const = 0; + virtual WifiErrorNo GroupAdd(bool isPersistent, int networkId, int freq) const = 0; + virtual WifiErrorNo GroupRemove(const std::string &groupInterface) const = 0; + virtual WifiErrorNo Invite(const WifiP2pGroupInfo &group, const std::string &deviceAddr) const = 0; + virtual WifiErrorNo Reinvoke(int networkId, const std::string &deviceAddr) const = 0; + virtual WifiErrorNo GetDeviceAddress(std::string &deviceAddress) const = 0; + virtual WifiErrorNo GetGroupCapability(const std::string &deviceAddress, uint32_t &cap) const = 0; + virtual WifiErrorNo P2pServiceAdd(const WifiP2pServiceInfo &info) const = 0; + virtual WifiErrorNo P2pServiceRemove(const WifiP2pServiceInfo &info) const = 0; + virtual WifiErrorNo FlushService() const = 0; + virtual WifiErrorNo ReqServiceDiscovery( + const std::string &deviceAddress, const std::vector &tlvs, std::string &reqID) const = 0; + virtual WifiErrorNo CancelReqServiceDiscovery(const std::string &id) const = 0; + virtual WifiErrorNo SaveConfig() const = 0; + virtual WifiErrorNo SetRandomMacAddr(bool enable) const = 0; + virtual WifiErrorNo SetMiracastMode(int type) const = 0; + virtual WifiErrorNo RegisterP2pCallback(const P2pHalCallback &callbacks) = 0; + virtual WifiErrorNo RespServiceDiscovery( + const WifiP2pDevice &device, int frequency, int dialogToken, const std::vector &tlvs) const = 0; + virtual WifiErrorNo SetServiceDiscoveryExternal(bool isExternalProcess) const = 0; + virtual WifiErrorNo GetP2pPeer(const std::string &deviceAddress, WifiP2pDevice &device) const = 0; + virtual WifiErrorNo P2pGetSupportFrequenciesByBand(int band, std::vector &frequencies) const = 0; + virtual WifiErrorNo P2pSetGroupConfig(int networkId, const IdlP2pGroupConfig &config) const = 0; + virtual WifiErrorNo P2pGetGroupConfig(int networkId, IdlP2pGroupConfig &config) const = 0; + virtual WifiErrorNo P2pAddNetwork(int &networkId) const = 0; + virtual WifiErrorNo SetPersistentReconnect(int mode) const = 0; + virtual WifiErrorNo SetP2pSecondaryDeviceType(const std::string &type) = 0; +}; + +class WifiP2PHalInterface : public MockWifiP2PHalInterface { +public: + static WifiP2PHalInterface &GetInstance(); + +public: + MOCK_CONST_METHOD0(StartP2p, WifiErrorNo()); + MOCK_CONST_METHOD0(StopP2p, WifiErrorNo()); + MOCK_CONST_METHOD1(ListNetworks, WifiErrorNo(std::map &value)); + MOCK_CONST_METHOD2(StartWpsPbc, WifiErrorNo(const std::string &groupInterface, const std::string &bssid)); + MOCK_CONST_METHOD4(StartWpsPin, WifiErrorNo(const std::string &groupInterface, const std::string &address, + const std::string &pin, std::string &result)); + MOCK_CONST_METHOD1(RemoveNetwork, WifiErrorNo(int)); + MOCK_CONST_METHOD1(SetP2pDeviceName, WifiErrorNo(const std::string &name)); + MOCK_CONST_METHOD1(SetP2pDeviceType, WifiErrorNo(const std::string &type)); + MOCK_CONST_METHOD1(SetP2pConfigMethods, WifiErrorNo(const std::string &config)); + MOCK_CONST_METHOD1(SetP2pSsidPostfix, WifiErrorNo(const std::string &postfixName)); + MOCK_CONST_METHOD2(SetP2pGroupIdle, WifiErrorNo(const std::string &groupInterface, size_t time)); + MOCK_CONST_METHOD2(SetP2pPowerSave, WifiErrorNo(const std::string &groupInterface, bool enable)); + MOCK_CONST_METHOD1(SetWfdEnable, WifiErrorNo(bool)); + MOCK_CONST_METHOD1(SetWfdDeviceConfig, WifiErrorNo(const std::string &config)); + MOCK_CONST_METHOD1(P2pFind, WifiErrorNo(size_t)); + MOCK_CONST_METHOD0(P2pStopFind, WifiErrorNo()); + MOCK_CONST_METHOD3(P2pConfigureListen, WifiErrorNo(bool enable, size_t period, size_t interval)); + MOCK_CONST_METHOD2(SetListenChannel, WifiErrorNo(size_t channel, unsigned char regClass)); + MOCK_CONST_METHOD0(P2pFlush, WifiErrorNo()); + MOCK_CONST_METHOD3(Connect, WifiErrorNo(const WifiP2pConfig &config, bool isJoinExistingGroup, std::string &pin)); + MOCK_CONST_METHOD0(CancelConnect, WifiErrorNo()); + MOCK_CONST_METHOD1(ProvisionDiscovery, WifiErrorNo(const WifiP2pConfig &)); + MOCK_CONST_METHOD3(GroupAdd, WifiErrorNo(bool isPersistent, int networkId, int freq)); + MOCK_CONST_METHOD1(GroupRemove, WifiErrorNo(const std::string &groupInterface)); + MOCK_CONST_METHOD2(Invite, WifiErrorNo(const WifiP2pGroupInfo &group, const std::string &deviceAddr)); + MOCK_CONST_METHOD2(Reinvoke, WifiErrorNo(int networkId, const std::string &deviceAddr)); + MOCK_CONST_METHOD1(GetDeviceAddress, WifiErrorNo(std::string &deviceAddress)); + MOCK_CONST_METHOD2(GetGroupCapability, WifiErrorNo(const std::string &deviceAddress, uint32_t &cap)); + MOCK_CONST_METHOD1(P2pServiceAdd, WifiErrorNo(const WifiP2pServiceInfo &info)); + MOCK_CONST_METHOD1(P2pServiceRemove, WifiErrorNo(const WifiP2pServiceInfo &info)); + MOCK_CONST_METHOD0(FlushService, WifiErrorNo()); + MOCK_CONST_METHOD3(ReqServiceDiscovery, + WifiErrorNo(const std::string &deviceAddress, const std::vector &tlvs, std::string &reqID)); + MOCK_CONST_METHOD1(CancelReqServiceDiscovery, WifiErrorNo(const std::string &id)); + MOCK_CONST_METHOD0(SaveConfig, WifiErrorNo()); + MOCK_CONST_METHOD1(SetRandomMacAddr, WifiErrorNo(bool)); + MOCK_CONST_METHOD1(SetMiracastMode, WifiErrorNo(int)); + MOCK_METHOD1(RegisterP2pCallback, WifiErrorNo(const P2pHalCallback &callbacks)); + MOCK_CONST_METHOD4(RespServiceDiscovery, WifiErrorNo(const WifiP2pDevice &device, int frequency, int dialogToken, + const std::vector &tlvs)); + MOCK_CONST_METHOD1(SetServiceDiscoveryExternal, WifiErrorNo(bool)); + MOCK_CONST_METHOD2(GetP2pPeer, WifiErrorNo(const std::string &deviceAddress, WifiP2pDevice &device)); + MOCK_CONST_METHOD2(P2pGetSupportFrequenciesByBand, WifiErrorNo(int band, std::vector &frequencies)); + MOCK_CONST_METHOD2(P2pSetGroupConfig, WifiErrorNo(int networkId, const IdlP2pGroupConfig &config)); + MOCK_CONST_METHOD2(P2pGetGroupConfig, WifiErrorNo(int networkId, IdlP2pGroupConfig &config)); + MOCK_CONST_METHOD1(P2pAddNetwork, WifiErrorNo(int &networkId)); + MOCK_CONST_METHOD1(SetPersistentReconnect, WifiErrorNo(int mode)); + MOCK_METHOD1(SetP2pSecondaryDeviceType, WifiErrorNo(const std::string &type)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.cpp new file mode 100644 index 000000000..bea1b93df --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.cpp @@ -0,0 +1,26 @@ +/* + * 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 "mock_wifi_settings.h" + +namespace OHOS { +namespace Wifi { +WifiSettings &WifiSettings::GetInstance() +{ + static WifiSettings gWifiSettings; + return gWifiSettings; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.h new file mode 100644 index 000000000..7a49e52c6 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.h @@ -0,0 +1,92 @@ +/* + * 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_WIFISETTINGS_H +#define OHOS_MOCK_WIFISETTINGS_H + +#include +#include +#include +#include "wifi_msg.h" +#include + +namespace OHOS { +namespace Wifi { +const int MODE_ADD = 0; +const int MODE_DEL = 1; +const int MODE_UPDATE = 2; + +using ChannelsTable = std::map>; + +class MockWifiSettings { +public: + virtual ~MockWifiSettings() = default; + virtual int SetCountryCode(const std::string &countryCode) = 0; + virtual int GetCountryCode(std::string &countryCode) = 0; + virtual int GetHotspotState() = 0; + virtual int SetHotspotState(int state) = 0; + virtual int SetHotspotConfig(const HotspotConfig &config) = 0; + virtual int GetHotspotConfig(HotspotConfig &config) = 0; + virtual int GetStationList(std::vector &results) = 0; + virtual int ManageStation(const StationInfo &info, int mode) = 0; /* add / update / remove */ + virtual int ClearStationList() = 0; + virtual int GetBlockList(std::vector &results) = 0; + virtual int ManageBlockList(const StationInfo &info, int mode) = 0; /* add / remove */ + virtual int FindConnStation(const StationInfo &info) = 0; + virtual int GetValidBands(std::vector &bands) = 0; + virtual int SetValidChannels(const ChannelsTable &channelsInfo) = 0; + virtual int GetValidChannels(ChannelsTable &channelsInfo) = 0; + virtual int ClearValidChannels() = 0; + virtual int GetApMaxConnNum() = 0; + virtual int SetWifiP2pGroupInfo(const std::vector &groups) = 0; + virtual int SetP2pVendorConfig(const P2pVendorConfig &config) = 0; + virtual int GetP2pVendorConfig(P2pVendorConfig &config) = 0; + virtual int GetP2pInfo(WifiP2pInfo &connInfo) = 0; + virtual int SaveP2pInfo(WifiP2pInfo &connInfo) = 0; + virtual int GetWifiP2pGroupInfo(std::vector &groups) = 0; +}; + +class WifiSettings : public MockWifiSettings { +public: + WifiSettings() = default; + ~WifiSettings() = default; + static WifiSettings &GetInstance(void); + MOCK_METHOD1(GetWifiP2pGroupInfo, int(std::vector &groups)); + MOCK_METHOD1(SaveP2pInfo, int(WifiP2pInfo &connInfo)); + MOCK_METHOD1(GetP2pInfo, int(WifiP2pInfo &connInfo)); + MOCK_METHOD1(SetP2pVendorConfig, int(const P2pVendorConfig &config)); + MOCK_METHOD1(GetP2pVendorConfig, int(P2pVendorConfig &config)); + MOCK_METHOD1(SetWifiP2pGroupInfo, int(const std::vector &groups)); + MOCK_METHOD1(SetCountryCode, int(const std::string &countryCode)); + MOCK_METHOD1(GetCountryCode, int(std::string &countryCode)); + MOCK_METHOD0(GetHotspotState, int()); + MOCK_METHOD1(SetHotspotState, int(int)); + MOCK_METHOD1(SetHotspotConfig, int(const HotspotConfig &config)); + MOCK_METHOD1(GetHotspotConfig, int(HotspotConfig &config)); + MOCK_METHOD1(GetStationList, int(std::vector &results)); + MOCK_METHOD2(ManageStation, int(const StationInfo &info, int mode)); + MOCK_METHOD0(ClearStationList, int()); + MOCK_METHOD1(GetBlockList, int(std::vector &results)); + MOCK_METHOD2(ManageBlockList, int(const StationInfo &info, int mode)); + MOCK_METHOD1(FindConnStation, int(const StationInfo &info)); + MOCK_METHOD1(GetValidBands, int(std::vector &bands)); + MOCK_METHOD1(SetValidChannels, int(const ChannelsTable &channelsInfo)); + MOCK_METHOD1(GetValidChannels, int(ChannelsTable &channelsInfo)); + MOCK_METHOD0(ClearValidChannels, int()); + MOCK_METHOD0(GetApMaxConnNum, int()); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/authorizing_negotiation_request_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/authorizing_negotiation_request_state_test.cpp new file mode 100644 index 000000000..f3b7cbb6c --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/authorizing_negotiation_request_state_test.cpp @@ -0,0 +1,122 @@ +/* + * 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 "authorizing_negotiation_request_state.h" +#include "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class AuthorizingNegotiationRequestStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pAuthorizingNegotlationRequestState.reset( + new AuthorizingNegotiationRequestState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + pGroupFormedState.reset( + new GroupFormedState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + } + virtual void TearDown() + { + pAuthorizingNegotlationRequestState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + pGroupFormedState.reset(); + pGroupFormedState.reset(); + } + +public: + void AddSaveP2pConfig() + { + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_ENTER_PIN)); + WifiP2pTempDiscEvent procDisc; + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + procDisc.SetDevice(device); + msg.SetMessageObj(procDisc); + pGroupFormedState->ExecuteStateMsg(&msg); + } + std::unique_ptr pGroupFormedState; + std::unique_ptr pAuthorizingNegotlationRequestState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(AuthorizingNegotiationRequestStateTest, GoInState, TestSize.Level1) +{ + pAuthorizingNegotlationRequestState->GoInState(); + AddSaveP2pConfig(); + pAuthorizingNegotlationRequestState->GoInState(); +} +HWTEST_F(AuthorizingNegotiationRequestStateTest, GoOutState, TestSize.Level1) +{ + pAuthorizingNegotlationRequestState->GoOutState(); +} +HWTEST_F(AuthorizingNegotiationRequestStateTest, ExecuteStateMsg, TestSize.Level1) +{ + AddSaveP2pConfig(); + InternalMessage msg; + std::string inputPin; + msg.SetMessageObj(inputPin); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::INTERNAL_CONN_USER_ACCEPT)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pAuthorizingNegotlationRequestState->ExecuteStateMsg(&msg); +} + +HWTEST_F(AuthorizingNegotiationRequestStateTest, ExecuteStateMsg1, TestSize.Level1) +{ + AddSaveP2pConfig(); + InternalMessage msg; + std::string b = "std::any"; + msg.SetMessageObj(b); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::INTERNAL_CONN_USER_ACCEPT)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pAuthorizingNegotlationRequestState->ExecuteStateMsg(&msg); +} +HWTEST_F(AuthorizingNegotiationRequestStateTest, ExecuteStateMsg2, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::PEER_CONNECTION_USER_REJECT)); + pAuthorizingNegotlationRequestState->ExecuteStateMsg(&msg); +} +HWTEST_F(AuthorizingNegotiationRequestStateTest, ExecuteStateMsg3, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::INTERNAL_CONN_USER_CONFIRM)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), Connect(_, _, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pAuthorizingNegotlationRequestState->ExecuteStateMsg(&msg); +} +HWTEST_F(AuthorizingNegotiationRequestStateTest, ExecuteStateMsg4, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::REMOVE_SERVICE_REQUEST_RECORD)); + pAuthorizingNegotlationRequestState->ExecuteStateMsg(&msg); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.cpp new file mode 100644 index 000000000..72891b022 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.cpp @@ -0,0 +1,23 @@ +/* + * 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 "global_test.h" +void GlobalTest::SetUp() +{ + printf("GlobalTest P2P SetUp\n"); +} +void GlobalTest::TearDown() +{ + printf("GlobalTest P2P TearDown\n"); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.h new file mode 100644 index 000000000..507b75268 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.h @@ -0,0 +1,24 @@ +/* + * 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 GLOBAL_TEST_H +#define GLOBAL_TEST_H +#include + +class GlobalTest : public testing::Environment { +public: + virtual void SetUp(); + virtual void TearDown(); +}; +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_formed_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_formed_state_test.cpp new file mode 100644 index 000000000..848a9b4a4 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_formed_state_test.cpp @@ -0,0 +1,260 @@ +/* + * 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 "group_formed_state.h" +#include "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" + +using ::testing::_; +using ::testing::Eq; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class GroupFormedStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pGroupFormedState.reset( + new GroupFormedState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + pGroupFormedState->Init(); + } + virtual void TearDown() + { + pGroupFormedState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + } + +public: + void AddGroupManager() + { + WifiP2pGroupInfo groupInfo; + groupInfo.SetNetworkId(0); + groupInfo.SetGroupName("AAA"); + groupInfo.SetIsGroupOwner(true); + WifiP2pDevice owner; + owner.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + groupInfo.SetOwner(owner); + pGroupFormedState->groupManager.AddGroup(groupInfo); + pGroupFormedState->groupManager.SetCurrentGroup(groupInfo); + } + void AddDeviceStateMachine() + { + WifiP2pDevice device; + device.SetDeviceName("device"); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + device.SetGroupCapabilitys(static_cast(P2pGroupCapability::PGC_GROUP_OWNER)); + device.SetPrimaryDeviceType("10-0050F204-5"); + pGroupFormedState->deviceManager.AddDevice(device); + } + void AddDeviceManager() + { + WifiP2pDevice device; + device.SetDeviceName("device"); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + device.SetGroupCapabilitys(static_cast(P2pGroupCapability::PGC_GROUP_OWNER)); + device.SetPrimaryDeviceType("10-0050F204-5"); + pGroupFormedState->deviceManager.AddDevice(device); + } + std::unique_ptr pGroupFormedState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(GroupFormedStateTest, GoInState, TestSize.Level1) +{ + AddGroupManager(); + pGroupFormedState->GoInState(); +} +HWTEST_F(GroupFormedStateTest, GoOutState, TestSize.Level1) +{ + pGroupFormedState->GoOutState(); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg1, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pDevice device; + AddGroupManager(); + AddDeviceManager(); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + msg.SetMessageObj(device); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::AP_STA_CONNECTED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pGroupIdle(_, _)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg1break, TestSize.Level1) +{ + InternalMessage msg; + AddGroupManager(); + WifiP2pDevice device; + msg.SetMessageObj(device); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::AP_STA_CONNECTED)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg2, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pDevice device; + AddGroupManager(); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + msg.SetMessageObj(device); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::AP_STA_DISCONNECTED)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg2break, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::WPA_CONNECTED_EVENT)); + EXPECT_FALSE(pGroupFormedState->ExecuteStateMsg(&msg)); + WifiP2pDevice device; + msg.SetMessageObj(device); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::AP_STA_DISCONNECTED)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg3, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pDevice device; + AddGroupManager(); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + msg.SetMessageObj(device); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_LOST)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg3break, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pDevice device; + msg.SetMessageObj(device); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_LOST)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg4, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg5, TestSize.Level1) +{ + WifiP2pConfig config; + InternalMessage msg; + msg.SetMessageObj(config); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg6, TestSize.Level1) +{ + WifiP2pConfig config; + AddDeviceManager(); + InternalMessage msg; + config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + msg.SetMessageObj(config); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); + AddDeviceStateMachine(); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg7, TestSize.Level1) +{ + WifiP2pTempDiscEvent procDisc; + InternalMessage msg; + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + procDisc.SetDevice(device); + msg.SetMessageObj(procDisc); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_PBC_REQ)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg8, TestSize.Level1) +{ + WifiP2pTempDiscEvent procDisc; + InternalMessage msg; + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + procDisc.SetDevice(device); + msg.SetMessageObj(procDisc); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_ENTER_PIN)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg9, TestSize.Level1) +{ + WifiP2pTempDiscEvent procDisc; + InternalMessage msg; + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + procDisc.SetDevice(device); + msg.SetMessageObj(procDisc); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_SHOW_PIN)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); + AddGroupManager(); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg9break, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pTempDiscEvent procDisc; + msg.SetMessageObj(procDisc); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_SHOW_PIN)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg10, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg11, TestSize.Level1) +{ + InternalMessage msg; + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pFind(DISC_TIMEOUT_S)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DEVICE_DISCOVERS)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ExecuteStateMsg12, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_REMOVED)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ProcessCmdRemoveGroup1, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_REMOVE_GROUP)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} +HWTEST_F(GroupFormedStateTest, ProcessCmdRemoveGroup2, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DELETE_GROUP)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DISCONNECT)); + EXPECT_FALSE(pGroupFormedState->ExecuteStateMsg(&msg)); + EXPECT_FALSE(pGroupFormedState->ExecuteStateMsg(nullptr)); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_negotiation_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_negotiation_state_test.cpp new file mode 100644 index 000000000..31a5ac844 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_negotiation_state_test.cpp @@ -0,0 +1,206 @@ +/* + * 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 "group_negotiation_state.h" +#include "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class GroupNegotiationStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pGroupNegotiationState.reset( + new GroupNegotiationState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + pGroupNegotiationState->Init(); + } + virtual void TearDown() + { + pGroupNegotiationState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + } + +public: + void AddGroupManager() + { + WifiP2pGroupInfo groupInfo; + groupInfo.SetNetworkId(0); + groupInfo.SetGroupName("AAA"); + groupInfo.SetIsGroupOwner(true); + WifiP2pDevice owner; + owner.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + groupInfo.SetOwner(owner); + pGroupNegotiationState->groupManager.AddGroup(groupInfo); + pGroupNegotiationState->groupManager.SetCurrentGroup(groupInfo); + } + void AddDeviceManager() + { + WifiP2pDevice device; + device.SetDeviceName("device"); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + device.SetGroupCapabilitys(static_cast(P2pGroupCapability::PGC_GROUP_OWNER)); + device.SetPrimaryDeviceType("10-0050F204-5"); + pGroupNegotiationState->deviceManager.AddDevice(device); + } + std::unique_ptr pGroupNegotiationState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(GroupNegotiationStateTest, GoInState, TestSize.Level1) +{ + pGroupNegotiationState->GoInState(); +} + +HWTEST_F(GroupNegotiationStateTest, GoOutState, TestSize.Level1) +{ + pGroupNegotiationState->GoOutState(); +} + +HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg1, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_FORMATION_SUCCESS)); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg2, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pGroupInfo group; + group.SetIsGroupOwner(true); + group.SetIsPersistent(false); + msg.SetMessageObj(group); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg3, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pGroupInfo group; + WifiP2pDevice device; + group.SetIsGroupOwner(false); + group.SetIsPersistent(true); + device.SetDeviceName("device"); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + group.SetOwner(device); + msg.SetMessageObj(group); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pGroupIdle(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + AddDeviceManager(); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg4, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pGroupInfo group; + group.SetIsGroupOwner(false); + group.SetIsPersistent(true); + msg.SetMessageObj(group); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pGroupIdle(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + AddDeviceManager(); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg5, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GO_NEG_FAILURE)); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg6, TestSize.Level1) +{ + InternalMessage msg; + msg.SetParam1(1); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RESULT)); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg7, TestSize.Level1) +{ + InternalMessage msg; + msg.SetParam1(0); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RESULT)); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg8, TestSize.Level1) +{ + InternalMessage msg; + msg.SetParam1(8); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RESULT)); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg9, TestSize.Level1) +{ + InternalMessage msg; + msg.SetParam1(1); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RESULT)); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg10, TestSize.Level1) +{ + InternalMessage msg; + msg.SetParam1(7); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RESULT)); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(GroupNegotiationStateTest, ProcessNegotSucessEvt, TestSize.Level1) +{ + InternalMessage msg; + msg.SetParam1(0); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GO_NEG_SUCCESS)); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); + EXPECT_FALSE(pGroupNegotiationState->ExecuteStateMsg(nullptr)); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_PBC_REQ)); + EXPECT_FALSE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(GroupNegotiationStateTest, ProcessGroupFormationFailEvt, TestSize.Level1) +{ + InternalMessage msg; + msg.SetParam1(0); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_FORMATION_FAILURE)); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_PBC_REQ)); + EXPECT_FALSE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} +} // namespace Wifi +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_recelved_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_recelved_state_test.cpp new file mode 100644 index 000000000..e79e4dd5f --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_recelved_state_test.cpp @@ -0,0 +1,104 @@ +/* + * 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 "invitation_received_state.h" +#include "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class InvitationReceivedStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pInvitationReceivedState.reset( + new InvitationReceivedState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + pGroupFormedState.reset( + new GroupFormedState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + } + virtual void TearDown() + { + pInvitationReceivedState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + pGroupFormedState.reset(); + } + +public: + void AddSaveP2pConfig() + { + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_ENTER_PIN)); + WifiP2pTempDiscEvent procDisc; + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + procDisc.SetDevice(device); + msg.SetMessageObj(procDisc); + pGroupFormedState->ExecuteStateMsg(&msg); + } + std::unique_ptr pGroupFormedState; + std::unique_ptr pInvitationReceivedState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(InvitationReceivedStateTest, GoInState, TestSize.Level1) +{ + pInvitationReceivedState->GoInState(); +} + +HWTEST_F(InvitationReceivedStateTest, GoOutState, TestSize.Level1) +{ + pInvitationReceivedState->GoOutState(); +} + +HWTEST_F(InvitationReceivedStateTest, ExecuteStateMsg1, TestSize.Level1) +{ + InternalMessage msg; + AddSaveP2pConfig(); + std::string inputPin; + msg.SetMessageObj(inputPin); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::INTERNAL_CONN_USER_ACCEPT)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pInvitationReceivedState->ExecuteStateMsg(&msg); +} + +HWTEST_F(InvitationReceivedStateTest, ExecuteStateMsg2, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::PEER_CONNECTION_USER_REJECT)); + pInvitationReceivedState->ExecuteStateMsg(&msg); +} + +HWTEST_F(InvitationReceivedStateTest, ExecuteStateMsg3, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CREATE_GROUP_TIMED_OUT)); + pInvitationReceivedState->ExecuteStateMsg(&msg); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_request_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_request_state_test.cpp new file mode 100644 index 000000000..5d82a02e7 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_request_state_test.cpp @@ -0,0 +1,88 @@ +/* + * 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 "invitation_request_state.h" +#include "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class InvitationRequestStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pInvitationRequestState.reset( + new InvitationRequestState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + } + virtual void TearDown() + { + pInvitationRequestState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + } + +public: + void AddGroup() + { + WifiP2pGroupInfo group; + group.SetNetworkId(0); + pInvitationRequestState->groupManager.SetCurrentGroup(group); + } + std::unique_ptr pInvitationRequestState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(InvitationRequestStateTest, GoInState, TestSize.Level1) +{ + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), Invite(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pInvitationRequestState->GoInState(); + pInvitationRequestState->GoInState(); +} + +HWTEST_F(InvitationRequestStateTest, GoOutState, TestSize.Level1) +{ + pInvitationRequestState->GoOutState(); +} + +HWTEST_F(InvitationRequestStateTest, ExecuteStateMsg1, TestSize.Level1) +{ + InternalMessage msg; + msg.SetParam1(0); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RESULT)); + EXPECT_TRUE(pInvitationRequestState->ExecuteStateMsg(&msg)); + + msg.SetParam1(8); + EXPECT_TRUE(pInvitationRequestState->ExecuteStateMsg(&msg)); + + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_FORMATION_SUCCESS)); + EXPECT_FALSE(pInvitationRequestState->ExecuteStateMsg(&msg)); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/mock_p2p_pendant.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/mock_p2p_pendant.h new file mode 100644 index 000000000..d3cf9bc6a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/mock_p2p_pendant.h @@ -0,0 +1,190 @@ +/* + * 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_AP_PENDANT_H +#define OHOS_MOCK_AP_PENDANT_H +#include "mock_p2p_monitor.h" +#include "mock_authorizing_negotiation_request_state.h" +#include "mock_group_formed_state.h" +#include "mock_group_negotiation_state.h" +#include "mock_invitation_recelved_state.h" +#include "mock_invitation_request_state.h" +#include "mock_p2p_default_state.h" +#include "mock_p2p_disabled_state.h" +#include "mock_p2p_disabling_state.h" +#include "mock_p2p_enabled_state.h" +#include "mock_p2p_enabling_state.h" +#include "mock_p2p_group_formation_state.h" +#include "mock_p2p_group_join_state.h" +#include "mock_p2p_group_operating_state.h" +#include "mock_p2p_idle_state.h" +#include "mock_p2p_inviting_state.h" +#include "mock_p2p_state_machine.h" +#include "mock_provision_discovery_state.h" + +namespace OHOS { +namespace Wifi { +class MockP2pPendant { +public: + MockP2pPendant() + : groupManager(), + deviceManager(), + svrManager(), + mockAuthorizingNegotiationRequestState(p2pStateMachine, groupManager, deviceManager), + mockGroupFormedState(p2pStateMachine, groupManager, deviceManager), + mockGroupNegotiationState(p2pStateMachine, groupManager, deviceManager), + mockInvitationReceivedState(p2pStateMachine, groupManager, deviceManager), + mockInvitationRequestState(p2pStateMachine, groupManager, deviceManager), + mockP2pDefaultState(p2pStateMachine), + mockP2pDisabledState(p2pStateMachine, groupManager, deviceManager, serviceManager), + mockP2pDisablingState(p2pStateMachine, groupManager, deviceManager), + mockP2pEnabledState(p2pStateMachine, groupManager, deviceManager), + mockP2pEnablingState(p2pStateMachine, groupManager, deviceManager), + mockP2pGroupFormationState(p2pStateMachine, groupManager, deviceManager), + mockP2pGroupJoinState(p2pStateMachine, groupManager, deviceManager), + mockP2pGroupOperatingState(p2pStateMachine, groupManager, deviceManager), + mockP2pIdleState(p2pStateMachine, groupManager, deviceManager), + mockP2pInvitingState(p2pStateMachine, groupManager, deviceManager), + mockProvisionDiscoveryState(p2pStateMachine, groupManager, deviceManager), + p2pStateMachine(mockP2pMonitor, groupManager, deviceManager, svrManager, + mockAuthorizingNegotiationRequestState, mockGroupFormedState, mockGroupNegotiationState, + mockInvitationReceivedState, mockInvitationRequestState, mockP2pDefaultState, + mockP2pDisabledState, mockP2pDisablingState, mockP2pEnabledState, mockP2pEnablingState, + mockP2pGroupFormationState, mockP2pGroupJoinState, mockP2pGroupOperatingState, mockP2pIdleState, + mockP2pInvitingState, mockProvisionDiscoveryState) + { + } + ~MockP2pPendant() + {} + +public: + void AddGroup(const WifiP2pGroupInfo &group) + { + groupManager.AddGroup(group); + } + void AddDevice(const WifiP2pDevice &device) + { + deviceManager.AddDevice(device); + } + void AddSvr() + {} + void SetCurrentGroup(const WifiP2pGroupInfo &group) + { + groupManager.SetCurrentGroup(group); + } + MockAuthorizingNegotiationRequestState &GetMockAuthorizingNegotiationRequestState() + { + return mockAuthorizingNegotiationRequestState; + } + MockGroupFormedState &GetMockGroupFormedState() + { + return mockGroupFormedState; + } + MockGroupNegotiationState &GetMockGroupNegotiationState() + { + return mockGroupNegotiationState; + } + MockInvitationReceivedState &GetMockInvitationReceivedState() + { + return mockInvitationReceivedState; + } + MockInvitationRequestState &GetMockInvitationRequestState() + { + return mockInvitationRequestState; + } + MockP2pDefaultState &GetMockP2pDefaultState() + { + return mockP2pDefaultState; + } + MockP2pDisabledState &GetMockP2pDisabledState() + { + return mockP2pDisabledState; + } + MockP2pDisablingState &GetMockP2pDisablingState() + { + return mockP2pDisablingState; + } + + MockP2pEnabledState &GetMockP2pEnabledState() + { + return mockP2pEnabledState; + } + MockP2pEnablingState &GetMockP2pEnablingState() + { + return mockP2pEnablingState; + } + MockP2pGroupFormationState &GetMockP2pGroupFormationState() + { + return mockP2pGroupFormationState; + } + MockP2pGroupJoinState &GetMockP2pGroupJoinState() + { + return mockP2pGroupJoinState; + } + MockP2pGroupOperatingState &GetMockP2pGroupOperatingState() + { + return mockP2pGroupOperatingState; + } + MockP2pIdleState &GetMockP2pIdleState() + { + return mockP2pIdleState; + } + MockP2pInvitingState &GetMockP2pInvitingState() + { + return mockP2pInvitingState; + } + MockP2pStateMachine &GetP2pStateMachine() + { + return p2pStateMachine; + } + MockProvisionDiscoveryState &GetMockProvisionDiscoveryState() + { + return mockProvisionDiscoveryState; + } + MockP2pMonitor &GetMockP2pMonitor() + { + return mockP2pMonitor; + } + +private: + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; + WifiP2pServiceManager svrManager; + WifiP2pServiceManager serviceManager; + MockAuthorizingNegotiationRequestState mockAuthorizingNegotiationRequestState; + MockGroupFormedState mockGroupFormedState; + MockGroupNegotiationState mockGroupNegotiationState; + + MockInvitationReceivedState mockInvitationReceivedState; + MockInvitationRequestState mockInvitationRequestState; + MockP2pDefaultState mockP2pDefaultState; + + MockP2pDisabledState mockP2pDisabledState; + MockP2pDisablingState mockP2pDisablingState; + + MockP2pEnabledState mockP2pEnabledState; + MockP2pEnablingState mockP2pEnablingState; + MockP2pGroupFormationState mockP2pGroupFormationState; + MockP2pGroupJoinState mockP2pGroupJoinState; + MockP2pGroupOperatingState mockP2pGroupOperatingState; + MockP2pIdleState mockP2pIdleState; + MockP2pInvitingState mockP2pInvitingState; + MockProvisionDiscoveryState mockProvisionDiscoveryState; + + MockP2pMonitor mockP2pMonitor; + MockP2pStateMachine p2pStateMachine; +}; +} // namespace Wifi +} // namespace OHOS +#endif diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_default_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_default_state_test.cpp new file mode 100644 index 000000000..3a38e4ba9 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_default_state_test.cpp @@ -0,0 +1,79 @@ +/* + * 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 "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" +#include "p2p_default_state.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class P2pDefaultStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pDefaultState.reset(new P2pDefaultState(pMockP2pPendant->GetP2pStateMachine())); + } + virtual void TearDown() + { + pDefaultState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + } + +public: + std::unique_ptr pDefaultState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(P2pDefaultStateTest, GoInState, TestSize.Level1) +{ + pDefaultState->GoInState(); +} + +HWTEST_F(P2pDefaultStateTest, GoOutState, TestSize.Level1) +{ + pDefaultState->GoOutState(); +} + +HWTEST_F(P2pDefaultStateTest, ExecuteStateMsg1, TestSize.Level1) +{ + InternalMessage msg; + std::string deviceAddress; + msg.SetMessageObj(deviceAddress); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::REMOVE_SERVICE_REQUEST_RECORD)); + pDefaultState->ExecuteStateMsg(&msg); +} + +HWTEST_F(P2pDefaultStateTest, ExecuteStateMsg2, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CREATE_GROUP_TIMED_OUT)); + pDefaultState->ExecuteStateMsg(&msg); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabled_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabled_state_test.cpp new file mode 100644 index 000000000..0df0d35a0 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabled_state_test.cpp @@ -0,0 +1,84 @@ +/* + * 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 "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" +#include "p2p_disabled_state.h" +#include "mock_p2p_monitor.h" +#include "mock_wifi_settings.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class P2pDisabledStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pMockMonitor = &pMockP2pPendant->GetMockP2pMonitor(); + pP2pDisabledState.reset( + new P2pDisabledState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager, serviceManager)); + } + virtual void TearDown() + { + pP2pDisabledState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + pMockMonitor = nullptr; + } + +public: + std::unique_ptr pP2pDisabledState; + std::unique_ptr pMockP2pPendant; + MockP2pMonitor* pMockMonitor; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; + WifiP2pServiceManager serviceManager; +}; + +HWTEST_F(P2pDisabledStateTest, GoInState, TestSize.Level1) +{ + pP2pDisabledState->GoInState(); +} + +HWTEST_F(P2pDisabledStateTest, GoOutState, TestSize.Level1) +{ + pP2pDisabledState->GoOutState(); +} + +HWTEST_F(P2pDisabledStateTest, ExecuteStateMsg, TestSize.Level1) +{ + InternalMessage msg; + EXPECT_CALL(*pMockMonitor, RegisterIfaceHandler(_, _)).WillOnce(Return()); + EXPECT_CALL(*pMockMonitor, MonitorBegins(_)).WillOnce(Return()); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), StartP2p()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetRandomMacAddr(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_ENABLE)); + pP2pDisabledState->ExecuteStateMsg(&msg); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE)); + pP2pDisabledState->ExecuteStateMsg(&msg); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabling_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabling_state_test.cpp new file mode 100644 index 000000000..d4ab353e3 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabling_state_test.cpp @@ -0,0 +1,87 @@ +/* + * 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 "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" +#include "p2p_disabling_state.h" +#include "mock_p2p_monitor.h" +#include "mock_wifi_settings.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class P2pDisablingStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pP2pDisablingState.reset( + new P2pDisablingState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + } + virtual void TearDown() + { + pP2pDisablingState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + } + +public: + std::unique_ptr pP2pDisablingState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(P2pDisablingStateTest, GoInState, TestSize.Level1) +{ + pP2pDisablingState->GoInState(); +} + +HWTEST_F(P2pDisablingStateTest, GoOutState, TestSize.Level1) +{ + pP2pDisablingState->GoOutState(); +} + +HWTEST_F(P2pDisablingStateTest, ExecuteStateMsg, TestSize.Level1) +{ + InternalMessage msg; + msg.SetParam1(1); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::WPA_CONNECTED_EVENT)); + pP2pDisablingState->ExecuteStateMsg(&msg); + + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE)); + pP2pDisablingState->ExecuteStateMsg(&msg); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::WPA_CONNECTED_EVENT)); +} + +HWTEST_F(P2pDisablingStateTest, ExecuteStateMsg2, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::WPA_CONNECTED_EVENT)); + msg.SetParam1(0); + EXPECT_CALL(pMockP2pPendant->GetMockP2pMonitor(), MonitorEnds(_)).WillOnce(Return()); + pP2pDisablingState->ExecuteStateMsg(&msg); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabled_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabled_state_test.cpp new file mode 100644 index 000000000..5ddc83242 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabled_state_test.cpp @@ -0,0 +1,380 @@ +/* + * 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 "p2p_enabled_state.h" +#include "mock_p2p_pendant.h" +#include "mock_wifi_settings.h" +#include "mock_wifi_p2p_hal_interface.h" + +using ::testing::_; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class P2pEnabledStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pP2pEnabledState.reset(new P2pEnabledState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + pP2pEnabledState->Init(); + } + virtual void TearDown() + { + pP2pEnabledState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + } + +public: + void AddDevice() + { + const int testCfgMethod = 128; + WifiP2pDevice device; + device.SetDeviceName("device"); + device.SetWpsConfigMethod(testCfgMethod); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + device.SetGroupCapabilitys(static_cast(P2pGroupCapability::PGC_GROUP_OWNER)); + device.SetPrimaryDeviceType("10-0050F204-5"); + pP2pEnabledState->deviceManager.AddDevice(device); + } + std::unique_ptr pP2pEnabledState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(P2pEnabledStateTest, GoInState, TestSize.Level1) +{ + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pDeviceName(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pSsidPostfix(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pDeviceType(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pConfigMethods(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GetDeviceAddress(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pFlush()) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), FlushService()) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetServiceDiscoveryExternal(Eq(false))) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetPersistentReconnect(Eq(1))) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RemoveNetwork(Eq(-1))) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + pP2pEnabledState->GoInState(); + pP2pEnabledState->GoInState(); +} + +HWTEST_F(P2pEnabledStateTest, GoOutState, TestSize.Level1) +{ + pP2pEnabledState->GoOutState(); +} + +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg, TestSize.Level1) +{ + EXPECT_FALSE(pP2pEnabledState->ExecuteStateMsg(nullptr)); +} + +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg1, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), StopP2p()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pP2pEnabledState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg2, TestSize.Level1) +{ + InternalMessage msg; + msg.SetParam1(1); + msg.SetParam2(1); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_START_LISTEN)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pFlush()) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetListenChannel(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pConfigureListen(_, _, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pP2pEnabledState->ExecuteStateMsg(&msg)); + EXPECT_TRUE(pP2pEnabledState->ExecuteStateMsg(&msg)); + EXPECT_TRUE(pP2pEnabledState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg3, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_STOP_LISTEN)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pConfigureListen(_, _, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pFlush()) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + pP2pEnabledState->ExecuteStateMsg(&msg); + pP2pEnabledState->ExecuteStateMsg(&msg); +} + +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg4, TestSize.Level1) +{ + InternalMessage msg; + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pFind(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DEVICE_DISCOVERS)); + pP2pEnabledState->ExecuteStateMsg(&msg); +} + +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg5, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_STOP_DEVICE_DISCOVERS)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pP2pEnabledState->ExecuteStateMsg(&msg); + pP2pEnabledState->ExecuteStateMsg(&msg); +} + +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg6, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pDevice device; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_FOUND)); + msg.SetMessageObj(device); + pP2pEnabledState->ExecuteStateMsg(&msg); +} + +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg7, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pDevice device; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_LOST)); + msg.SetMessageObj(device); + pP2pEnabledState->ExecuteStateMsg(&msg); + + AddDevice(); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + msg.SetMessageObj(device); + pP2pEnabledState->ExecuteStateMsg(&msg); +} + +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg8, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_FIND_STOPPED)); + pP2pEnabledState->ExecuteStateMsg(&msg); +} + +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg9, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DELETE_GROUP)); + pP2pEnabledState->ExecuteStateMsg(&msg); + +} +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg10, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_PUT_LOCAL_SERVICE)); + WifiP2pServiceInfo service; + msg.SetMessageObj(service); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pServiceAdd(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pP2pEnabledState->ExecuteStateMsg(&msg); + pP2pEnabledState->ExecuteStateMsg(&msg); +} +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg11, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DEL_LOCAL_SERVICE)); + WifiP2pServiceInfo service; + msg.SetMessageObj(service); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pServiceRemove(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pP2pEnabledState->ExecuteStateMsg(&msg); + pP2pEnabledState->ExecuteStateMsg(&msg); +} +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg12, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_STOP_DISCOVER_SERVICES)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pP2pEnabledState->ExecuteStateMsg(&msg); + pP2pEnabledState->ExecuteStateMsg(&msg); +} +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg13, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_REQUEST_SERVICE)); + std::pair info; + msg.SetMessageObj(info); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ReqServiceDiscovery(_, _, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + pP2pEnabledState->ExecuteStateMsg(&msg); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pFind(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pP2pEnabledState->ExecuteStateMsg(&msg); + pP2pEnabledState->ExecuteStateMsg(&msg); +} +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg14, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_SERV_DISC_REQ)); + WifiP2pServiceRequestList reqList; + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + reqList.SetDevice(device); + msg.SetMessageObj(reqList); + pP2pEnabledState->ExecuteStateMsg(&msg); +} +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg15, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_SERV_DISC_RESP)); + + WifiP2pServiceResponseList respList; + msg.SetMessageObj(respList); + pP2pEnabledState->ExecuteStateMsg(&msg); +} +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg16, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_FAILURE)); + pP2pEnabledState->ExecuteStateMsg(&msg); +} +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg17, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pServiceInfo service; + msg.SetMessageObj(service); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_PUT_LOCAL_SERVICE)); + pP2pEnabledState->ExecuteStateMsg(&msg); +} +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg18, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pServiceInfo service; + msg.SetMessageObj(service); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pServiceRemove(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DEL_LOCAL_SERVICE)); + pP2pEnabledState->ExecuteStateMsg(&msg); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ReqServiceDiscovery(_, _, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pFind(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DISCOVER_SERVICES)); + pP2pEnabledState->ExecuteStateMsg(&msg); + pP2pEnabledState->ExecuteStateMsg(&msg); + pP2pEnabledState->ExecuteStateMsg(&msg); +} + +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg19, TestSize.Level1) +{ + InternalMessage msg; + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_STOP_DISCOVER_SERVICES)); + pP2pEnabledState->ExecuteStateMsg(&msg); + pP2pEnabledState->ExecuteStateMsg(&msg); +} +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg20, TestSize.Level1) +{ + InternalMessage msg; + std::pair info; + msg.SetMessageObj(info); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_REQUEST_SERVICE)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ReqServiceDiscovery(_, _, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pFind(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + pP2pEnabledState->ExecuteStateMsg(&msg); + pP2pEnabledState->ExecuteStateMsg(&msg); + pP2pEnabledState->ExecuteStateMsg(&msg); +} +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg21, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pServiceRequestList reqList; + msg.SetMessageObj(reqList); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_SERV_DISC_REQ)); + pP2pEnabledState->ExecuteStateMsg(&msg); +} +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg22, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pServiceResponseList respList; + msg.SetMessageObj(respList); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_SERV_DISC_RESP)); + pP2pEnabledState->ExecuteStateMsg(&msg); + + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_FAILURE)); + pP2pEnabledState->ExecuteStateMsg(&msg); +} +HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg23, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::EXCEPTION_TIMED_OUT)); + pP2pEnabledState->ExecuteStateMsg(&msg); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabling_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabling_state_test.cpp new file mode 100644 index 000000000..6e51c66d5 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabling_state_test.cpp @@ -0,0 +1,79 @@ +/* + * 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 "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" +#include "p2p_enabling_state.h" +#include "mock_p2p_monitor.h" +#include "mock_wifi_settings.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class P2pEnablingStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pP2pEnablingState.reset( + new P2pEnablingState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + } + virtual void TearDown() + { + pP2pEnablingState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + } + +public: + std::unique_ptr pP2pEnablingState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(P2pEnablingStateTest, GoInState, TestSize.Level1) +{ + pP2pEnablingState->GoInState(); +} + +HWTEST_F(P2pEnablingStateTest, GoOutState, TestSize.Level1) +{ + pP2pEnablingState->GoOutState(); +} + +HWTEST_F(P2pEnablingStateTest, ExecuteStateMsg, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::WPA_CONNECTED_EVENT)); + pP2pEnablingState->ExecuteStateMsg(&msg); + + EXPECT_CALL(pMockP2pPendant->GetMockP2pMonitor(), MonitorEnds(_)).WillOnce(Return()); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE)); + pP2pEnablingState->ExecuteStateMsg(&msg); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_STOP_DEVICE_DISCOVERS)); + pP2pEnablingState->ExecuteStateMsg(&msg); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_formation_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_formation_state_test.cpp new file mode 100644 index 000000000..674f817dc --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_formation_state_test.cpp @@ -0,0 +1,77 @@ +/* + * 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 "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" +#include "p2p_group_formation_state.h" +#include "mock_p2p_monitor.h" +#include "mock_wifi_settings.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class P2pGroupFormationStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pP2pGroupFormationState.reset( + new P2pGroupFormationState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + } + virtual void TearDown() + { + pP2pGroupFormationState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + } + +public: + std::unique_ptr pP2pGroupFormationState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(P2pGroupFormationStateTest, GoInState, TestSize.Level1) +{ + pP2pGroupFormationState->GoInState(); +} + +HWTEST_F(P2pGroupFormationStateTest, GoOutState, TestSize.Level1) +{ + pP2pGroupFormationState->GoOutState(); +} + +HWTEST_F(P2pGroupFormationStateTest, ExecuteStateMsg, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DEVICE_DISCOVERS)); + pP2pGroupFormationState->ExecuteStateMsg(&msg); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_LOST)); + pP2pGroupFormationState->ExecuteStateMsg(&msg); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RECEIVED)); + pP2pGroupFormationState->ExecuteStateMsg(&msg); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_join_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_join_state_test.cpp new file mode 100644 index 000000000..af65684bb --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_join_state_test.cpp @@ -0,0 +1,120 @@ +/* + * 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 "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" +#include "p2p_group_join_state.h" +#include "mock_p2p_monitor.h" +#include "mock_wifi_settings.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class P2pGroupJoinStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pP2pGroupJoinState.reset( + new P2pGroupJoinState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + pGroupFormedState.reset( + new GroupFormedState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + } + virtual void TearDown() + { + pP2pGroupJoinState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pGroupFormedState.reset(); + pMockP2pPendant.reset(); + } + +public: + void AddSaveP2pConfig1() + { + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_PBC_REQ)); + + WifiP2pTempDiscEvent procDisc; + + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + procDisc.SetDevice(device); + msg.SetMessageObj(procDisc); + pGroupFormedState->ExecuteStateMsg(&msg); + } + void AddSaveP2pConfig2() + { + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_ENTER_PIN)); + + WifiP2pTempDiscEvent procDisc; + + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + procDisc.SetDevice(device); + msg.SetMessageObj(procDisc); + pGroupFormedState->ExecuteStateMsg(&msg); + } + std::unique_ptr pP2pGroupJoinState; + std::unique_ptr pMockP2pPendant; + std::unique_ptr pGroupFormedState; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(P2pGroupJoinStateTest, GoInState, TestSize.Level1) +{ + pP2pGroupJoinState->GoInState(); +} + +HWTEST_F(P2pGroupJoinStateTest, GoOutState, TestSize.Level1) +{ + pP2pGroupJoinState->GoOutState(); +} + +HWTEST_F(P2pGroupJoinStateTest, ExecuteStateMsg, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_FAILURE)); + pP2pGroupJoinState->ExecuteStateMsg(&msg); + + AddSaveP2pConfig2(); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::INTERNAL_CONN_USER_ACCEPT)); + std::string inputPin; + msg.SetMessageObj(inputPin); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), StartWpsPin(_, _, _, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), StartWpsPbc(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pP2pGroupJoinState->ExecuteStateMsg(&msg); + AddSaveP2pConfig1(); + pP2pGroupJoinState->ExecuteStateMsg(&msg); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::PEER_CONNECTION_USER_REJECT)); + pP2pGroupJoinState->ExecuteStateMsg(&msg); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_operating_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_operating_state_test.cpp new file mode 100644 index 000000000..c593cef8e --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_operating_state_test.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 +#include + +#include "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" +#include "p2p_group_operating_state.h" +#include "mock_p2p_monitor.h" +#include "mock_wifi_settings.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class P2pGroupOperatingStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pP2pGroupOperatingState.reset( + new P2pGroupOperatingState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + pP2pGroupOperatingState->Init(); + } + virtual void TearDown() + { + pP2pGroupOperatingState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + } + +public: + void AddGroupManager() + { + pP2pGroupOperatingState->groupManager.ClearAll(); + WifiP2pGroupInfo group; + group.SetP2pGroupStatus(P2pGroupStatus::GS_STARTED); + group.SetNetworkId(1); + group.SetIsPersistent(true); + pP2pGroupOperatingState->groupManager.AddGroup(group); + pP2pGroupOperatingState->groupManager.SetCurrentGroup(group); + } + std::unique_ptr pP2pGroupOperatingState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(P2pGroupOperatingStateTest, GoInState, TestSize.Level1) +{ + pP2pGroupOperatingState->GoInState(); +} + +HWTEST_F(P2pGroupOperatingStateTest, GoOutState, TestSize.Level1) +{ + pP2pGroupOperatingState->GoOutState(); +} + +HWTEST_F(P2pGroupOperatingStateTest, ExecuteStateMsg1, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_FORM_GROUP)); + WifiP2pConfig config; + config.SetNetId(0); + msg.SetMessageObj(config); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupAdd(_, _, _)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); + + config.SetNetId(-2); + msg.SetMessageObj(config); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupAdd(_, _, _)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); + + config.SetNetId(-1); + msg.SetMessageObj(config); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupAdd(_, _, _)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); + + config.SetNetId(-5); + msg.SetMessageObj(config); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pGroupOperatingStateTest, ExecuteStateMsg2, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); + WifiP2pGroupInfo group; + group.SetIsPersistent(true); + msg.SetMessageObj(group); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); + group.SetIsPersistent(false); + msg.SetMessageObj(group); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); + + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CREATE_GROUP_TIMED_OUT)); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); + + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE)); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pGroupOperatingStateTest, ExecuteStateMsg3, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_REMOVE_GROUP)); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); + + AddGroupManager(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupRemove(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); + AddGroupManager(); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pGroupOperatingStateTest, ExecuteStateMsg4, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DELETE_GROUP)); + AddGroupManager(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RemoveNetwork(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupRemove(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + WifiP2pGroupInfo group; + group.SetNetworkId(1); + msg.SetMessageObj(group); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pGroupOperatingStateTest, ExecuteStateMsg5, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DELETE_GROUP)); + AddGroupManager(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RemoveNetwork(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupRemove(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + WifiP2pGroupInfo group; + group.SetNetworkId(1); + msg.SetMessageObj(group); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pGroupOperatingStateTest, ExecuteStateMsg6, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DISCONNECT)); + EXPECT_FALSE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DELETE_GROUP)); + AddGroupManager(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RemoveNetwork(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + WifiP2pGroupInfo group; + group.SetNetworkId(2); + msg.SetMessageObj(group); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); + EXPECT_FALSE(pP2pGroupOperatingState->ExecuteStateMsg(nullptr)); +} + +HWTEST_F(P2pGroupOperatingStateTest, ProcessGroupRemovedEvt, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_REMOVED)); + AddGroupManager(); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); + EXPECT_FALSE(pP2pGroupOperatingState->ExecuteStateMsg(nullptr)); + + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_PBC_REQ)); + EXPECT_FALSE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_idle_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_idle_state_test.cpp new file mode 100644 index 000000000..33e2b821c --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_idle_state_test.cpp @@ -0,0 +1,259 @@ + +/* + * 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 "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" +#include "p2p_idle_state.h" +#include "mock_p2p_monitor.h" +#include "mock_wifi_settings.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class P2pIdleStateTest : public testing::Test { + const int TEST_CONFIG_METHOD1 = 8; + const int TEST_CONFIG_METHOD2 = 128; + const int TEST_CONFIG_METHOD3 = 256; + +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pP2pIdleState.reset(new P2pIdleState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + pP2pIdleState->Init(); + } + virtual void TearDown() + { + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pP2pIdleState.reset(); + pMockP2pPendant.reset(); + } + +public: + void AddGroupManager() const + { + pP2pIdleState->groupManager.ClearAll(); + WifiP2pGroupInfo group; + group.SetP2pGroupStatus(P2pGroupStatus::GS_STARTED); + group.SetNetworkId(1); + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + group.SetOwner(device); + pP2pIdleState->groupManager.AddGroup(group); + pP2pIdleState->groupManager.SetCurrentGroup(group); + } + void AddDeviceManager() const + { + WifiP2pDevice device; + device.SetDeviceName("device"); + device.SetWpsConfigMethod(P2pIdleStateTest::TEST_CONFIG_METHOD2); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + device.SetGroupCapabilitys(static_cast(P2pGroupCapability::PGC_GROUP_OWNER)); + device.SetPrimaryDeviceType("10-0050F204-5"); + pMockP2pPendant->AddDevice(device); + } + void AddDeviceManager1() const + { + pP2pIdleState->deviceManager.ClearAll(); + WifiP2pDevice device; + device.SetDeviceName("device"); + device.SetWpsConfigMethod(P2pIdleStateTest::TEST_CONFIG_METHOD2); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + device.SetGroupCapabilitys(static_cast(P2pGroupCapability::PGC_GROUP_OWNER)); + device.SetPrimaryDeviceType("10-0050F204-5"); + pP2pIdleState->deviceManager.AddDevice(device); + } + void AddDeviceManager2() const + { + pP2pIdleState->deviceManager.ClearAll(); + WifiP2pDevice device; + device.SetDeviceName("device"); + device.SetWpsConfigMethod(P2pIdleStateTest::TEST_CONFIG_METHOD1); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + device.SetGroupCapabilitys(static_cast(P2pGroupCapability::PGC_GROUP_OWNER)); + device.SetPrimaryDeviceType("10-0050F204-5"); + pP2pIdleState->deviceManager.AddDevice(device); + } + void AddDeviceManager3() const + { + pP2pIdleState->deviceManager.ClearAll(); + WifiP2pDevice device; + device.SetDeviceName("device"); + device.SetWpsConfigMethod(P2pIdleStateTest::TEST_CONFIG_METHOD3); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + device.SetGroupCapabilitys(static_cast(P2pGroupCapability::PGC_GROUP_OWNER)); + device.SetPrimaryDeviceType("10-0050F204-5"); + pP2pIdleState->deviceManager.AddDevice(device); + } + std::unique_ptr pP2pIdleState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(P2pIdleStateTest, GoInState, TestSize.Level1) +{ + pP2pIdleState->GoInState(); +} + +HWTEST_F(P2pIdleStateTest, GoOutState, TestSize.Level1) +{ + pP2pIdleState->GoOutState(); +} + +HWTEST_F(P2pIdleStateTest, ExecuteStateMsg1, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_STOP_DEVICE_DISCOVERS)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pFlush()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); + + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ExecuteStateMsg2, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); + WifiP2pConfig config; + msg.SetMessageObj(config); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); + + AddDeviceManager(); + config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + msg.SetMessageObj(config); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), IsConfigUnusable(_)).WillOnce(Return(P2pConfigErrCode::SUCCESS)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ExecuteStateMsg, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); + WifiP2pConfig config; + AddDeviceManager(); + config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + msg.SetMessageObj(config); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), IsConfigUnusable(_)).WillOnce(Return(P2pConfigErrCode::SUCCESS)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ExecuteStateMsg3, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_ENTER_PIN)); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); + + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_SHOW_PIN)); + WifiP2pTempDiscEvent provDisc; + msg.SetMessageObj(provDisc); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ExecuteStateMsg4, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DISCONNECT)); + EXPECT_FALSE(pP2pIdleState->ExecuteStateMsg(&msg)); + + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RECEIVED)); + WifiP2pGroupInfo group; + WifiP2pDevice device; + + group.SetNetworkId(-1); + msg.SetMessageObj(group); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); + + group.SetNetworkId(1); + msg.SetMessageObj(group); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); + + AddGroupManager(); + device.SetDeviceAddress(""); + group.SetOwner(device); + msg.SetMessageObj(group); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); + + AddDeviceManager1(); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); + + AddDeviceManager2(); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); + + AddDeviceManager3(); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ExecuteStateMsg5, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GO_NEG_REQUEST)); + WifiP2pConfig conf; + msg.SetMessageObj(conf); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ExecuteStateMsg6, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pGroupInfo group; + group.SetIsPersistent(true); + msg.SetMessageObj(group); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_REMOVED)); + EXPECT_FALSE(pP2pIdleState->ExecuteStateMsg(&msg)); + EXPECT_FALSE(pP2pIdleState->ExecuteStateMsg(nullptr)); +} + +HWTEST_F(P2pIdleStateTest, ProcessCmdDeleteGroup, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DELETE_GROUP)); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ProcessCmdRemoveGroup, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_REMOVE_GROUP)); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ProcessCmdCreateGroup, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_FORM_GROUP)); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_inviting_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_inviting_state_test.cpp new file mode 100644 index 000000000..de6f13838 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_inviting_state_test.cpp @@ -0,0 +1,79 @@ +/* + * 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 "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" +#include "p2p_inviting_state.h" +#include "mock_p2p_monitor.h" +#include "mock_wifi_settings.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class P2pInvitingStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pP2pInvitingState.reset( + new P2pInvitingState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + } + virtual void TearDown() + { + pP2pInvitingState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + } + +public: + std::unique_ptr pP2pInvitingState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(P2pInvitingStateTest, GoInState, TestSize.Level1) +{ + pP2pInvitingState->GoInState(); +} + +HWTEST_F(P2pInvitingStateTest, GoOutState, TestSize.Level1) +{ + pP2pInvitingState->GoOutState(); +} + +HWTEST_F(P2pInvitingStateTest, ExecuteStateMsg, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DEVICE_DISCOVERS)); + pP2pInvitingState->ExecuteStateMsg(&msg); + + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_LOST)); + pP2pInvitingState->ExecuteStateMsg(&msg); + + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_FOUND)); + pP2pInvitingState->ExecuteStateMsg(&msg); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_monitor_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_monitor_test.cpp new file mode 100644 index 000000000..20e4a4c34 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_monitor_test.cpp @@ -0,0 +1,671 @@ +/* + * 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 "p2p_monitor.h" +#include "mock_wifi_p2p_hal_interface.h" +#include "wifi_logger.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; +const char *g_pIface = "test0"; + +namespace OHOS { +namespace Wifi { +class P2pMonitorTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + const int testDevCap = 10; + const int testGroupCap = 15; + const int testCfgMethod = 6; + pP2pMonitor.reset(new P2pMonitor); + testDevice.SetDeviceName(std::string("UnitTestDeviceName")); + testDevice.SetDeviceAddress(std::string("ff:ff:ff:ff:ff:ff")); + testDevice.SetPrimaryDeviceType(std::string("1-111111-1")); + testDevice.SetDeviceCapabilitys(testDevCap); + testDevice.SetGroupCapabilitys(testGroupCap); + testDevice.SetWpsConfigMethod(testCfgMethod); + testDevice.SetP2pDeviceStatus(P2pDeviceStatus::PDS_AVAILABLE); + } + virtual void TearDown() + { + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pP2pMonitor.reset(); + } + +public: + void WrapMethodSendMessage( + const std::string &iface, P2P_STATE_MACHINE_CMD msgName, int param1, int param2, const std::any &anyObj) const + { + pP2pMonitor->MessageToStateMachine(iface, msgName, param1, param2, anyObj); + } + + P2pStatus WrapMethodIntStatusToP2pStatus(int status) const + { + return pP2pMonitor->IntStatusToP2pStatus(status); + } + + void WrapMethodBroadcast2SmConnectSupplicant(const std::string &iface, int status) const + { + pP2pMonitor->Broadcast2SmConnectSupplicant(iface, status); + } + + void WrapMethodBroadcast2SmDeviceFound(const std::string &iface, const WifiP2pDevice &device) const + { + pP2pMonitor->Broadcast2SmDeviceFound(iface, device); + } + + void WrapMethodBroadcast2SmDeviceLost(const std::string &iface, const WifiP2pDevice &device) const + { + pP2pMonitor->Broadcast2SmDeviceLost(iface, device); + } + + void WrapMethodBroadcast2SmGoNegRequest(const std::string &iface, const WifiP2pConfig &config) const + { + pP2pMonitor->Broadcast2SmGoNegRequest(iface, config); + } + + void WrapMethodBroadcast2SmGoNegSuccess(const std::string &iface) const + { + pP2pMonitor->Broadcast2SmGoNegSuccess(iface); + } + + void WrapMethodBroadcast2SmGoNegFailure(const std::string &iface, P2pStatus p2pStatus) const + { + pP2pMonitor->Broadcast2SmGoNegFailure(iface, p2pStatus); + } + + void WrapMethodBroadcast2SmInvitationReceived(const std::string &iface, const WifiP2pGroupInfo &group) const + { + pP2pMonitor->Broadcast2SmInvitationReceived(iface, group); + } + + void WrapMethodBroadcast2SmInvitationResult(const std::string &iface, P2pStatus p2pStatus) const + { + pP2pMonitor->Broadcast2SmInvitationResult(iface, p2pStatus); + } + + void WrapMethodBroadcast2SmGroupFormationSuccess(const std::string &iface) const + { + pP2pMonitor->Broadcast2SmGroupFormationSuccess(iface); + } + + void WrapMethodBroadcast2SmGroupFormationFailure(const std::string &iface, const std::string &reason) const + { + pP2pMonitor->Broadcast2SmGroupFormationFailure(iface, reason); + } + + void WrapMethodBroadcast2SmGroupStarted(const std::string &iface, const WifiP2pGroupInfo &group) const + { + pP2pMonitor->Broadcast2SmGroupStarted(iface, group); + } + + void WrapMethodBroadcast2SmGroupRemoved(const std::string &iface, const WifiP2pGroupInfo &group) const + { + pP2pMonitor->Broadcast2SmGroupRemoved(iface, group); + } + + void WrapMethodBroadcast2SmProvDiscPbcReq(const std::string &iface, const WifiP2pTempDiscEvent &event) const + { + pP2pMonitor->Broadcast2SmProvDiscPbcReq(iface, event); + } + + void WrapMethodBroadcast2SmProvDiscPbcResp(const std::string &iface, const WifiP2pTempDiscEvent &event) const + { + pP2pMonitor->Broadcast2SmProvDiscPbcResp(iface, event); + } + + void WrapMethodBroadcast2SmProvDiscEnterPin(const std::string &iface, const WifiP2pTempDiscEvent &event) const + { + pP2pMonitor->Broadcast2SmProvDiscEnterPin(iface, event); + } + + void WrapMethodBroadcast2SmProvDiscShowPin(const std::string &iface, const WifiP2pTempDiscEvent &event) const + { + pP2pMonitor->Broadcast2SmProvDiscShowPin(iface, event); + } + + void WrapMethodBroadcast2SmProvDiscFailure(const std::string &iface) const + { + pP2pMonitor->Broadcast2SmProvDiscFailure(iface); + } + + void WrapMethodBroadcast2SmFindStopped(const std::string &iface) const + { + pP2pMonitor->Broadcast2SmFindStopped(iface); + } + void WrapMethodBroadcast2SmServDiscReq(const std::string &iface, const WifiP2pServiceRequestList &reqList) const + { + pP2pMonitor->Broadcast2SmServDiscReq(iface, reqList); + } + void WrapMethodBroadcast2SmServDiscResp(const std::string &iface, const WifiP2pServiceResponseList &respList) const + { + pP2pMonitor->Broadcast2SmServDiscResp(iface, respList); + } + + void WrapMethodBroadcast2SmApStaDisconnected(const std::string &iface, const WifiP2pDevice &device) const + { + pP2pMonitor->Broadcast2SmApStaDisconnected(iface, device); + } + + void WrapMethodBroadcast2SmApStaConnected(const std::string &iface, const WifiP2pDevice &device) const + { + pP2pMonitor->Broadcast2SmApStaConnected(iface, device); + } + + void WrapMethodBroadcast2SmConnectSupplicantFailed(const std::string &iface) const + { + pP2pMonitor->Broadcast2SmConnectSupplicantFailed(iface); + } + + void WrapMethodOnConnectSupplicant(int status) + { + pP2pMonitor->OnConnectSupplicant(status); + } + + void WrapMethodOnDeviceFound(IdlP2pDeviceFound deviceInfo) + { + pP2pMonitor->WpaEventDeviceFound(deviceInfo); + } + + void WrapMethodOnDeviceLost(const std::string &p2pDeviceAddress) + { + pP2pMonitor->WpaEventDeviceLost(p2pDeviceAddress); + } + + void WrapMethodOnGoNegRequest(const std::string &srcAddress, short passwordId) + { + pP2pMonitor->WpaEventGoNegRequest(srcAddress, passwordId); + } + + void WrapMethodOnGoNegSuccess() + { + pP2pMonitor->WpaEventGoNegSuccess(); + } + + void WrapMethodOnGoNegFailure(int status) + { + pP2pMonitor->WpaEventGoNegFailure(status); + } + + void WrapMethodOnInvitationReceived(IdlP2pInvitationInfo recvInfo) + { + pP2pMonitor->WpaEventInvitationReceived(recvInfo); + } + + void WrapMethodOnInvitationResult(const std::string &bssid, int status) + { + pP2pMonitor->WpaEventInvitationResult(bssid, status); + } + + void WrapMethodOnGroupFormationSuccess() + { + pP2pMonitor->WpaEventGroupFormationSuccess(); + } + + void WrapMethodOnGroupFormationFailure(const std::string &failureReason) + { + pP2pMonitor->WpaEventGroupFormationFailure(failureReason); + } + + void WrapMethodOnGroupStarted(IdlP2pGroupInfo groupInfo) + { + pP2pMonitor->WpaEventGroupStarted(groupInfo); + } + + void WrapMethodOnGroupRemoved(const std::string &groupIfName, bool isGo) + { + pP2pMonitor->WpaEventGroupRemoved(groupIfName, isGo); + } + + void WrapMethodOnProvDiscPbcReq(const std::string &p2pDeviceAddress) + { + pP2pMonitor->WpaEventProvDiscPbcReq(p2pDeviceAddress); + } + + void WrapMethodOnProvDiscPbcResp(const std::string &p2pDeviceAddress) + { + pP2pMonitor->WpaEventProvDiscPbcResp(p2pDeviceAddress); + } + + void WrapMethodOnProvDiscEnterPin(const std::string &p2pDeviceAddress) + { + pP2pMonitor->WpaEventProvDiscEnterPin(p2pDeviceAddress); + } + + void WrapMethodOnProvDiscShowPin(const std::string &p2pDeviceAddress, const std::string &generatedPin) + { + pP2pMonitor->WpaEventProvDiscShowPin(p2pDeviceAddress, generatedPin); + } + + void WrapMethodOnProvDiscFailure() + { + pP2pMonitor->WpaEventProvDiscFailure(); + } + + void WrapMethodOnFindStopped() + { + pP2pMonitor->WpaEventFindStopped(); + } + void WrapMethodOnServDiscReq(IdlP2pServDiscReqInfo reqInfo) + { + pP2pMonitor->WpaEventServDiscReq(reqInfo); + } + + void WrapMethodOnServDiscResp( + const std::string &srcAddress, short updateIndicator, const std::vector &tlvs) + { + pP2pMonitor->WpaEventServDiscResp(srcAddress, updateIndicator, tlvs); + } + + void WrapMethodOnApStaDisconnected(const std::string &p2pDeviceAddress) + { + pP2pMonitor->WpaEventApStaDisconnected(p2pDeviceAddress); + } + + void WrapMethodOnApStaConnected(const std::string &p2pDeviceAddress) + { + pP2pMonitor->WpaEventApStaConnected(p2pDeviceAddress); + } + + void WrapMethodOnConnectSupplicantFailed() + { + pP2pMonitor->OnConnectSupplicantFailed(); + } + + const std::set &WrapDataSetMonitorIface() + { + return pP2pMonitor->setMonitorIface; + } + +public: + std::unique_ptr pP2pMonitor; + WifiP2pDevice testDevice; +}; + +HWTEST_F(P2pMonitorTest, Initialize_SUCCESS, TestSize.Level1) +{ + pP2pMonitor->Initialize(); +} +HWTEST_F(P2pMonitorTest, RegisterHandler_SUCCESS, TestSize.Level1) +{ + const std::string iface = g_pIface; + const std::function mapHandler; + pP2pMonitor->RegisterIfaceHandler(iface, mapHandler); +} +HWTEST_F(P2pMonitorTest, UnregisterHandler_SUCCESS, TestSize.Level1) +{ + const std::string iface = g_pIface; + pP2pMonitor->UnregisterHandler(iface); +} + +HWTEST_F(P2pMonitorTest, WrapMethod_test, TestSize.Level1) +{ + const std::string iface = g_pIface; + constexpr P2P_STATE_MACHINE_CMD msgName = P2P_STATE_MACHINE_CMD::WPA_CONNECTED_EVENT; + constexpr int param1 = 0; + constexpr int param2 = 1; + const std::any anyObj = std::string("test_any"); + WrapMethodSendMessage(iface, msgName, param1, param2, anyObj); +} + +HWTEST_F(P2pMonitorTest, WrapMethod_data, TestSize.Level1) +{ + const std::string iface = g_pIface; + const std::set &setMonitorIface = WrapDataSetMonitorIface(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pP2pMonitor->MonitorEnds(iface); + EXPECT_TRUE(setMonitorIface.count(iface) == 0); + + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pP2pMonitor->MonitorBegins(iface); + EXPECT_TRUE(setMonitorIface.count(iface) == 1); +} + +HWTEST_F(P2pMonitorTest, IntStatusToP2pStatus, TestSize.Level1) +{ + EXPECT_TRUE(WrapMethodIntStatusToP2pStatus(0) == P2pStatus::SUCCESS); + + EXPECT_TRUE(WrapMethodIntStatusToP2pStatus(5) == P2pStatus::UNABLE_TO_ACCOMMODATE_REQUEST); + + EXPECT_TRUE(WrapMethodIntStatusToP2pStatus(11) == P2pStatus::REJECTED_BY_USER); + + EXPECT_TRUE(WrapMethodIntStatusToP2pStatus(-1) == P2pStatus::UNKNOWN); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmConnectSupplicant, TestSize.Level1) +{ + const std::string iface = g_pIface; + int status = 1; + WrapMethodBroadcast2SmConnectSupplicant(iface, status); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmDeviceFound, TestSize.Level1) +{ + const std::string iface = g_pIface; + WrapMethodBroadcast2SmDeviceFound(iface, testDevice); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmDeviceLost, TestSize.Level1) +{ + const std::string iface = g_pIface; + WrapMethodBroadcast2SmDeviceLost(iface, testDevice); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmGoNegRequest, TestSize.Level1) +{ + const std::string iface = g_pIface; + WifiP2pConfig testConfig; + WrapMethodBroadcast2SmGoNegRequest(iface, testConfig); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmGoNegSuccess, TestSize.Level1) +{ + const std::string iface = g_pIface; + WrapMethodBroadcast2SmGoNegSuccess(iface); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmGoNegFailure, TestSize.Level1) +{ + const std::string iface = g_pIface; + P2pStatus testStatus = P2pStatus::SUCCESS; + WrapMethodBroadcast2SmGoNegFailure(iface, testStatus); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmInvitationReceived, TestSize.Level1) +{ + const std::string iface = g_pIface; + WifiP2pGroupInfo testGroup; + WrapMethodBroadcast2SmInvitationReceived(iface, testGroup); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmInvitationResult, TestSize.Level1) +{ + const std::string iface = g_pIface; + P2pStatus testStatus = P2pStatus::SUCCESS; + WrapMethodBroadcast2SmInvitationResult(iface, testStatus); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmGroupFormationSuccess, TestSize.Level1) +{ + const std::string iface = g_pIface; + WrapMethodBroadcast2SmGroupFormationSuccess(iface); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmGroupFormationFailure, TestSize.Level1) +{ + const std::string iface = g_pIface; + const std::string reason("P2pUnitTest"); + WrapMethodBroadcast2SmGroupFormationFailure(iface, reason); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmGroupStarted, TestSize.Level1) +{ + const std::string iface = g_pIface; + WifiP2pGroupInfo testGroup; + WrapMethodBroadcast2SmGroupStarted(iface, testGroup); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmGroupRemoved, TestSize.Level1) +{ + const std::string iface = g_pIface; + WifiP2pGroupInfo testGroup; + WrapMethodBroadcast2SmGroupRemoved(iface, testGroup); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmProvDiscPbcReq, TestSize.Level1) +{ + const std::string iface = g_pIface; + WifiP2pTempDiscEvent testEvent; + WrapMethodBroadcast2SmProvDiscPbcReq(iface, testEvent); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmProvDiscPbcResp, TestSize.Level1) +{ + const std::string iface = g_pIface; + WifiP2pTempDiscEvent testEvent; + WrapMethodBroadcast2SmProvDiscPbcResp(iface, testEvent); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmProvDiscEnterPin, TestSize.Level1) +{ + const std::string iface = g_pIface; + WifiP2pTempDiscEvent testEvent; + WrapMethodBroadcast2SmProvDiscEnterPin(iface, testEvent); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmProvDiscShowPin, TestSize.Level1) +{ + const std::string iface = g_pIface; + WifiP2pTempDiscEvent testEvent; + WrapMethodBroadcast2SmProvDiscShowPin(iface, testEvent); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmProvDiscFailure, TestSize.Level1) +{ + const std::string iface = g_pIface; + WrapMethodBroadcast2SmProvDiscFailure(iface); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmFindStopped, TestSize.Level1) +{ + const std::string iface = g_pIface; + WrapMethodBroadcast2SmFindStopped(iface); +} +HWTEST_F(P2pMonitorTest, Broadcast2SmServDiscReq, TestSize.Level1) +{ + const std::string iface = g_pIface; + WifiP2pServiceRequestList testRequeList; + WrapMethodBroadcast2SmServDiscReq(iface, testRequeList); +} +HWTEST_F(P2pMonitorTest, Broadcast2SmServDiscResp, TestSize.Level1) +{ + const std::string iface = g_pIface; + WifiP2pServiceResponseList testRespList; + WrapMethodBroadcast2SmServDiscResp(iface, testRespList); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmApStaDisconnected, TestSize.Level1) +{ + const std::string iface = g_pIface; + WrapMethodBroadcast2SmApStaDisconnected(iface, testDevice); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmApStaConnected, TestSize.Level1) +{ + const std::string iface = g_pIface; + WrapMethodBroadcast2SmApStaConnected(iface, testDevice); +} + +HWTEST_F(P2pMonitorTest, Broadcast2SmConnectSupplicantFailed, TestSize.Level1) +{ + const std::string iface = g_pIface; + WrapMethodBroadcast2SmConnectSupplicantFailed(iface); +} + +HWTEST_F(P2pMonitorTest, OnConnectSupplicant, TestSize.Level1) +{ + int status = 1; + WrapMethodOnConnectSupplicant(status); +} + +HWTEST_F(P2pMonitorTest, WpaEventDeviceFound, TestSize.Level1) +{ + IdlP2pDeviceFound deviceInfo; + deviceInfo.srcAddress = "ff:ff:ff:ff:ff:ff"; + deviceInfo.p2pDeviceAddress = "ff:ff:ff:ff:ff:ff"; + deviceInfo.primaryDeviceType = "1-111111-1"; + deviceInfo.deviceName = "P2pUnitTest"; + deviceInfo.configMethods = 10; + deviceInfo.deviceCapabilities = 8; + deviceInfo.groupCapabilities = 12; + deviceInfo.wfdDeviceInfo.push_back('1'); + deviceInfo.wfdDeviceInfo.push_back('5'); + deviceInfo.wfdDeviceInfo.push_back('a'); + deviceInfo.wfdDeviceInfo.push_back('3'); + deviceInfo.wfdDeviceInfo.push_back('6'); + deviceInfo.wfdDeviceInfo.push_back('e'); + deviceInfo.wfdDeviceInfo.push_back('8'); + deviceInfo.wfdDeviceInfo.push_back('8'); + WrapMethodOnDeviceFound(deviceInfo); +} + +HWTEST_F(P2pMonitorTest, WpaEventDeviceLost, TestSize.Level1) +{ + WrapMethodOnDeviceLost("ff:ff:ff:ff:ff:ff"); +} + +HWTEST_F(P2pMonitorTest, WpaEventGoNegRequest, TestSize.Level1) +{ + short testPasswordId = 8; + WrapMethodOnGoNegRequest("ff:ff:ff:ff:ff:ff", testPasswordId); +} + +HWTEST_F(P2pMonitorTest, WpaEventGoNegSuccess, TestSize.Level1) +{ + WrapMethodOnGoNegSuccess(); +} + +HWTEST_F(P2pMonitorTest, WpaEventGoNegFailure, TestSize.Level1) +{ + int testStatus = 1; + WrapMethodOnGoNegFailure(testStatus); +} + +HWTEST_F(P2pMonitorTest, WpaEventInvitationReceived, TestSize.Level1) +{ + IdlP2pInvitationInfo testRecvInfo; + testRecvInfo.persistentNetworkId = 1; + testRecvInfo.operatingFrequency = 6; + testRecvInfo.srcAddress = "ff:ff:ff:ff:ff:ff"; + testRecvInfo.goDeviceAddress = "ff:ff:ff:ff:ff:fe"; + testRecvInfo.bssid = "ff:ff:ff:ff:ff:ef"; + WrapMethodOnInvitationReceived(testRecvInfo); +} + +HWTEST_F(P2pMonitorTest, WpaEventInvitationResult, TestSize.Level1) +{ + int testStatus = 1; + WrapMethodOnInvitationResult("ff:ff:ff:ff:ff:ff", testStatus); +} + +HWTEST_F(P2pMonitorTest, WpaEventGroupFormationSuccess, TestSize.Level1) +{ + WrapMethodOnGroupFormationSuccess(); +} + +HWTEST_F(P2pMonitorTest, WpaEventGroupFormationFailure, TestSize.Level1) +{ + WrapMethodOnGroupFormationFailure("P2pUnitTestReason"); +} + +HWTEST_F(P2pMonitorTest, WpaEventGroupStarted, TestSize.Level1) +{ + IdlP2pGroupInfo testGroupInfo; + testGroupInfo.isGo = true; + testGroupInfo.isPersistent = true; + testGroupInfo.frequency = 6; + testGroupInfo.groupName = "P2pUnitTestWlan"; + testGroupInfo.ssid = "P2pUnitTestGroup"; + testGroupInfo.psk = "123456789"; + testGroupInfo.passphrase = "TestPassphrase"; + testGroupInfo.goDeviceAddress = "ff:ff:ff:ff:ff:ff"; + WrapMethodOnGroupStarted(testGroupInfo); +} + +HWTEST_F(P2pMonitorTest, WpaEventGroupRemoved, TestSize.Level1) +{ + bool isGo = true; + WrapMethodOnGroupRemoved("P2pUnitTestWlan", isGo); +} + +HWTEST_F(P2pMonitorTest, WpaEventProvDiscPbcReq, TestSize.Level1) +{ + WrapMethodOnProvDiscPbcReq("ff:ff:ff:ff:ff:ff"); +} + +HWTEST_F(P2pMonitorTest, WpaEventProvDiscPbcResp, TestSize.Level1) +{ + WrapMethodOnProvDiscPbcResp("ff:ff:ff:ff:ff:ff"); +} + +HWTEST_F(P2pMonitorTest, WpaEventProvDiscEnterPin, TestSize.Level1) +{ + WrapMethodOnProvDiscEnterPin("ff:ff:ff:ff:ff:ff"); +} + +HWTEST_F(P2pMonitorTest, WpaEventProvDiscShowPin, TestSize.Level1) +{ + WrapMethodOnProvDiscShowPin("ff:ff:ff:ff:ff:ff", "TestGeneratedPin"); +} + +HWTEST_F(P2pMonitorTest, WpaEventProvDiscFailure, TestSize.Level1) +{ + WrapMethodOnProvDiscFailure(); +} + +HWTEST_F(P2pMonitorTest, WpaEventFindStopped, TestSize.Level1) +{ + WrapMethodOnFindStopped(); +} + +HWTEST_F(P2pMonitorTest, WpaEventServDiscReq, TestSize.Level1) +{ + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + const std::string iface = g_pIface; + pP2pMonitor->MonitorBegins(iface); + IdlP2pServDiscReqInfo info; + std::vector tList; + info.tlvList = tList; + info.mac = "111"; + WrapMethodOnServDiscReq(info); +} + +HWTEST_F(P2pMonitorTest, WpaEventServDiscResp, TestSize.Level1) +{ + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + const std::string iface = g_pIface; + pP2pMonitor->MonitorBegins(iface); + short testUpdateIndicator = 5; + const std::vector testTlvs; + WrapMethodOnServDiscResp("ff:ff:ff:ff:ff:ff", testUpdateIndicator, testTlvs); +} + +HWTEST_F(P2pMonitorTest, WpaEventApStaDisconnected, TestSize.Level1) +{ + WrapMethodOnApStaDisconnected("ff:ff:ff:ff:ff:ff"); +} + +HWTEST_F(P2pMonitorTest, WpaEventApStaConnected, TestSize.Level1) +{ + WrapMethodOnApStaConnected("ff:ff:ff:ff:ff:ff"); +} + +HWTEST_F(P2pMonitorTest, OnConnectSupplicantFailed, TestSize.Level1) +{ + WrapMethodOnConnectSupplicantFailed(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_state_machine_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_state_machine_test.cpp new file mode 100644 index 000000000..8a927007c --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_state_machine_test.cpp @@ -0,0 +1,640 @@ +/* + * 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 "p2p_state_machine.h" +#include "mock_p2p_pendant.h" +#include "wifi_p2p_msg.h" +#include "mock_p2p_monitor.h" +#include "mock_authorizing_negotiation_request_state.h" +#include "mock_group_formed_state.h" +#include "mock_group_negotiation_state.h" +#include "mock_invitation_recelved_state.h" +#include "mock_invitation_request_state.h" +#include "mock_p2p_default_state.h" +#include "mock_p2p_disabled_state.h" +#include "mock_p2p_disabling_state.h" +#include "mock_p2p_enabled_state.h" +#include "mock_p2p_enabling_state.h" +#include "mock_p2p_group_formation_state.h" +#include "mock_p2p_group_join_state.h" +#include "mock_p2p_group_operating_state.h" +#include "mock_p2p_idle_state.h" +#include "mock_p2p_inviting_state.h" +#include "mock_p2p_state_machine.h" +#include "mock_provision_discovery_state.h" +#include "mock_wifi_p2p_hal_interface.h" +#include "mock_wifi_settings.h" +#include "wifi_logger.h" + +using ::testing::_; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::ext::TestSize; + +DEFINE_WIFILOG_P2P_LABEL("p2pStateMachineTest"); +namespace OHOS { +namespace Wifi { +class P2pStateMachineTest : public testing::Test { +public: + ~P2pStateMachineTest() + {} + P2pStateMachineTest() : pMockP2pPendant(nullptr), groupManager(), deviceManager(), svrManager() + {} + static void SetUpTestCase(){} + static void TearDownTestCase(){} + virtual void SetUp() + { + WifiP2PHalInterface::GetInstance(); + pMockP2pPendant = new MockP2pPendant(); + pMockAuthorizingNegotiationRequestState = &pMockP2pPendant->GetMockAuthorizingNegotiationRequestState(); + pMockGroupFormedState = &pMockP2pPendant->GetMockGroupFormedState(); + pMockGroupNegotiationState = &pMockP2pPendant->GetMockGroupNegotiationState(); + pMockInvitationReceivedState = &pMockP2pPendant->GetMockInvitationReceivedState(); + pMockInvitationRequestState = &pMockP2pPendant->GetMockInvitationRequestState(); + pMockP2pDefaultState = &pMockP2pPendant->GetMockP2pDefaultState(); + pMockP2pDisabledState = &pMockP2pPendant->GetMockP2pDisabledState(); + pMockP2pDisablingState = &pMockP2pPendant->GetMockP2pDisablingState(); + pMockP2pEnabledState = &pMockP2pPendant->GetMockP2pEnabledState(); + pMockP2pEnablingState = &pMockP2pPendant->GetMockP2pEnablingState(); + pMockP2pGroupFormationState = &pMockP2pPendant->GetMockP2pGroupFormationState(); + pMockP2pGroupJoinState = &pMockP2pPendant->GetMockP2pGroupJoinState(); + pMockP2pGroupOperatingState = &pMockP2pPendant->GetMockP2pGroupOperatingState(); + pMockP2pIdleState = &pMockP2pPendant->GetMockP2pIdleState(); + pMockP2pInvitingState = &pMockP2pPendant->GetMockP2pInvitingState(); + pMockProvisionDiscoveryState = &pMockP2pPendant->GetMockProvisionDiscoveryState(); + pMockP2pMonitor = &pMockP2pPendant->GetMockP2pMonitor(); + pP2pStateMachine.reset(new P2pStateMachine(*pMockP2pMonitor, + groupManager, + deviceManager, + svrManager, + *pMockAuthorizingNegotiationRequestState, + *pMockGroupFormedState, + *pMockGroupNegotiationState, + *pMockInvitationReceivedState, + *pMockInvitationRequestState, + *pMockP2pDefaultState, + *pMockP2pDisabledState, + *pMockP2pDisablingState, + *pMockP2pEnabledState, + *pMockP2pEnablingState, + *pMockP2pGroupFormationState, + *pMockP2pGroupJoinState, + *pMockP2pGroupOperatingState, + *pMockP2pIdleState, + *pMockP2pInvitingState, + *pMockProvisionDiscoveryState)); + pP2pStateMachine->groupManager.Initialize(); + } + virtual void TearDown() + { + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pP2pStateMachine.reset(); + delete pMockP2pPendant; + pMockAuthorizingNegotiationRequestState = nullptr; + pMockGroupFormedState = nullptr; + pMockGroupNegotiationState = nullptr; + pMockInvitationReceivedState = nullptr; + pMockInvitationRequestState = nullptr; + pMockP2pDefaultState = nullptr; + pMockP2pDisabledState = nullptr; + pMockP2pDisablingState = nullptr; + pMockP2pEnabledState = nullptr; + pMockP2pEnablingState = nullptr; + pMockP2pGroupFormationState = nullptr; + pMockP2pGroupJoinState = nullptr; + pMockP2pGroupOperatingState = nullptr; + pMockP2pIdleState = nullptr; + pMockP2pInvitingState = nullptr; + pMockProvisionDiscoveryState = nullptr; + pMockP2pMonitor = nullptr; + } + +public: + std::unique_ptr pP2pStateMachine; + MockP2pPendant *pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; + WifiP2pServiceManager svrManager; + + MockAuthorizingNegotiationRequestState *pMockAuthorizingNegotiationRequestState; + MockGroupFormedState *pMockGroupFormedState; + MockGroupNegotiationState *pMockGroupNegotiationState; + MockInvitationReceivedState *pMockInvitationReceivedState; + MockInvitationRequestState *pMockInvitationRequestState; + MockP2pDefaultState *pMockP2pDefaultState; + MockP2pDisabledState *pMockP2pDisabledState; + MockP2pDisablingState *pMockP2pDisablingState; + MockP2pEnabledState *pMockP2pEnabledState; + MockP2pEnablingState *pMockP2pEnablingState; + MockP2pGroupFormationState *pMockP2pGroupFormationState; + MockP2pGroupJoinState *pMockP2pGroupJoinState; + MockP2pGroupOperatingState *pMockP2pGroupOperatingState; + MockP2pIdleState *pMockP2pIdleState; + MockP2pInvitingState *pMockP2pInvitingState; + MockProvisionDiscoveryState *pMockProvisionDiscoveryState; + MockP2pMonitor *pMockP2pMonitor; + +public: + void Addsvr() + { + pP2pStateMachine->serviceManager.SetQueryId("queryId"); + } + void AddDeviceManager() + { + WifiP2pDevice device; + device.SetDeviceName("device"); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + device.SetGroupCapabilitys(static_cast(P2pGroupCapability::PGC_GROUP_OWNER)); + device.SetPrimaryDeviceType("10-0050F204-5"); + pP2pStateMachine->deviceManager.AddDevice(device); + } + void AddDeviceManagerLimit() + { + WifiP2pDevice device; + device.SetDeviceName("device"); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + device.SetGroupCapabilitys(static_cast(P2pGroupCapability::PGC_GROUP_LIMIT)); + device.SetPrimaryDeviceType("10-0050F204-5"); + pP2pStateMachine->deviceManager.AddDevice(device); + } + void AddDeviceManagerInViteable() + { + WifiP2pDevice device; + device.SetDeviceName("device"); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + device.SetGroupCapabilitys(static_cast(P2pGroupCapability::PGC_PERSISTENT_RECONN)); + device.SetPrimaryDeviceType("10-0050F204-5"); + device.SetDeviceCapabilitys(static_cast(P2pDeviceCapability::PDC_INVITATION_PROCEDURE)); + pP2pStateMachine->deviceManager.AddDevice(device); + } + void AddGroupManager() + { + WifiP2pGroupInfo groupInfo; + groupInfo.SetNetworkId(0); + groupInfo.SetGroupName("AAA"); + groupInfo.SetIsGroupOwner(true); + WifiP2pDevice owner; + owner.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + groupInfo.SetOwner(owner); + pP2pStateMachine->groupManager.AddGroup(groupInfo); + } + void AddGroupManager2() + { + WifiP2pGroupInfo groupInfo; + groupInfo.SetNetworkId(-1); + groupInfo.SetGroupName("AAA"); + groupInfo.SetIsGroupOwner(true); + WifiP2pDevice owner; + owner.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + groupInfo.SetOwner(owner); + pP2pStateMachine->groupManager.AddGroup(groupInfo); + } + void WarpHandlerDiscoverPeers() + { + pP2pStateMachine->HandlerDiscoverPeers(); + } + void WarpRegisterEventHandler() + { + pP2pStateMachine->RegisterEventHandler(); + } + + void WarpUpdateThisDevice() + { + pP2pStateMachine->UpdateOwnDevice(P2pDeviceStatus::PDS_CONNECTED); + } + void WarpUpdatePersistentGroups() + { + pP2pStateMachine->UpdatePersistentGroups(); + } + + bool WarpReinvokePersistentGroup(WifiP2pConfig &config) const + { + return pP2pStateMachine->ReawakenPersistentGroup(config); + } + void WarpFetchNewerDeviceInfo(const std::string &deviceAddr) const + { + pP2pStateMachine->FetchNewerDeviceInfo(deviceAddr); + } + void WarpDealGroupCreationFailed() + { + pP2pStateMachine->DealGroupCreationFailed(); + } + void WarpRemoveGroupByNetworkId(int networkId) const + { + pP2pStateMachine->RemoveGroupByNetworkId(networkId); + } + void WarpSetWifiP2pInfoOnGroupFormed(const std::string &groupOwnerAddress) + { + pP2pStateMachine->SetWifiP2pInfoWhenGroupFormed(groupOwnerAddress); + } + void WarpInitializeThisDevice() + { + pP2pStateMachine->InitializeThisDevice(); + } + bool WarpIsUsableNetworkName(std::string nwName) + { + return pP2pStateMachine->IsUsableNetworkName(nwName); + } + P2pConfigErrCode WarpIsConfigUnusable(const WifiP2pConfig &config) + { + return pP2pStateMachine->IsConfigUnusable(config); + } + bool WarpIsConfigUsableAsGroup(WifiP2pConfig config) + { + return pP2pStateMachine->IsConfigUsableAsGroup(config); + } + void WarpCleanSupplicantServiceReq() + { + pP2pStateMachine->CancelSupplicantSrvDiscReq(); + } + + void WarpBroadcastP2pStatusChanged(P2pState state) const + { + pP2pStateMachine->BroadcastP2pStatusChanged(state); + } + void WarpBroadcastP2pPeersChanged() const + { + pP2pStateMachine->BroadcastP2pPeersChanged(); + } + void WarpBroadcastP2pServicesChanged() const + { + pP2pStateMachine->BroadcastP2pServicesChanged(); + } + void WarpBroadcastP2pConnectionChanged() const + { + pP2pStateMachine->BroadcastP2pConnectionChanged(); + } + void WarpBroadcastThisDeviceChanaged(const WifiP2pDevice &device) const + { + pP2pStateMachine->BroadcastThisDeviceChanaged(device); + } + void WarpBroadcastP2pDiscoveryChanged(bool isActive) const + { + pP2pStateMachine->BroadcastP2pDiscoveryChanged(isActive); + } + void WarpBroadcastPersistentGroupsChanged() const + { + pP2pStateMachine->BroadcastPersistentGroupsChanged(); + } + void WarpBroadcastActionResult(P2pActionCallback action, ErrCode result) const + { + pP2pStateMachine->BroadcastActionResult(action, result); + } + + void WarpNotifyInvitationSent(const std::string &pin, const std::string &peerAddress) const + { + pP2pStateMachine->NotifyUserInvitationSentMessage(pin, peerAddress); + } + void WarpNotifyP2pProvDiscShowPinRequest(const std::string &pin, const std::string &peerAddress) + { + pP2pStateMachine->NotifyUserProvDiscShowPinRequestMessage(pin, peerAddress); + } + void WarpP2pConnectWithPinDisplay(const WifiP2pConfig &config) const + { + pP2pStateMachine->P2pConnectByShowingPin(config); + } + void WarpNotifyInvitationReceived() + { + pP2pStateMachine->NotifyUserInvitationReceivedMessage(); + } + void WarpNotifyInvitationReceived2() + { + WpsInfo info; + info.SetWpsMethod(WpsMethod::WPS_METHOD_KEYPAD); + pP2pStateMachine->savedP2pConfig.SetWpsInfo(info); + pP2pStateMachine->NotifyUserInvitationReceivedMessage(); + } + void WarpNotifyInvitationReceived3() + { + WpsInfo info; + info.SetWpsMethod(WpsMethod::WPS_METHOD_DISPLAY); + pP2pStateMachine->savedP2pConfig.SetWpsInfo(info); + pP2pStateMachine->NotifyUserInvitationReceivedMessage(); + } + + void WarpClearWifiP2pInfo() + { + pP2pStateMachine->ClearWifiP2pInfo(); + } +}; + +void ButtonTest(AlertDialog &dialog, std::any ctx) +{ + printf("button callback, input = %s\n", dialog.GetInputBox("input pin").c_str()); +} + +HWTEST_F(P2pStateMachineTest, RegisterP2pServiceCallbacks_SUCCESS, TestSize.Level1) +{ + IP2pServiceCallbacks callback; + pP2pStateMachine->RegisterP2pServiceCallbacks(callback); +} + +HWTEST_F(P2pStateMachineTest, HandlerDiscoverPeers, TestSize.Level1) +{ + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pFind(DISC_TIMEOUT_S)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + WarpHandlerDiscoverPeers(); +} + +HWTEST_F(P2pStateMachineTest, HandlerDiscoverPeers2, TestSize.Level1) +{ + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pFind(DISC_TIMEOUT_S)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + WarpHandlerDiscoverPeers(); +} + +HWTEST_F(P2pStateMachineTest, RegisterEventHandler, TestSize.Level1) +{ + EXPECT_CALL(*pMockP2pMonitor, RegisterIfaceHandler(_, _)); + WarpRegisterEventHandler(); +} + +HWTEST_F(P2pStateMachineTest, UpdateOwnDevice, TestSize.Level1) +{ + WarpUpdateThisDevice(); +} + +HWTEST_F(P2pStateMachineTest, UpdatePersistentGroups_SUCCESS, TestSize.Level1) +{ + std::map mapGroups; + WifiP2pGroupInfo p2pGroupInfo; + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + p2pGroupInfo.SetOwner(device); + mapGroups[100] = p2pGroupInfo; + deviceManager.AddDevice(device); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)) + .WillOnce(DoAll(SetArgReferee<0>(mapGroups), Return(WifiErrorNo::WIFI_IDL_OPT_OK))); + WarpUpdatePersistentGroups(); +} + +HWTEST_F(P2pStateMachineTest, UpdatePersistentGroups_FAILED, TestSize.Level1) +{ + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + WarpUpdatePersistentGroups(); +} + +HWTEST_F(P2pStateMachineTest, P2pConnectWithPinDisplay_SUCCESS, TestSize.Level1) +{ + WifiP2pConfig conf; + WarpP2pConnectWithPinDisplay(conf); + + conf.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + WarpP2pConnectWithPinDisplay(conf); + + AddDeviceManager(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), Connect(_, _, _)) + .WillOnce(DoAll(SetArgReferee<2>("11"), Return(WifiErrorNo::WIFI_IDL_OPT_FAILED))); + WarpP2pConnectWithPinDisplay(conf); +} + +HWTEST_F(P2pStateMachineTest, DealGroupCreationFailed, TestSize.Level1) +{ + WarpDealGroupCreationFailed(); +} + +HWTEST_F(P2pStateMachineTest, RemoveGroupByNetworkId, TestSize.Level1) +{ + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RemoveNetwork(Eq(1))) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + WarpRemoveGroupByNetworkId(1); +} + +HWTEST_F(P2pStateMachineTest, SetWifiP2pInfoWhenGroupFormed, TestSize.Level1) +{ + WarpSetWifiP2pInfoOnGroupFormed("AA:BB:CC:DD:EE:FF"); +} + +HWTEST_F(P2pStateMachineTest, InitializeThisDevice1, TestSize.Level1) +{ + P2pVendorConfig vendorconfig, a; + vendorconfig.SetDeviceName("DeviceName"); + vendorconfig.SetPrimaryDeviceType("DeviceType"); + vendorconfig.SetRandomMacSupport(true); + WarpInitializeThisDevice(); +} + +HWTEST_F(P2pStateMachineTest, InitializeThisDevice2, TestSize.Level1) +{ + P2pVendorConfig vendorconfig; + vendorconfig.SetDeviceName(""); + vendorconfig.SetPrimaryDeviceType("DeviceType"); + vendorconfig.SetRandomMacSupport(true); + WarpInitializeThisDevice(); +} + +HWTEST_F(P2pStateMachineTest, IsUsableNetworkName, TestSize.Level1) +{ + EXPECT_FALSE(WarpIsUsableNetworkName("")); + EXPECT_TRUE(WarpIsUsableNetworkName("12345678910")); + EXPECT_FALSE(WarpIsUsableNetworkName("1")); +} + +HWTEST_F(P2pStateMachineTest, IsConfigUnusable, TestSize.Level1) +{ + WifiP2pConfig config; + config.SetDeviceAddress(""); + EXPECT_TRUE(WarpIsConfigUnusable(config) == P2pConfigErrCode::MAC_EMPTY); + AddDeviceManager(); + config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + EXPECT_FALSE(WarpIsConfigUnusable(config) == P2pConfigErrCode::SUCCESS); + config.SetDeviceAddress("aa:cc:bb:dd:ee:ff"); + EXPECT_TRUE(WarpIsConfigUnusable(config) == P2pConfigErrCode::MAC_NOT_FOUND); + config.SetDeviceAddress("aa:cc::bb:dd:ee:ff"); + EXPECT_TRUE(WarpIsConfigUnusable(config) == P2pConfigErrCode::ERR_MAC_FORMAT); +} + +HWTEST_F(P2pStateMachineTest, IsConfigUsableAsGroup, TestSize.Level1) +{ + WifiP2pConfig config; + config.SetDeviceAddress(""); + EXPECT_FALSE(WarpIsConfigUsableAsGroup(config)); + config.SetDeviceAddress("1"); + EXPECT_FALSE(WarpIsConfigUsableAsGroup(config)); + config.SetNetworkName("12345678910"); + config.SetPassphrase("12345678910"); + EXPECT_TRUE(WarpIsConfigUsableAsGroup(config)); +} + +HWTEST_F(P2pStateMachineTest, CancelSupplicantSrvDiscReq, TestSize.Level1) +{ + WarpCleanSupplicantServiceReq(); + Addsvr(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), CancelReqServiceDiscovery(testing::StrEq("queryId"))) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + WarpCleanSupplicantServiceReq(); + Addsvr(); + WarpCleanSupplicantServiceReq(); +} + +HWTEST_F(P2pStateMachineTest, BroadcastP2pStatusChanged, TestSize.Level1) +{ + IP2pServiceCallbacks callback; + callback.OnP2pStateChangedEvent = [](P2pState state) { WIFI_LOGI("lamda"); }; + pP2pStateMachine->RegisterP2pServiceCallbacks(callback); + WarpBroadcastP2pStatusChanged(P2pState::P2P_STATE_STARTED); +} + +HWTEST_F(P2pStateMachineTest, BroadcastP2pPeersChanged, TestSize.Level1) +{ + IP2pServiceCallbacks callback; + callback.OnP2pPeersChangedEvent = [](const std::vector &) { WIFI_LOGI("lamda"); }; + pP2pStateMachine->RegisterP2pServiceCallbacks(callback); + WarpBroadcastP2pPeersChanged(); +} + +HWTEST_F(P2pStateMachineTest, BroadcastP2pServicesChanged, TestSize.Level1) +{ + IP2pServiceCallbacks callback; + callback.OnP2pServicesChangedEvent = [](const std::vector &) { WIFI_LOGI("lamda"); }; + pP2pStateMachine->RegisterP2pServiceCallbacks(callback); + WarpBroadcastP2pServicesChanged(); +} + +HWTEST_F(P2pStateMachineTest, BroadcastP2pConnectionChanged, TestSize.Level1) +{ + IP2pServiceCallbacks callback; + callback.OnP2pConnectionChangedEvent = [](const WifiP2pInfo &) { WIFI_LOGI("lamda"); }; + pP2pStateMachine->RegisterP2pServiceCallbacks(callback); + WarpBroadcastP2pConnectionChanged(); +} + +HWTEST_F(P2pStateMachineTest, BroadcastThisDeviceChanaged, TestSize.Level1) +{ + IP2pServiceCallbacks callback; + callback.OnP2pThisDeviceChangedEvent = [](const WifiP2pDevice &) { WIFI_LOGI("lamda"); }; + pP2pStateMachine->RegisterP2pServiceCallbacks(callback); + WifiP2pDevice device; + WarpBroadcastThisDeviceChanaged(device); +} + +HWTEST_F(P2pStateMachineTest, BroadcastP2pDiscoveryChanged, TestSize.Level1) +{ + IP2pServiceCallbacks callback; + callback.OnP2pDiscoveryChangedEvent = [](bool) { WIFI_LOGI("lamda"); }; + pP2pStateMachine->RegisterP2pServiceCallbacks(callback); + WarpBroadcastP2pDiscoveryChanged(true); +} + +HWTEST_F(P2pStateMachineTest, BroadcastPersistentGroupsChanged, TestSize.Level1) +{ + IP2pServiceCallbacks callback; + callback.OnP2pGroupsChangedEvent = []() { WIFI_LOGI("lamda"); }; + pP2pStateMachine->RegisterP2pServiceCallbacks(callback); + WarpBroadcastPersistentGroupsChanged(); +} + +HWTEST_F(P2pStateMachineTest, BroadcastActionResult, TestSize.Level1) +{ + IP2pServiceCallbacks callback; + callback.OnP2pActionResultEvent = [](P2pActionCallback, ErrCode) { WIFI_LOGI("lamda"); }; + pP2pStateMachine->RegisterP2pServiceCallbacks(callback); + WarpBroadcastActionResult(P2pActionCallback::PutLocalP2pService, ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(P2pStateMachineTest, NotifyUserProvDiscShowPinRequestMessage, TestSize.Level1) +{ + std::string pin; + const std::string peerAddress; + WarpNotifyP2pProvDiscShowPinRequest(pin, peerAddress); +} + +HWTEST_F(P2pStateMachineTest, NotifyUserInvitationSentMessage, TestSize.Level1) +{ + std::string pin; + const std::string peerAddress; + WarpNotifyInvitationSent(pin, peerAddress); +} + +HWTEST_F(P2pStateMachineTest, NotifyInvitationReceived1, TestSize.Level1) +{ + WarpNotifyInvitationReceived(); +} + +HWTEST_F(P2pStateMachineTest, NotifyInvitationReceived2, TestSize.Level1) +{ + WarpNotifyInvitationReceived2(); +} + +HWTEST_F(P2pStateMachineTest, NotifyInvitationReceived3, TestSize.Level1) +{ + WarpNotifyInvitationReceived3(); +} + +HWTEST_F(P2pStateMachineTest, ClearWifiP2pInfo, TestSize.Level1) +{ + WarpClearWifiP2pInfo(); +} + +HWTEST_F(P2pStateMachineTest, ReinvokePersistentGroup1, TestSize.Level1) +{ + WifiP2pConfig config; + EXPECT_FALSE(WarpReinvokePersistentGroup(config)); + + config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + config.SetNetworkName("AAA"); + AddGroupManager(); + AddDeviceManager(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupAdd(_, _, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(WarpReinvokePersistentGroup(config)); + EXPECT_FALSE(WarpReinvokePersistentGroup(config)); +} + +HWTEST_F(P2pStateMachineTest, ReinvokePersistentGroup2, TestSize.Level1) +{ + WifiP2pConfig config; + config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + config.SetNetworkName("AAA"); + AddGroupManager(); + AddDeviceManagerLimit(); + EXPECT_FALSE(WarpReinvokePersistentGroup(config)); +} + +HWTEST_F(P2pStateMachineTest, ReinvokePersistentGroup3, TestSize.Level1) +{ + WifiP2pConfig config; + config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + config.SetNetworkName("AAA"); + config.SetNetId(2); + AddGroupManager(); + AddDeviceManagerInViteable(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), Reinvoke(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(WarpReinvokePersistentGroup(config)); + EXPECT_FALSE(WarpReinvokePersistentGroup(config)); +} + +HWTEST_F(P2pStateMachineTest, ReinvokePersistentGroup4, TestSize.Level1) +{ + WifiP2pConfig config; + config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + config.SetNetworkName("AAA"); + config.SetNetId(3); + AddGroupManager2(); + AddDeviceManagerInViteable(); + EXPECT_FALSE(WarpReinvokePersistentGroup(config)); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/provision_discovery_state_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/provision_discovery_state_test.cpp new file mode 100644 index 000000000..365b3f4ad --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/provision_discovery_state_test.cpp @@ -0,0 +1,185 @@ +/* + * 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 "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" +#include "provision_discovery_state.h" +#include "mock_p2p_monitor.h" +#include "mock_wifi_settings.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class ProvisionDiscoveryStateTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pProvisionDiscoveryState.reset( + new ProvisionDiscoveryState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + pGroupFormedState.reset( + new GroupFormedState(pMockP2pPendant->GetP2pStateMachine(), groupManager, deviceManager)); + pProvisionDiscoveryState->Init(); + } + virtual void TearDown() + { + pProvisionDiscoveryState.reset(); + pGroupFormedState.reset(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); + pMockP2pPendant.reset(); + } + +public: + void AddSaveP2pConfig1() + { + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_PBC_REQ)); + + WifiP2pTempDiscEvent procDisc; + + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + procDisc.SetDevice(device); + msg.SetMessageObj(procDisc); + pGroupFormedState->ExecuteStateMsg(&msg); + } + void AddSaveP2pConfig2() + { + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_ENTER_PIN)); + WifiP2pTempDiscEvent procDisc; + + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + procDisc.SetDevice(device); + msg.SetMessageObj(procDisc); + pGroupFormedState->ExecuteStateMsg(&msg); + } + void AddSaveP2pConfig3() + { + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_SHOW_PIN)); + + WifiP2pTempDiscEvent procDisc; + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + procDisc.SetDevice(device); + msg.SetMessageObj(procDisc); + pGroupFormedState->ExecuteStateMsg(&msg); + } + std::unique_ptr pProvisionDiscoveryState; + std::unique_ptr pGroupFormedState; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; +}; + +HWTEST_F(ProvisionDiscoveryStateTest, GoInState, TestSize.Level1) +{ + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ProvisionDiscovery(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pProvisionDiscoveryState->GoInState(); +} + +HWTEST_F(ProvisionDiscoveryStateTest, GoOutState, TestSize.Level1) +{ + pProvisionDiscoveryState->GoOutState(); +} + +HWTEST_F(ProvisionDiscoveryStateTest, ExecuteStateMsg1, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DEVICE_DISCOVERS)); + EXPECT_TRUE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); + + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_PBC_RESP)); + + WifiP2pTempDiscEvent provDisc; + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + provDisc.SetDevice(device); + msg.SetMessageObj(provDisc); + EXPECT_TRUE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); + + AddSaveP2pConfig1(); + EXPECT_TRUE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(ProvisionDiscoveryStateTest, ExecuteStateMsg2, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_ENTER_PIN)); + + WifiP2pTempDiscEvent provDisc; + msg.SetMessageObj(provDisc); + EXPECT_TRUE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); + + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + provDisc.SetDevice(device); + msg.SetMessageObj(provDisc); + AddSaveP2pConfig2(); + EXPECT_TRUE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); + + device.SetDeviceAddress("AA:BB:CC:DD:EE:FA"); + provDisc.SetDevice(device); + msg.SetMessageObj(provDisc); + EXPECT_TRUE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(ProvisionDiscoveryStateTest, ExecuteStateMsg3, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_SHOW_PIN)); + + WifiP2pTempDiscEvent provDisc; + msg.SetMessageObj(provDisc); + EXPECT_TRUE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + provDisc.SetDevice(device); + msg.SetMessageObj(provDisc); + EXPECT_TRUE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); + + AddSaveP2pConfig3(); + EXPECT_TRUE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(ProvisionDiscoveryStateTest, ExecuteStateMsg4, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::AP_STA_CONNECTED)); + EXPECT_FALSE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); + EXPECT_FALSE(pProvisionDiscoveryState->ExecuteStateMsg(nullptr)); +} + +HWTEST_F(ProvisionDiscoveryStateTest, ProcessProvDiscFailEvt, TestSize.Level1) +{ + InternalMessage msg; + + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::PEER_CONNECTION_USER_REJECT)); + EXPECT_FALSE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_device_manager_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_device_manager_test.cpp new file mode 100644 index 000000000..aaeac9f5c --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_device_manager_test.cpp @@ -0,0 +1,152 @@ +/* + * 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.0wifi_p2p_device_manager_test.cpp + * + * 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 "wifi_p2p_device_manager.h" +#include "wifi_logger.h" + +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class WifiP2pDeviceManagerTest : public testing::Test { +public: + static void SetUpTestCase(){} + static void TearDownTestCase(){} + virtual void SetUp() + { + pWifiP2pDeviceManager.reset(new WifiP2pDeviceManager()); + int decCapa = 1; + int groCapa = 1; + + device1.SetDeviceAddress(std::string("aa:bb:cc:dd:ee:11")); + device1.SetDeviceName(std::string("Test1")); + device1.SetDeviceCapabilitys(decCapa); + device1.SetGroupCapabilitys(groCapa); + device1.SetP2pDeviceStatus(P2pDeviceStatus::PDS_UNAVAILABLE); + device1.SetPrimaryDeviceType("Test1 Type"); + device1.SetWpsConfigMethod(static_cast(WpsConfigMethod::WPS_CFG_INVALID)); + + device2.SetDeviceAddress(std::string("aa:bb:cc:dd:ee:22")); + device2.SetDeviceName(std::string("Test2")); + device2.SetDeviceCapabilitys(decCapa); + device2.SetGroupCapabilitys(groCapa); + device2.SetP2pDeviceStatus(P2pDeviceStatus::PDS_UNAVAILABLE); + device2.SetPrimaryDeviceType("Test2 Type"); + device2.SetWpsConfigMethod(static_cast(WpsConfigMethod::WPS_CFG_INVALID)); + }; + virtual void TearDown() + { + pWifiP2pDeviceManager.reset(); + } + +public: + WifiP2pDevice device1; + WifiP2pDevice device2; + std::unique_ptr pWifiP2pDeviceManager; +}; + +HWTEST_F(WifiP2pDeviceManagerTest, Initialize_SUCCESS, TestSize.Level1) +{ + pWifiP2pDeviceManager->Initialize(); +} + +HWTEST_F(WifiP2pDeviceManagerTest, AddDevice_SUCCESS, TestSize.Level1) +{ + WifiP2pDevice device; + EXPECT_FALSE(pWifiP2pDeviceManager->AddDevice(device)); + EXPECT_TRUE(pWifiP2pDeviceManager->AddDevice(device1)); + EXPECT_FALSE(pWifiP2pDeviceManager->AddDevice(device1)); +} + +HWTEST_F(WifiP2pDeviceManagerTest, RemoveDevice_SUCCESS, TestSize.Level1) +{ + EXPECT_TRUE(pWifiP2pDeviceManager->AddDevice(device1)); + EXPECT_FALSE(pWifiP2pDeviceManager->AddDevice(device1)); + EXPECT_TRUE(pWifiP2pDeviceManager->RemoveDevice(device1)); + EXPECT_FALSE(pWifiP2pDeviceManager->RemoveDevice(device1)); +} + +HWTEST_F(WifiP2pDeviceManagerTest, ClearAll_SUCCESS, TestSize.Level1) +{ + EXPECT_TRUE(pWifiP2pDeviceManager->AddDevice(device1)); + EXPECT_EQ(pWifiP2pDeviceManager->ClearAll(), 1); +} + +HWTEST_F(WifiP2pDeviceManagerTest, GetDevicesList_SUCCESS, TestSize.Level1) +{ + std::vector decVec; + EXPECT_TRUE(pWifiP2pDeviceManager->AddDevice(device1)); + EXPECT_EQ(pWifiP2pDeviceManager->GetDevicesList(decVec), 1); + EXPECT_EQ(decVec[0], device1); +} + +HWTEST_F(WifiP2pDeviceManagerTest, UpdateDevice_SUCCESS, TestSize.Level1) +{ + WifiP2pDevice device; + EXPECT_FALSE(pWifiP2pDeviceManager->UpdateDevice(device)); + + EXPECT_TRUE(pWifiP2pDeviceManager->AddDevice(device1)); + EXPECT_TRUE(pWifiP2pDeviceManager->UpdateDevice(device1)); + EXPECT_TRUE(pWifiP2pDeviceManager->UpdateDevice(device2)); +} + +HWTEST_F(WifiP2pDeviceManagerTest, UpdateDeviceSupplicantInf_SUCCESS, TestSize.Level1) +{ + WifiP2pDevice device; + EXPECT_FALSE(pWifiP2pDeviceManager->UpdateDeviceSupplicantInf(device)); + + EXPECT_TRUE(pWifiP2pDeviceManager->AddDevice(device1)); + EXPECT_TRUE(pWifiP2pDeviceManager->UpdateDeviceSupplicantInf(device1)); + EXPECT_TRUE(pWifiP2pDeviceManager->UpdateDeviceSupplicantInf(device2)); +} + +HWTEST_F(WifiP2pDeviceManagerTest, UpdateGroupCapability_SUCCESS, TestSize.Level1) +{ + EXPECT_FALSE(pWifiP2pDeviceManager->UpdateDeviceGroupCap("", 1)); + + EXPECT_TRUE(pWifiP2pDeviceManager->AddDevice(device1)); + EXPECT_TRUE(pWifiP2pDeviceManager->UpdateDeviceGroupCap("aa:bb:cc:dd:ee:11", 1)); + EXPECT_FALSE(pWifiP2pDeviceManager->UpdateDeviceGroupCap("aa:bb:cc:ad:ee:11", 1)); + WifiP2pDevice device; + EXPECT_FALSE(pWifiP2pDeviceManager->UpdateDeviceGroupCap(device)); + EXPECT_FALSE(pWifiP2pDeviceManager->UpdateDeviceGroupCap(device2)); +} + +HWTEST_F(WifiP2pDeviceManagerTest, UpdateDeviceStatus_SUCCESS, TestSize.Level1) +{ + WifiP2pDevice device; + EXPECT_FALSE(pWifiP2pDeviceManager->UpdateDeviceStatus(device)); + EXPECT_FALSE(pWifiP2pDeviceManager->UpdateDeviceStatus(device1)); + + EXPECT_FALSE(pWifiP2pDeviceManager->UpdateDeviceStatus("", P2pDeviceStatus::PDS_CONNECTED)); + EXPECT_TRUE(pWifiP2pDeviceManager->AddDevice(device1)); + EXPECT_TRUE(pWifiP2pDeviceManager->UpdateDeviceStatus("aa:bb:cc:dd:ee:11", P2pDeviceStatus::PDS_CONNECTED)); + EXPECT_FALSE(pWifiP2pDeviceManager->UpdateDeviceStatus("aa:bb:cc:dd:ea:11", P2pDeviceStatus::PDS_CONNECTED)); +} + +HWTEST_F(WifiP2pDeviceManagerTest, GetDevices_SUCCESS, TestSize.Level1) +{ + WifiP2pDevice ret; + EXPECT_EQ(ret, pWifiP2pDeviceManager->GetDevices("")); + + EXPECT_TRUE(pWifiP2pDeviceManager->AddDevice(device1)); + EXPECT_EQ(device1, pWifiP2pDeviceManager->GetDevices("aa:bb:cc:dd:ee:11")); + + EXPECT_EQ("Test1", pWifiP2pDeviceManager->GetDeviceName("aa:bb:cc:dd:ee:11")); + EXPECT_EQ("aa:ba:cc:dd:ee:11", pWifiP2pDeviceManager->GetDeviceName("aa:ba:cc:dd:ee:11")); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_info_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_info_test.cpp new file mode 100644 index 000000000..d4cad132e --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_info_test.cpp @@ -0,0 +1,76 @@ +/* + * 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 "wifi_p2p_dns_sd_service_info.h" + +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class WifiP2pDnsSdServiceInfoTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pWifiP2pDnsSdServiceInfo.reset(new WifiP2pDnsSdServiceInfo()); + } + virtual void TearDown() + { + pWifiP2pDnsSdServiceInfo.reset(); + } + +public: + std::unique_ptr pWifiP2pDnsSdServiceInfo; + void WarpCompressDnsName() + { + std::string dnsName = "a.txt"; + EXPECT_EQ("c00c", pWifiP2pDnsSdServiceInfo->TurnDnsNameToStream("_tcp.local.")); + EXPECT_EQ("c011", pWifiP2pDnsSdServiceInfo->TurnDnsNameToStream("local.")); + EXPECT_EQ("c01c", pWifiP2pDnsSdServiceInfo->TurnDnsNameToStream("_udp.local.")); + EXPECT_EQ("00", pWifiP2pDnsSdServiceInfo->TurnDnsNameToStream("")); + EXPECT_EQ("01610374787400", pWifiP2pDnsSdServiceInfo->TurnDnsNameToStream(dnsName)); + } +}; + +HWTEST_F(WifiP2pDnsSdServiceInfoTest, Create, TestSize.Level1) +{ + std::string instanceName; + std::string serviceType; + std::map txtMap; + std::string svrName; + WifiP2pDnsSdServiceInfo::Create(instanceName, serviceType, txtMap, svrName); +} + +HWTEST_F(WifiP2pDnsSdServiceInfoTest, BuildRequest, TestSize.Level1) +{ + std::string dnsName; + int dnsType = 0; + int version = 0; + std::string instanceName; + std::string serviceType; + std::string svrName; + std::map txtMap; + WifiP2pDnsSdServiceInfo::Create(instanceName, serviceType, txtMap, svrName).BuildRequest(dnsName, dnsType, version); +} +HWTEST_F(WifiP2pDnsSdServiceInfoTest, TurnDnsNameToStream, TestSize.Level1) +{ + WarpCompressDnsName(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_request_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_request_test.cpp new file mode 100644 index 000000000..792d1f5da --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_request_test.cpp @@ -0,0 +1,64 @@ +/* + * 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 "wifi_p2p_dns_sd_service_request.h" + +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class WifiP2pDnsSdServiceRequestTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: + void WarpCreate1() + { + WifiP2pDnsSdServiceRequest::Create(); + } + void WarpCreate2() + { + WifiP2pDnsSdServiceRequest::Create("serviceType"); + } + void WarpCreate3() + { + WifiP2pDnsSdServiceRequest::Create("instanceName", "serviceType"); + } +}; + +HWTEST_F(WifiP2pDnsSdServiceRequestTest, Create1, TestSize.Level1) +{ + WarpCreate1(); +} + +HWTEST_F(WifiP2pDnsSdServiceRequestTest, Create2, TestSize.Level1) +{ + WarpCreate2(); +} + +HWTEST_F(WifiP2pDnsSdServiceRequestTest, Create3, TestSize.Level1) +{ + WarpCreate3(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_response_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_response_test.cpp new file mode 100644 index 000000000..9a96490ff --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_response_test.cpp @@ -0,0 +1,96 @@ +/* + * 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 "wifi_p2p_dns_sd_service_response.h" +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class WifiP2pDnsSdServiceResponseTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + pWifiP2pDnsSdServiceResponse.reset(new WifiP2pDnsSdServiceResponse(resp)); + } + virtual void TearDown() + { + pWifiP2pDnsSdServiceResponse.reset(); + } + +public: + WifiP2pServiceResponse resp; + std::unique_ptr pWifiP2pDnsSdServiceResponse; + void WarpReadTxtData() + { + std::istringstream istream("name"); + pWifiP2pDnsSdServiceResponse->FetchTxtData(istream); + } +}; + +HWTEST_F(WifiP2pDnsSdServiceResponseTest, GetQueryName, TestSize.Level1) +{ + EXPECT_EQ("", pWifiP2pDnsSdServiceResponse->GetQueryName()); +} + +HWTEST_F(WifiP2pDnsSdServiceResponseTest, GetInstanceName, TestSize.Level1) +{ + EXPECT_EQ("", pWifiP2pDnsSdServiceResponse->GetInstanceName()); +} + +HWTEST_F(WifiP2pDnsSdServiceResponseTest, GetDnsType, TestSize.Level1) +{ + EXPECT_EQ(-1, pWifiP2pDnsSdServiceResponse->GetDnsType()); +} + +HWTEST_F(WifiP2pDnsSdServiceResponseTest, GetVersion, TestSize.Level1) +{ + EXPECT_EQ(-1, pWifiP2pDnsSdServiceResponse->GetVersion()); +} + +HWTEST_F(WifiP2pDnsSdServiceResponseTest, GetTxtRecord, TestSize.Level1) +{ + pWifiP2pDnsSdServiceResponse->GetTxtRecord(); +} + +HWTEST_F(WifiP2pDnsSdServiceResponseTest, ParseData, TestSize.Level1) +{ + EXPECT_EQ(true, pWifiP2pDnsSdServiceResponse->ParseData()); + std::vector data; + data.push_back(1); + pWifiP2pDnsSdServiceResponse->SetData(data); + EXPECT_EQ(false, pWifiP2pDnsSdServiceResponse->ParseData()); + + data.clear(); + data.push_back(0x00); + pWifiP2pDnsSdServiceResponse->SetData(data); + EXPECT_EQ(false, pWifiP2pDnsSdServiceResponse->ParseData()); + + data.clear(); + data.push_back(0xc0); + pWifiP2pDnsSdServiceResponse->SetData(data); + EXPECT_EQ(false, pWifiP2pDnsSdServiceResponse->ParseData()); +} + +HWTEST_F(WifiP2pDnsSdServiceResponseTest, FetchTxtData, TestSize.Level1) +{ + WarpReadTxtData(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_info_proxy_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_info_proxy_test.cpp new file mode 100644 index 000000000..a752d217f --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_info_proxy_test.cpp @@ -0,0 +1,82 @@ +/* + * 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 "wifi_p2p_group_info_proxy.h" + +using namespace OHOS; +using namespace Wifi; +using ::testing::ext::TestSize; + +class WifiP2pGroupInfoProxyTest : public testing::Test { +public: + static void SetUpTestCase(){} + static void TearDownTestCase(){} + virtual void SetUp() + { + pWifiP2pGroupInfoProxy.reset(new WifiP2pGroupInfoProxy()); + } + virtual void TearDown() + { + pWifiP2pGroupInfoProxy.reset(); + } + +public: + std::unique_ptr pWifiP2pGroupInfoProxy; +}; + +HWTEST_F(WifiP2pGroupInfoProxyTest, OperatorSuccess, TestSize.Level1) +{ + WifiP2pGroupInfo wifiP2pGroupInfo; + + EXPECT_TRUE((*pWifiP2pGroupInfoProxy) == wifiP2pGroupInfo); + wifiP2pGroupInfo.SetNetworkId(1); + pWifiP2pGroupInfoProxy->SetNetworkId(2); + EXPECT_TRUE((*pWifiP2pGroupInfoProxy) != wifiP2pGroupInfo); +} + +HWTEST_F(WifiP2pGroupInfoProxyTest, CompareSuccess, TestSize.Level1) +{ + pWifiP2pGroupInfoProxy->SetIsGroupOwner(true); + EXPECT_EQ(pWifiP2pGroupInfoProxy->IsGroupOwner(), true); + WifiP2pDevice device, device1, device2; + device.SetDeviceName("device"); + pWifiP2pGroupInfoProxy->SetOwner(device); + EXPECT_EQ(pWifiP2pGroupInfoProxy->GetOwner(), device); + pWifiP2pGroupInfoProxy->SetPassphrase("12345678"); + EXPECT_EQ(pWifiP2pGroupInfoProxy->GetPassphrase(), "12345678"); + pWifiP2pGroupInfoProxy->SetInterface("iface"); + EXPECT_EQ(pWifiP2pGroupInfoProxy->GetInterface(), "iface"); + pWifiP2pGroupInfoProxy->SetGroupName("groupName"); + EXPECT_EQ(pWifiP2pGroupInfoProxy->GetGroupName(), "groupName"); + pWifiP2pGroupInfoProxy->SetFrequency(2020); + EXPECT_EQ(pWifiP2pGroupInfoProxy->GetFrequency(), 2020); + pWifiP2pGroupInfoProxy->SetIsPersistent(true); + EXPECT_EQ(pWifiP2pGroupInfoProxy->IsPersistent(), true); + pWifiP2pGroupInfoProxy->SetP2pGroupStatus(P2pGroupStatus::GS_CREATING); + EXPECT_EQ(pWifiP2pGroupInfoProxy->GetP2pGroupStatus(), P2pGroupStatus::GS_CREATING); + pWifiP2pGroupInfoProxy->SetNetworkId(1); + EXPECT_EQ(pWifiP2pGroupInfoProxy->GetNetworkId(), 1); + pWifiP2pGroupInfoProxy->AddClientDevice(device1); + EXPECT_TRUE(pWifiP2pGroupInfoProxy->IsContainsDevice(device1)); + pWifiP2pGroupInfoProxy->RemoveClientDevice(device1); + std::vector devices; + devices.push_back(device1); + devices.push_back(device2); + pWifiP2pGroupInfoProxy->SetClientDevices(devices); + EXPECT_FALSE(pWifiP2pGroupInfoProxy->IsClientDevicesEmpty()); + pWifiP2pGroupInfoProxy->ClearClientDevices(); + EXPECT_TRUE(pWifiP2pGroupInfoProxy->IsClientDevicesEmpty()); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_manager_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_manager_test.cpp new file mode 100644 index 000000000..5856662b6 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_manager_test.cpp @@ -0,0 +1,182 @@ +/* + * 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 "wifi_p2p_group_manager.h" +#include "mock_wifi_settings.h" + +using ::testing::_; +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +const int SET_FREQUENCY = 6; +const int SET_NETWORKID = 10; + +class WifiP2pGroupManagerTest : public testing::Test { +public: + static void SetUpTestCase(){} + static void TearDownTestCase(){} + virtual void SetUp() + { + pWifiP2pGroupManager.reset(new WifiP2pGroupManager()); + device.SetDeviceName(std::string("UnitTestDevice")); + device.SetDeviceAddress(std::string("12:34:56:78:9a:bc")); + device.SetPrimaryDeviceType(std::string("UnitTestPrimaryDeviceType")); + device.SetP2pDeviceStatus(P2pDeviceStatus::PDS_UNAVAILABLE); + device.SetWpsConfigMethod(static_cast(WpsConfigMethod::WPS_CFG_INVALID)); + + groupInfo.SetIsGroupOwner(true); + groupInfo.SetOwner(device); + groupInfo.SetPassphrase(std::string("UnitTestPassphrase")); + groupInfo.SetInterface(std::string("UnitTestWlan")); + groupInfo.SetGroupName(std::string("UnitTestGroupName")); + groupInfo.SetFrequency(SET_FREQUENCY); + groupInfo.SetIsPersistent(true); + groupInfo.SetP2pGroupStatus(P2pGroupStatus::GS_INVALID); + groupInfo.SetNetworkId(SET_NETWORKID); + groupInfo.SetGoIpAddress(std::string("111.111.111.111")); + groupInfo.AddClientDevice(device); + } + virtual void TearDown() + { + pWifiP2pGroupManager.reset(); + } + WifiP2pGroupInfo groupInfo; + WifiP2pDevice device; + std::unique_ptr pWifiP2pGroupManager; + void WarpRefreshGroupsFromCurrentGroup() + { + pWifiP2pGroupManager->RefreshGroupsFromCurrentGroup(); + } + void WarpRefreshCurrentGroupFromGroups() + { + pWifiP2pGroupManager->RefreshCurrentGroupFromGroups(); + } +}; + +HWTEST_F(WifiP2pGroupManagerTest, Initialize_SUCCESS, TestSize.Level1) +{ + pWifiP2pGroupManager->Initialize(); +} + +HWTEST_F(WifiP2pGroupManagerTest, StashGroups_SUCCESS, TestSize.Level1) +{ + pWifiP2pGroupManager->StashGroups(); +} + +HWTEST_F(WifiP2pGroupManagerTest, AddGroup_SUCCESS, TestSize.Level1) +{ + EXPECT_TRUE(pWifiP2pGroupManager->AddGroup(groupInfo)); + EXPECT_TRUE(pWifiP2pGroupManager->AddGroup(groupInfo)); +} + +HWTEST_F(WifiP2pGroupManagerTest, RemoveGroup, TestSize.Level1) +{ + EXPECT_FALSE(pWifiP2pGroupManager->RemoveGroup(groupInfo)); + EXPECT_TRUE(pWifiP2pGroupManager->AddGroup(groupInfo)); + EXPECT_TRUE(pWifiP2pGroupManager->RemoveGroup(groupInfo)); +} + +HWTEST_F(WifiP2pGroupManagerTest, ClearAll_SUCCESS, TestSize.Level1) +{ + pWifiP2pGroupManager->AddGroup(groupInfo); + EXPECT_EQ(1, pWifiP2pGroupManager->ClearAll()); +} + +HWTEST_F(WifiP2pGroupManagerTest, UpdateWpaGroup_SUCCESS, TestSize.Level1) +{ + pWifiP2pGroupManager->UpdateWpaGroup(groupInfo); + pWifiP2pGroupManager->UpdateWpaGroup(groupInfo); +} + +HWTEST_F(WifiP2pGroupManagerTest, RemoveClientFromGroup_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(-1, pWifiP2pGroupManager->RemoveClientFromGroup(10, "AA:BB:CC:DD:EE:FF")); + + pWifiP2pGroupManager->AddGroup(groupInfo); + pWifiP2pGroupManager->RemoveClientFromGroup(10, "12:34:56:78:9a:bc"); +} + +HWTEST_F(WifiP2pGroupManagerTest, GetGroups_SUCCESS, TestSize.Level1) +{ + std::vector groups, groups1; + pWifiP2pGroupManager->AddGroup(groupInfo); + groups1.push_back(groupInfo); + EXPECT_EQ(groups1, pWifiP2pGroupManager->GetGroups()); +} + +HWTEST_F(WifiP2pGroupManagerTest, GetNetworkIdFromClients_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(-1, pWifiP2pGroupManager->GetNetworkIdFromClients(device)); + pWifiP2pGroupManager->AddGroup(groupInfo); + EXPECT_EQ(10, pWifiP2pGroupManager->GetNetworkIdFromClients(device)); +} + +HWTEST_F(WifiP2pGroupManagerTest, GetNetworkId1_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(-1, pWifiP2pGroupManager->GetGroupNetworkId(device)); + pWifiP2pGroupManager->AddGroup(groupInfo); + EXPECT_EQ(10, pWifiP2pGroupManager->GetGroupNetworkId(device)); +} + +HWTEST_F(WifiP2pGroupManagerTest, GetNetworkId2_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ(-1, pWifiP2pGroupManager->GetGroupNetworkId(device, "name")); + pWifiP2pGroupManager->AddGroup(groupInfo); + EXPECT_EQ(10, pWifiP2pGroupManager->GetGroupNetworkId(device, "UnitTestGroupName")); +} + +HWTEST_F(WifiP2pGroupManagerTest, GetOwnerAddr_SUCCESS, TestSize.Level1) +{ + EXPECT_EQ("", pWifiP2pGroupManager->GetGroupOwnerAddr(10)); + pWifiP2pGroupManager->AddGroup(groupInfo); + EXPECT_EQ("12:34:56:78:9a:bc", pWifiP2pGroupManager->GetGroupOwnerAddr(10)); +} + +HWTEST_F(WifiP2pGroupManagerTest, Contains_SUCCESS, TestSize.Level1) +{ + WifiP2pInfo connInfo; + EXPECT_FALSE(pWifiP2pGroupManager->IsInclude(10)); + pWifiP2pGroupManager->AddGroup(groupInfo); + EXPECT_TRUE(pWifiP2pGroupManager->IsInclude(10)); +} + +HWTEST_F(WifiP2pGroupManagerTest, RefreshGroupsFromCurrentGroup_SUCCESS, TestSize.Level1) +{ + WarpRefreshGroupsFromCurrentGroup(); + WarpRefreshCurrentGroupFromGroups(); +} + +HWTEST_F(WifiP2pGroupManagerTest, SaveP2pInfo_SUCCESS, TestSize.Level1) +{ + WifiP2pInfo connInfo; + pWifiP2pGroupManager->SaveP2pInfo(connInfo); + pWifiP2pGroupManager->GetP2pInfo(); +} + +HWTEST_F(WifiP2pGroupManagerTest, UpdateGroupsNetwork, TestSize.Level1) +{ + EXPECT_TRUE(pWifiP2pGroupManager->AddGroup(groupInfo)); + std::map wpaGroups; + pWifiP2pGroupManager->UpdateGroupsNetwork(wpaGroups); + wpaGroups[1] = groupInfo; + EXPECT_TRUE(pWifiP2pGroupManager->AddGroup(groupInfo)); + pWifiP2pGroupManager->UpdateGroupsNetwork(wpaGroups); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_manager_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_manager_test.cpp new file mode 100644 index 000000000..63e9eb052 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_manager_test.cpp @@ -0,0 +1,240 @@ +/* + * 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 "wifi_msg.h" +#include "wifi_p2p_service_manager.h" + +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class WifiP2pServiceManagerTest : public testing::Test { +public: + WifiP2pServiceManagerTest() + {} + + virtual void SetUp() + { + WifiP2pDevice device; + pWifiP2pServiceManager.reset(new WifiP2pServiceManager()); + } + virtual void TearDown() + { + pWifiP2pServiceManager.reset(); + } + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + std::unique_ptr pWifiP2pServiceManager; +}; + +HWTEST_F(WifiP2pServiceManagerTest, Init, TestSize.Level1) +{ + pWifiP2pServiceManager->Init(); +} + +HWTEST_F(WifiP2pServiceManagerTest, ClearAll, TestSize.Level1) +{ + pWifiP2pServiceManager->ClearAll(); +} + +HWTEST_F(WifiP2pServiceManagerTest, SetQueryId, TestSize.Level1) +{ + pWifiP2pServiceManager->SetQueryId("queryId"); + EXPECT_EQ(pWifiP2pServiceManager->GetQueryId(), "queryId"); +} + +HWTEST_F(WifiP2pServiceManagerTest, GetTransId, TestSize.Level1) +{ + EXPECT_EQ(pWifiP2pServiceManager->GetTransId(), 1); +} + +HWTEST_F(WifiP2pServiceManagerTest, AddLocalService, TestSize.Level1) +{ + WifiP2pServiceInfo p2pSvrInfo; + EXPECT_TRUE(pWifiP2pServiceManager->AddLocalService(p2pSvrInfo)); + EXPECT_FALSE(pWifiP2pServiceManager->AddLocalService(p2pSvrInfo)); +} + +HWTEST_F(WifiP2pServiceManagerTest, RemoveLocalService, TestSize.Level1) +{ + WifiP2pServiceInfo p2pSvrInfo; + EXPECT_FALSE(pWifiP2pServiceManager->RemoveLocalService(p2pSvrInfo)); + EXPECT_TRUE(pWifiP2pServiceManager->AddLocalService(p2pSvrInfo)); + EXPECT_TRUE(pWifiP2pServiceManager->RemoveLocalService(p2pSvrInfo)); +} + +HWTEST_F(WifiP2pServiceManagerTest, GetLocalServiceList, TestSize.Level1) +{ + WifiP2pServiceInfo p2pSvrInfo; + std::vector localServicesInfo; + localServicesInfo.push_back(p2pSvrInfo); + EXPECT_TRUE(pWifiP2pServiceManager->AddLocalService(p2pSvrInfo)); + EXPECT_EQ(pWifiP2pServiceManager->GetLocalServiceList(), localServicesInfo); +} + +HWTEST_F(WifiP2pServiceManagerTest, AddDeviceResponses, TestSize.Level1) +{ + WifiP2pDevice device; + WifiP2pServiceResponseList p2pSvrReq; + EXPECT_TRUE(pWifiP2pServiceManager->AddDeviceResponses(p2pSvrReq)); + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + p2pSvrReq.SetDevice(device); + WifiP2pServiceResponse resp; + p2pSvrReq.AddServiceResponse(resp); + EXPECT_TRUE(pWifiP2pServiceManager->AddDeviceResponses(p2pSvrReq)); +} + +HWTEST_F(WifiP2pServiceManagerTest, AddDeviceService, TestSize.Level1) +{ + WifiP2pServiceResponse rsp; + WifiP2pDevice dev; + rsp.SetServiceStatus(P2pServiceStatus::PSRS_SERVICE_PROTOCOL_NOT_AVAILABLE); + EXPECT_FALSE(pWifiP2pServiceManager->AddDeviceService(rsp, dev)); + dev.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + rsp.SetServiceStatus(P2pServiceStatus::PSRS_SUCCESS); + EXPECT_TRUE(pWifiP2pServiceManager->AddDeviceService(rsp, dev)); +} + +HWTEST_F(WifiP2pServiceManagerTest, DelServicesFormAddress, TestSize.Level1) +{ + EXPECT_FALSE(pWifiP2pServiceManager->DelServicesFormAddress("AA:BB:CC:DD:EE:FF")); + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + WifiP2pServiceResponse rsp; + rsp.SetServiceStatus(P2pServiceStatus::PSRS_SUCCESS); + EXPECT_TRUE(pWifiP2pServiceManager->AddDeviceService(rsp, device)); + EXPECT_TRUE(pWifiP2pServiceManager->DelServicesFormAddress("AA:BB:CC:DD:EE:FF")); +} + +HWTEST_F(WifiP2pServiceManagerTest, GetDeviceServices, TestSize.Level1) +{ + std::vector services, services1; + WifiP2pServiceInfo info; + services1.push_back(info); + + WifiP2pDevice device; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + WifiP2pServiceResponse rsp; + rsp.SetServiceStatus(P2pServiceStatus::PSRS_SUCCESS); + EXPECT_TRUE(pWifiP2pServiceManager->AddDeviceService(rsp, device)); + pWifiP2pServiceManager->GetDeviceServices(services); +} + +HWTEST_F(WifiP2pServiceManagerTest, GetServiceResponseList, TestSize.Level1) +{ + std::vector respLists; + WifiP2pServiceResponseList respList; + respLists.push_back(respList); + pWifiP2pServiceManager->GetServiceResponseList(respLists); +} + +HWTEST_F(WifiP2pServiceManagerTest, AddServiceResponse_SUCCESS, TestSize.Level1) +{ + WifiP2pDevice device; + WifiP2pServiceResponseList p2pSvrReq, p2pSvrReq1; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + p2pSvrReq.SetDevice(device); + p2pSvrReq1.SetDevice(device); + WifiP2pServiceResponse resp, resq1; + resq1.SetServiceStatus(P2pServiceStatus::PSRS_REQUESTED_INFORMATION_NOT_AVAILABLE); + p2pSvrReq.AddServiceResponse(resp); + p2pSvrReq1.AddServiceResponse(resq1); + EXPECT_TRUE(pWifiP2pServiceManager->AddServiceResponse(p2pSvrReq)); + EXPECT_FALSE(pWifiP2pServiceManager->AddServiceResponse(p2pSvrReq)); + EXPECT_TRUE(pWifiP2pServiceManager->AddServiceResponse(p2pSvrReq1)); +} + + +HWTEST_F(WifiP2pServiceManagerTest, RemoveServiceResponse_SUCCESS, TestSize.Level1) +{ + WifiP2pDevice device; + WifiP2pServiceResponseList p2pSvrReq, p2pSvrReq1; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + p2pSvrReq.SetDevice(device); + p2pSvrReq1.SetDevice(device); + WifiP2pServiceResponse resp, resq1; + resq1.SetServiceStatus(P2pServiceStatus::PSRS_REQUESTED_INFORMATION_NOT_AVAILABLE); + p2pSvrReq.AddServiceResponse(resp); + p2pSvrReq1.AddServiceResponse(resq1); + + EXPECT_FALSE(pWifiP2pServiceManager->RemoveServiceResponse(p2pSvrReq)); + EXPECT_TRUE(pWifiP2pServiceManager->AddServiceResponse(p2pSvrReq)); + EXPECT_TRUE(pWifiP2pServiceManager->RemoveServiceResponse(p2pSvrReq)); + EXPECT_TRUE(pWifiP2pServiceManager->RemoveServiceResponse(p2pSvrReq1)); + EXPECT_TRUE(pWifiP2pServiceManager->AddServiceResponse(p2pSvrReq)); + EXPECT_TRUE(pWifiP2pServiceManager->RemoveServiceResponse("AA:BB:CC:DD:EE:FF")); + EXPECT_FALSE(pWifiP2pServiceManager->RemoveServiceResponse("AA:BB:CC:DD:EE:FF")); +} + +HWTEST_F(WifiP2pServiceManagerTest, ProcessServiceRequestList, TestSize.Level1) +{ + WifiP2pServiceRequestList respList; + WifiP2pServiceRequest req; + respList.AddServiceRequest(req); + WifiP2pServiceInfo p2pSvrInfo; + pWifiP2pServiceManager->ProcessServiceRequestList(respList); + EXPECT_TRUE(pWifiP2pServiceManager->AddLocalService(p2pSvrInfo)); + pWifiP2pServiceManager->ProcessServiceRequestList(respList); +} + +HWTEST_F(WifiP2pServiceManagerTest, ProcessServiceResponseList, TestSize.Level1) +{ + WifiP2pServiceResponseList respList; + WifiP2pServiceResponse resp; + respList.AddServiceResponse(resp); + WifiP2pServiceInfo p2pSvrInfo; + pWifiP2pServiceManager->ProcessServiceResponseList(respList); + EXPECT_TRUE(pWifiP2pServiceManager->AddLocalService(p2pSvrInfo)); + pWifiP2pServiceManager->ProcessServiceResponseList(respList); +} + +HWTEST_F(WifiP2pServiceManagerTest, AddRequestRecord, TestSize.Level1) +{ + pWifiP2pServiceManager->AddRequestRecord("AA:BB:CC:DD:EE:FF", 10); + pWifiP2pServiceManager->AddRequestRecord("AA:BB:CC:DD:EE:FF", 10); + pWifiP2pServiceManager->AddRequestRecord("AA:BB:CC:DD:EE:FF", 11); +} + +HWTEST_F(WifiP2pServiceManagerTest, IsRecordedRequest, TestSize.Level1) +{ + WifiP2pServiceInfo p2pSvrInfo; + EXPECT_FALSE(pWifiP2pServiceManager->IsRecordedRequest("AA:BB:CC:DD:EE:FF", 10)); + p2pSvrInfo.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + EXPECT_TRUE(pWifiP2pServiceManager->AddLocalService(p2pSvrInfo)); + + EXPECT_FALSE(pWifiP2pServiceManager->IsRecordedRequest("AA:BB:CC:DD:EE:FF", 10)); + pWifiP2pServiceManager->AddRequestRecord("AA:BB:CC:DD:EE:FF", 10); + EXPECT_TRUE(pWifiP2pServiceManager->IsRecordedRequest("AA:BB:CC:DD:EE:FF", 10)); +} + +HWTEST_F(WifiP2pServiceManagerTest, RemoveRequestRecord, TestSize.Level1) +{ + pWifiP2pServiceManager->RemoveRequestRecord("AA:BB:CC:DD:EE:FF", 10); + pWifiP2pServiceManager->AddRequestRecord("AA:BB:CC:DD:EE:FF", 10); + + pWifiP2pServiceManager->RemoveRequestRecord("AA:BB:CC:DD:EE:FF", 10); + pWifiP2pServiceManager->RemoveRequestRecord("AA:BB:CC:DD:EE:FF", 11); +} + +HWTEST_F(WifiP2pServiceManagerTest, ClearAllRequestRecord, TestSize.Level1) +{ + pWifiP2pServiceManager->ClearAllRequestRecord(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_request_list_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_request_list_test.cpp new file mode 100644 index 000000000..2fc9e8f39 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_request_list_test.cpp @@ -0,0 +1,110 @@ +/* + * 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 "wifi_p2p_service_request_list.h" + +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class WifiP2pServiceRequestListTest : public testing::Test { +public: + static void SetUpTestCase(){} + static void TearDownTestCase(){} + virtual void SetUp() + { + pWifiP2pServiceRequestList.reset(new WifiP2pServiceRequestList()); + } + virtual void TearDown() + { + pWifiP2pServiceRequestList.reset(); + } + +public: + std::unique_ptr pWifiP2pServiceRequestList; +}; + +HWTEST_F(WifiP2pServiceRequestListTest, AddServiceRequest, TestSize.Level1) +{ + WifiP2pServiceRequest req; + EXPECT_TRUE(pWifiP2pServiceRequestList->AddServiceRequest(req)); + EXPECT_FALSE(pWifiP2pServiceRequestList->AddServiceRequest(req)); +} + +HWTEST_F(WifiP2pServiceRequestListTest, RemoveServiceRequest, TestSize.Level1) +{ + WifiP2pServiceRequest req; + EXPECT_FALSE(pWifiP2pServiceRequestList->RemoveServiceRequest(req)); + EXPECT_TRUE(pWifiP2pServiceRequestList->AddServiceRequest(req)); + EXPECT_TRUE(pWifiP2pServiceRequestList->RemoveServiceRequest(req)); +} + +HWTEST_F(WifiP2pServiceRequestListTest, ClearServiceRequest, TestSize.Level1) +{ + EXPECT_EQ(true, pWifiP2pServiceRequestList->ClearServiceRequest()); +} + +HWTEST_F(WifiP2pServiceRequestListTest, GetServiceRequestList, TestSize.Level1) +{ + std::vector resps; + WifiP2pServiceRequest req; + resps.push_back(req); + EXPECT_TRUE(pWifiP2pServiceRequestList->AddServiceRequest(req)); + EXPECT_EQ(resps, pWifiP2pServiceRequestList->GetServiceRequestList()); +} + +HWTEST_F(WifiP2pServiceRequestListTest, SetUpdateIndic, TestSize.Level1) +{ + unsigned short updateIndic = 1; + pWifiP2pServiceRequestList->SetUpdateIndic(updateIndic); + EXPECT_EQ(pWifiP2pServiceRequestList->GetUpdateIndic(), updateIndic); +} + +HWTEST_F(WifiP2pServiceRequestListTest, SetFrequency, TestSize.Level1) +{ + int frequency = 2020; + pWifiP2pServiceRequestList->SetFrequency(frequency); + EXPECT_EQ(pWifiP2pServiceRequestList->GetFrequency(), frequency); +} + +HWTEST_F(WifiP2pServiceRequestListTest, SetDialogToken, TestSize.Level1) +{ + int dialogToken = 2020; + pWifiP2pServiceRequestList->SetDialogToken(dialogToken); + EXPECT_EQ(pWifiP2pServiceRequestList->GetDialogToken(), dialogToken); +} + +HWTEST_F(WifiP2pServiceRequestListTest, SetDevice, TestSize.Level1) +{ + WifiP2pDevice device; + pWifiP2pServiceRequestList->SetDevice(device); + EXPECT_EQ(pWifiP2pServiceRequestList->GetDevice(), device); +} + +HWTEST_F(WifiP2pServiceRequestListTest, GetTlvs, TestSize.Level1) // +{ + WifiP2pServiceRequest resp; + EXPECT_TRUE(pWifiP2pServiceRequestList->AddServiceRequest(resp)); + pWifiP2pServiceRequestList->GetTlvs(); +} + +HWTEST_F(WifiP2pServiceRequestListTest, ParseTlvs2ReqList, TestSize.Level1) +{ + const std::vector tlvList; + pWifiP2pServiceRequestList->ParseTlvs2ReqList(tlvList); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_response_list_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_response_list_test.cpp new file mode 100644 index 000000000..2b7767c09 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_response_list_test.cpp @@ -0,0 +1,145 @@ +/* + * 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 "wifi_p2p_service_response_list.h" + +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class WifiP2pServiceResponseListTest : public testing::Test { +public: + static void SetUpTestCase(){} + static void TearDownTestCase(){} + virtual void SetUp() + { + pWifiP2pServiceResponseList.reset(new WifiP2pServiceResponseList()); + } + virtual void TearDown() + { + pWifiP2pServiceResponseList.reset(); + } + +public: + std::unique_ptr pWifiP2pServiceResponseList; +}; + +HWTEST_F(WifiP2pServiceResponseListTest, constructions, TestSize.Level1) +{ + WifiP2pDevice device; + std::vector srvRespList; + WifiP2pServiceResponseList wifiP2pServiceResponseList = WifiP2pServiceResponseList(device, srvRespList); +} + +HWTEST_F(WifiP2pServiceResponseListTest, AddServiceResponse, TestSize.Level1) +{ + WifiP2pServiceResponse resp; + EXPECT_TRUE(pWifiP2pServiceResponseList->AddServiceResponse(resp)); + EXPECT_TRUE(pWifiP2pServiceResponseList->AddServiceResponse(resp)); +} + +HWTEST_F(WifiP2pServiceResponseListTest, RemoveServiceResponse, TestSize.Level1) +{ + WifiP2pServiceResponse resp; + EXPECT_FALSE(pWifiP2pServiceResponseList->RemoveServiceResponse(resp)); + EXPECT_TRUE(pWifiP2pServiceResponseList->AddServiceResponse(resp)); + EXPECT_TRUE(pWifiP2pServiceResponseList->RemoveServiceResponse(resp)); +} + +HWTEST_F(WifiP2pServiceResponseListTest, GetServiceResponseList, TestSize.Level1) +{ + std::vector resps; + WifiP2pServiceResponse resp; + resps.push_back(resp); + EXPECT_TRUE(pWifiP2pServiceResponseList->AddServiceResponse(resp)); + EXPECT_EQ(resps, pWifiP2pServiceResponseList->GetServiceResponseList()); +} + +HWTEST_F(WifiP2pServiceResponseListTest, FilterSerivceResponse, TestSize.Level1) +{ + pWifiP2pServiceResponseList->FilterSerivceResponse(P2pServiceStatus::PSRS_BAD_REQUEST); + WifiP2pServiceResponse resp; + resp.SetServiceStatus(P2pServiceStatus::PSRS_SUCCESS); + EXPECT_TRUE(pWifiP2pServiceResponseList->AddServiceResponse(resp)); + pWifiP2pServiceResponseList->FilterSerivceResponse(P2pServiceStatus::PSRS_SUCCESS); +} + +HWTEST_F(WifiP2pServiceResponseListTest, ReverseFilterSerivceResponse, TestSize.Level1) +{ + pWifiP2pServiceResponseList->ReverseFilterSerivceResponse(P2pServiceStatus::PSRS_BAD_REQUEST); + WifiP2pServiceResponse resp; + resp.SetServiceStatus(P2pServiceStatus::PSRS_SUCCESS); + EXPECT_TRUE(pWifiP2pServiceResponseList->AddServiceResponse(resp)); + pWifiP2pServiceResponseList->ReverseFilterSerivceResponse(P2pServiceStatus::PSRS_SUCCESS); +} + +HWTEST_F(WifiP2pServiceResponseListTest, MergerAndDeduplicate, TestSize.Level1) +{ + WifiP2pDevice device; + WifiP2pServiceResponseList responseList; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + responseList.SetDevice(device); + WifiP2pServiceResponse resp; + pWifiP2pServiceResponseList->MergerAndDeduplicate(responseList); + pWifiP2pServiceResponseList->SetDevice(device); + pWifiP2pServiceResponseList->MergerAndDeduplicate(responseList); + EXPECT_TRUE(pWifiP2pServiceResponseList->AddServiceResponse(resp)); + responseList.AddServiceResponse(resp); + pWifiP2pServiceResponseList->MergerAndDeduplicate(responseList); +} + +HWTEST_F(WifiP2pServiceResponseListTest, GetTlvs, TestSize.Level1) // +{ + WifiP2pServiceResponse resp; + EXPECT_TRUE(pWifiP2pServiceResponseList->AddServiceResponse(resp)); + pWifiP2pServiceResponseList->GetTlvs(); +} + +HWTEST_F(WifiP2pServiceResponseListTest, SetUpdateIndic, TestSize.Level1) +{ + unsigned short updateIndic = 1; + pWifiP2pServiceResponseList->SetUpdateIndic(updateIndic); + EXPECT_EQ(pWifiP2pServiceResponseList->GetUpdateIndic(), updateIndic); +} + +HWTEST_F(WifiP2pServiceResponseListTest, SetFrequency, TestSize.Level1) +{ + int frequency = 2020; + pWifiP2pServiceResponseList->SetFrequency(frequency); + EXPECT_EQ(pWifiP2pServiceResponseList->GetFrequency(), frequency); +} + +HWTEST_F(WifiP2pServiceResponseListTest, SetDialogToken, TestSize.Level1) +{ + int dialogToken = 2020; + pWifiP2pServiceResponseList->SetDialogToken(dialogToken); + EXPECT_EQ(pWifiP2pServiceResponseList->GetDialogToken(), dialogToken); +} + +HWTEST_F(WifiP2pServiceResponseListTest, SetDevice, TestSize.Level1) +{ + WifiP2pDevice device; + pWifiP2pServiceResponseList->SetDevice(device); + EXPECT_EQ(pWifiP2pServiceResponseList->GetDevice(), device); +} + +HWTEST_F(WifiP2pServiceResponseListTest, ParseTlvs2RespList, TestSize.Level1) +{ + const std::vector tlvList; + pWifiP2pServiceResponseList->ParseTlvs2RespList(tlvList); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_test.cpp new file mode 100644 index 000000000..340a61661 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_test.cpp @@ -0,0 +1,179 @@ +/* + * 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 "wifi_p2p_service.h" +#include "wifi_p2p_msg.h" +#include "mock_p2p_pendant.h" +#include "mock_wifi_p2p_hal_interface.h" + +using ::testing::Return; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class WifiP2pServiceTest : public testing::Test { +public: + WifiP2pServiceTest() : groupManager(), deviceManager(), svrManager() + {} + static void SetUpTestCase(){} + static void TearDownTestCase(){} + virtual void SetUp() + { + pMockP2pPendant.reset(new MockP2pPendant()); + pWifiP2pService.reset( + new WifiP2pService(pMockP2pPendant->GetP2pStateMachine(), deviceManager, groupManager, svrManager)); + } + virtual void TearDown() + { + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(testing::_)); + pWifiP2pService.reset(); + pMockP2pPendant.reset(); + } + +public: + std::unique_ptr pWifiP2pService; + std::unique_ptr pMockP2pPendant; + WifiP2pGroupManager groupManager; + WifiP2pDeviceManager deviceManager; + WifiP2pServiceManager svrManager; +}; + +HWTEST_F(WifiP2pServiceTest, DisableP2p, TestSize.Level1) +{ + EXPECT_EQ(pWifiP2pService->DisableP2p(), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, DiscoverDevices, TestSize.Level1) +{ + EXPECT_EQ(pWifiP2pService->DiscoverDevices(), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, StopDiscoverDevices, TestSize.Level1) +{ + EXPECT_EQ(pWifiP2pService->StopDiscoverDevices(), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, DiscoverServices, TestSize.Level1) +{ + EXPECT_EQ(pWifiP2pService->DiscoverServices(), ErrCode::WIFI_OPT_SUCCESS); +} +HWTEST_F(WifiP2pServiceTest, StopDiscoverServices, TestSize.Level1) +{ + EXPECT_EQ(pWifiP2pService->StopDiscoverServices(), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, PutLocalP2pService, TestSize.Level1) +{ + WifiP2pServiceInfo srvInfo; + EXPECT_EQ(pWifiP2pService->PutLocalP2pService(srvInfo), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, DeleteLocalP2pService, TestSize.Level1) +{ + WifiP2pServiceInfo srvInfo; + EXPECT_EQ(pWifiP2pService->DeleteLocalP2pService(srvInfo), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, RequestService, TestSize.Level1) +{ + WifiP2pDevice device; + WifiP2pServiceRequest request; + EXPECT_EQ(pWifiP2pService->RequestService(device, request), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, StartP2pListen, TestSize.Level1) +{ + int period = 0; + int interval = 0; + EXPECT_EQ(pWifiP2pService->StartP2pListen(period, interval), ErrCode::WIFI_OPT_SUCCESS); +} +HWTEST_F(WifiP2pServiceTest, StopP2pListen, TestSize.Level1) +{ + EXPECT_EQ(pWifiP2pService->StopP2pListen(), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, FormGroup, TestSize.Level1) +{ + WifiP2pConfig config; + EXPECT_EQ(pWifiP2pService->FormGroup(config), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, RemoveGroup, TestSize.Level1) +{ + EXPECT_EQ(pWifiP2pService->RemoveGroup(), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, DeleteGroup, TestSize.Level1) +{ + WifiP2pGroupInfo group; + EXPECT_EQ(pWifiP2pService->DeleteGroup(group), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, P2pConnect, TestSize.Level1) +{ + WifiP2pConfig config; + EXPECT_EQ(pWifiP2pService->P2pConnect(config), ErrCode::WIFI_OPT_SUCCESS); + EXPECT_EQ(pWifiP2pService->P2pDisConnect(), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, QueryP2pInfo, TestSize.Level1) +{ + WifiP2pInfo connInfo; + EXPECT_EQ(pWifiP2pService->QueryP2pInfo(connInfo), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, GetCurrentGroup, TestSize.Level1) +{ + WifiP2pGroupInfo group; + EXPECT_EQ(pWifiP2pService->GetCurrentGroup(group), ErrCode::WIFI_OPT_SUCCESS); +} +HWTEST_F(WifiP2pServiceTest, GetP2pEnableStatus, TestSize.Level1) +{ + int status; + EXPECT_EQ(pWifiP2pService->GetP2pEnableStatus(status), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, GetP2pDiscoverStatus, TestSize.Level1) +{ + int status; + EXPECT_EQ(pWifiP2pService->GetP2pDiscoverStatus(status), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, GetP2pConnectedStatus, TestSize.Level1) +{ + int status; + EXPECT_EQ(pWifiP2pService->GetP2pConnectedStatus(status), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, QueryP2pDevices, TestSize.Level1) +{ + std::vector devices; + EXPECT_EQ(pWifiP2pService->QueryP2pDevices(devices), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, QueryP2pGroups, TestSize.Level1) +{ + std::vector groups; + EXPECT_EQ(pWifiP2pService->QueryP2pGroups(groups), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, QueryP2pServices, TestSize.Level1) +{ + std::vector services; + EXPECT_EQ(pWifiP2pService->QueryP2pServices(services), ErrCode::WIFI_OPT_SUCCESS); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_test_entry.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_test_entry.cpp new file mode 100644 index 000000000..4d6c9d397 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_test_entry.cpp @@ -0,0 +1,27 @@ +/* + * 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 "global_test.h" + +using ::testing::ext::TestSize; + +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + testing::Environment *env = new GlobalTest(); + testing::AddGlobalTestEnvironment(env); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_info_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_info_test.cpp new file mode 100644 index 000000000..c94b56eae --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_info_test.cpp @@ -0,0 +1,64 @@ +/* + * 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 "wifi_p2p_upnp_service_info.h" + +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class WifiP2pUpnpServiceInfoTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: + void WarpCreate() + { + std::string uuid; + std::string device; + std::vector services; + std::string svrName; + WifiP2pUpnpServiceInfo::Create(uuid, device, services, svrName); + } + void WarpCreateSupQuery() + { + std::string uuid; + std::string data; + std::string device; + std::string svrName; + std::vector services; + WifiP2pUpnpServiceInfo::Create(uuid, device, services, svrName).BuildWpaQuery(uuid, data, svrName); + } +}; + +HWTEST_F(WifiP2pUpnpServiceInfoTest, Create, TestSize.Level1) +{ + WarpCreate(); +} + +HWTEST_F(WifiP2pUpnpServiceInfoTest, BuildWpaQuery, TestSize.Level1) +{ + WarpCreateSupQuery(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_request_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_request_test.cpp new file mode 100644 index 000000000..fe3c91460 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_request_test.cpp @@ -0,0 +1,47 @@ +/* + * 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 "wifi_p2p_upnp_service_request.h" + +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class WifiP2pUpnpServiceRequestTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} + +public: + void WarpCreate() + { + WifiP2pUpnpServiceRequest::Create(); + WifiP2pUpnpServiceRequest::Create("searchTarget"); + } +}; + +HWTEST_F(WifiP2pUpnpServiceRequestTest, Create, TestSize.Level1) +{ + WarpCreate(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_response_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_response_test.cpp new file mode 100644 index 000000000..87ed7a61d --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_response_test.cpp @@ -0,0 +1,65 @@ +/* + * 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 "wifi_p2p_upnp_service_response.h" + +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class WifiP2pUpnpServiceResponseTest : public testing::Test { +public: + virtual void SetUp() + {} + virtual void TearDown() + {} + + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + +public: + P2pServiceStatus status = P2pServiceStatus::PSRS_SUCCESS; + int tranId; + std::vector data; +}; + +HWTEST_F(WifiP2pUpnpServiceResponseTest, GetUniqueServNames, TestSize.Level1) +{ + std::vector strV; + EXPECT_EQ(strV, WifiP2pUpnpServiceResponse::Create(status, tranId, data).GetUniqueServNames()); +} + +HWTEST_F(WifiP2pUpnpServiceResponseTest, GetVersion, TestSize.Level1) +{ + status = P2pServiceStatus::PSRS_SERVICE_PROTOCOL_NOT_AVAILABLE; + EXPECT_EQ(-1, WifiP2pUpnpServiceResponse::Create(status, tranId, data).GetVersion()); +} + +HWTEST_F(WifiP2pUpnpServiceResponseTest, ParseData, TestSize.Level1) +{ + std::vector data; + data.push_back(1); + data.push_back(2); + data.push_back(3); + EXPECT_EQ(true, WifiP2pUpnpServiceResponse::Create(status, tranId, data).ParseData()); + WifiP2pUpnpServiceResponse::Create(status, tranId, data).SetData(data); + EXPECT_EQ(true, WifiP2pUpnpServiceResponse::Create(status, tranId, data).ParseData()); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn new file mode 100644 index 000000000..ab4f861f1 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn @@ -0,0 +1,101 @@ +# 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. + +import("//build/test.gni") +SUBSYSTEM_DIR = "//foundation/communication" +module_output_path = "wifi_standard/scan_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + ] +} + +ohos_unittest("wifi_scan_unittest") { + module_out_path = module_output_path + sources = [ + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.cpp", + "Mock/mock_scan_service.cpp", + "Mock/mock_scan_state_machine.cpp", + "Mock/mock_wifi_manager.cpp", + "Mock/mock_wifi_settings.cpp", + "Mock/mock_wifi_sta_hal_interface.cpp", + "Mock/mock_wifi_supplicant_hal_interface.cpp", + "global_test.cpp", + "scan_interface_test.cpp", + "scan_monitor_test.cpp", + "scan_service_test.cpp", + "scan_state_machine_test.cpp", + "wifi_scan_test.cpp", + ] + + include_dirs = [ + "//utils/native/base/include", + "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", + "//foundation/communication/wifi/services/wifi_standard/sdk/include", + "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//foundation/communication/wifi/services/wifi_standard/depends/include/hardware/libhardware/include", + "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/include", + "//foundation/communication/wifi/services/wifi_standard/depends/include/frameworks/native/include", + "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/libutils/include", + "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/base/include", + "//foundation/communication/wifi/services/wifi_standard/depends/include/system/libbase/include", + "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/libnetutils/include/netutils", + "//third_party/googletest/googlemock/include", + "//third_party/googletest/googletest/include", + ] + deps = [ + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + part_name = "wifi_standard" + subsystem_name = "communication" +} + +group("unittest") { + testonly = true + deps = [ ":wifi_scan_unittest" ] +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.cpp new file mode 100644 index 000000000..7abdfc5f0 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.cpp @@ -0,0 +1,106 @@ +/* + * 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 "mock_scan_service.h" +#include "wifi_logger.h" + +DEFINE_WIFILOG_SCAN_LABEL("MockScanService"); + +namespace OHOS { +namespace Wifi { +bool MockScanService::InitScanService(const IScanSerivceCallbacks &iScanSerivceCallbacks) +{ + (void)iScanSerivceCallbacks; + WIFI_LOGI("Enter MockScanService::InitScanService"); + return true; +} + +void MockScanService::UnInitScanService() +{ + WIFI_LOGI("Enter MockScanService::UnInitScanService"); +} + +void MockScanService::RegisterScanCallbacks(const IScanSerivceCallbacks &iScanSerivceCallbacks) +{ + (void)iScanSerivceCallbacks; + WIFI_LOGI("Enter MockScanService::RegisterScanCallbacks"); +} + +ErrCode MockScanService::Scan(bool externFlag) +{ + (void)externFlag; + WIFI_LOGI("Enter MockScanService::Scan"); + return WIFI_OPT_SUCCESS; +} + +ErrCode MockScanService::ScanWithParam(const WifiScanParams ¶ms) +{ + (void)params; + WIFI_LOGI("Enter MockScanService::ScanWithParam"); + return WIFI_OPT_SUCCESS; +} + +void MockScanService::SystemScanProcess(bool scanAtOnce) +{ + (void)scanAtOnce; + WIFI_LOGI("Enter MockScanService::SystemScanProcess"); +} + +void MockScanService::HandleScreenStatusChanged(bool screenOn) +{ + (void)screenOn; + WIFI_LOGI("Enter MockScanService::HandleScreenStatusChanged"); +} + +void MockScanService::HandleStaStatusChanged(int status) +{ + (void)status; + WIFI_LOGI("Enter MockScanService::HandleStaStatusChanged"); +} + +void MockScanService::HandleCustomStatusChanged(int customScene, int customSceneStatus) +{ + (void)customScene; + (void)customSceneStatus; + WIFI_LOGI("Enter MockScanService::HandleCustomStatusChanged"); +} + +void MockScanService::SetOperateAppMode(int appMode) +{ + (void)appMode; + WIFI_LOGI("Enter MockScanService::SetOperateAppMode"); +} + +void MockScanService::GetScanControlInfo() +{ + WIFI_LOGI("Enter MockScanService::GetScanControlInfo"); +} + +void MockScanService::ClearScanControlValue() +{ + WIFI_LOGI("Enter MockScanService::ClearScanControlValue"); +} + +void MockScanService::SetStaCurrentTime() +{ + WIFI_LOGI("Enter MockScanService::SetStaCurrentTime"); +} + +void MockScanService::HandleScanStatusReport(ScanStatusReport &scanStatusReport) +{ + (void)scanStatusReport; + WIFI_LOGI("Enter MockScanService::HandleScanStatusReport"); +} +} // namespace Wifi +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.h new file mode 100644 index 000000000..03a6a481d --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.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_MOCK_SCANSERVICE_H +#define OHOS_MOCK_SCANSERVICE_H + +#include +#include "scan_service.h" + +namespace OHOS { +namespace Wifi { +class MockScanService : public ScanService { +public: + MockScanService(){} + ~MockScanService(){} + bool InitScanService(const IScanSerivceCallbacks &iScanSerivceCallbacks); + void UnInitScanService(); + void RegisterScanCallbacks(const IScanSerivceCallbacks &iScanSerivceCallbacks); + ErrCode Scan(bool externFlag); + ErrCode ScanWithParam(const WifiScanParams ¶ms); + void SystemScanProcess(bool scanAtOnce); + void HandleScreenStatusChanged(bool screenOn); + void HandleStaStatusChanged(int status); + void HandleCustomStatusChanged(int customScene, int customSceneStatus); + void SetOperateAppMode(int appMode); + void GetScanControlInfo(); + void ClearScanControlValue(); + void SetStaCurrentTime(); + void HandleScanStatusReport(ScanStatusReport &scanStatusReport); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.cpp new file mode 100644 index 000000000..e982d00a4 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.cpp @@ -0,0 +1,58 @@ +/* + * 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 "mock_scan_state_machine.h" +#include "wifi_logger.h" + +DEFINE_WIFILOG_SCAN_LABEL("MockScanStateMachine"); + +namespace OHOS { +namespace Wifi { +void MockScanStateMachine::SendMessage(int what) +{ + WIFI_LOGD("MockScanStateMachine::SendMessage, what is %{public}d.", what); +} + +void MockScanStateMachine::SendMessage(int what, int arg1) +{ + WIFI_LOGD("MockScanStateMachine::SendMessage, what is %{public}d, arg1 is %{public}d.", what, arg1); +} + +void MockScanStateMachine::SendMessage(int what, int arg1, int arg2) +{ + WIFI_LOGD("MockScanStateMachine::SendMessage, what is %{public}d, arg1 is %{public}d, arg2 is %{public}d.", what, + arg1, arg2); +} + +void MockScanStateMachine::SendMessage(InternalMessage *msg) +{ + if (msg == nullptr) { + return; + } + WIFI_LOGD("MockScanStateMachine::SendMessage, msg is %{public}d.", msg->GetMessageName()); +} + +void MockScanStateMachine::StartTimer(int timerName, int64_t interval) +{ + (void)timerName; + (void)interval; + WIFI_LOGD("Enter MockScanStateMachine::StartTimer"); +} +void MockScanStateMachine::StopTimer(int timerName) +{ + (void)timerName; + WIFI_LOGD("Enter MockScanStateMachine::StopTimer"); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.h new file mode 100644 index 000000000..564b0491b --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.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_MOCK_SCANSTATEMACHINE_H +#define OHOS_MOCK_SCANSTATEMACHINE_H + +#include +#include "scan_state_machine.h" + +namespace OHOS { +namespace Wifi { +class MockScanStateMachine : public ScanStateMachine { +public: + MockScanStateMachine(){} + ~MockScanStateMachine(){} + void SendMessage(int what); + void SendMessage(int what, int arg1); + void SendMessage(int what, int arg1, int arg2); + void SendMessage(InternalMessage *msg); + void StartTimer(int timerName, int64_t interval); + void StopTimer(int timerName); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.cpp new file mode 100644 index 000000000..4011e31e2 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.cpp @@ -0,0 +1,45 @@ +/* + * 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 "mock_wifi_manager.h" + +namespace OHOS { +namespace Wifi { +WifiManager &WifiManager::GetInstance() +{ + static WifiManager gWifiManager; + return gWifiManager; +} + +WifiManager::WifiManager() +{ + InitScanCallback(); +} + +IScanSerivceCallbacks WifiManager::GetScanCallback(void) +{ + return mScanCallback; +} + +void WifiManager::InitScanCallback(void) +{ + using namespace std::placeholders; + mScanCallback.OnScanStartEvent = std::bind(&WifiManager::DealScanOpenRes, this); + mScanCallback.OnScanStopEvent = std::bind(&WifiManager::DealScanCloseRes, this); + mScanCallback.OnScanFinishEvent = std::bind(&WifiManager::DealScanFinished, this, _1); + mScanCallback.OnScanInfoEvent = std::bind(&WifiManager::DealScanInfoNotify, this, _1); + return; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.h new file mode 100644 index 000000000..bb8d74bbc --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.h @@ -0,0 +1,51 @@ +/* + * 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_WIFI_MANAGER_H +#define OHOS_MOCK_WIFI_MANAGER_H + +#include +#include "iscan_service_callbacks.h" + +namespace OHOS { +namespace Wifi { +class MockWifiManager { +public: + virtual ~MockWifiManager() = default; + virtual void DealScanOpenRes() = 0; + virtual void DealScanCloseRes() = 0; + virtual void DealScanFinished(int state) = 0; + virtual void DealScanInfoNotify(std::vector &results) = 0; +}; + +class WifiManager : public MockWifiManager { +public: + WifiManager(); + ~WifiManager() = default; + static WifiManager &GetInstance(); + IScanSerivceCallbacks GetScanCallback(); + + MOCK_METHOD0(DealScanOpenRes, void()); + MOCK_METHOD0(DealScanCloseRes, void()); + MOCK_METHOD1(DealScanFinished, void(int state)); + MOCK_METHOD1(DealScanInfoNotify, void(std::vector &results)); + +private: + IScanSerivceCallbacks mScanCallback; + void InitScanCallback(void); +}; +} // namespace Wifi +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.cpp new file mode 100644 index 000000000..cdcfbf514 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.cpp @@ -0,0 +1,25 @@ +/* + * 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 "mock_wifi_settings.h" + +namespace OHOS { +namespace Wifi { +WifiSettings &WifiSettings::GetInstance(void) +{ + static WifiSettings inst; + return inst; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.h new file mode 100644 index 000000000..77eaedf81 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.h @@ -0,0 +1,58 @@ +/* + * 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_WIFI_SETTINGS_H +#define OHOS_MOCK_WIFI_SETTINGS_H + +#include "wifi_msg.h" +#include + +namespace OHOS { +namespace Wifi { +class MockWifiSettings { +public: + virtual ~MockWifiSettings() = default; + virtual int SaveScanInfoList(const std::vector &results) = 0; + virtual int GetScanInfoList(std::vector &results) = 0; + virtual int GetScanControlInfo(ScanControlInfo &info) = 0; + virtual int SetScanControlInfo(const ScanControlInfo &info) = 0; + virtual void SetScreenState(const int &state) = 0; + virtual int GetScreenState() = 0; + virtual bool GetSupportHwPnoFlag() = 0; + virtual int GetMinRssi2Dot4Ghz() = 0; + virtual int GetMinRssi5Ghz() = 0; + virtual bool GetWhetherToAllowNetworkSwitchover() = 0; + virtual int GetDeviceConfig(std::vector &results) = 0; +}; + +class WifiSettings : public MockWifiSettings { +public: + static WifiSettings &GetInstance(void); + + MOCK_METHOD1(SaveScanInfoList, int(const std::vector &results)); + MOCK_METHOD1(GetScanInfoList, int(std::vector &results)); + MOCK_METHOD1(GetScanControlInfo, int(ScanControlInfo &info)); + MOCK_METHOD1(SetScanControlInfo, int(const ScanControlInfo &info)); + MOCK_METHOD1(SetScreenState, void(const int &state)); + MOCK_METHOD0(GetScreenState, int()); + MOCK_METHOD0(GetSupportHwPnoFlag, bool()); + MOCK_METHOD0(GetMinRssi2Dot4Ghz, int()); + MOCK_METHOD0(GetMinRssi5Ghz, int()); + MOCK_METHOD0(GetWhetherToAllowNetworkSwitchover, bool()); + MOCK_METHOD1(GetDeviceConfig, int(std::vector &results)); +}; +} // namespace Wifi +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.cpp new file mode 100644 index 000000000..3273ae49f --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.cpp @@ -0,0 +1,25 @@ +/* + * 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 "mock_wifi_sta_hal_interface.h" + +namespace OHOS { +namespace Wifi { +WifiStaHalInterface &WifiStaHalInterface::GetInstance(void) +{ + static WifiStaHalInterface inst; + return inst; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.h new file mode 100644 index 000000000..78c7a9a13 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.h @@ -0,0 +1,51 @@ +/* + * 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_WIFI_SCAN_HAL_INTERFACE_H +#define OHOS_MOCK_WIFI_SCAN_HAL_INTERFACE_H + +#include +#include +#include +#include "wifi_error_no.h" +#include "wifi_internal_msg.h" +#include "wifi_idl_struct.h" +#include "wifi_scan_param.h" + +namespace OHOS { +namespace Wifi { +class MockWifiStaHalInterface { +public: + virtual ~MockWifiStaHalInterface() = default; + virtual WifiErrorNo Scan(const WifiScanParam &scanParam) = 0; + virtual WifiErrorNo QueryScanInfos(std::vector &scanInfos) = 0; + virtual WifiErrorNo StartPnoScan(const WifiPnoScanParam &scanParam) = 0; + virtual WifiErrorNo StopPnoScan(void) = 0; + virtual WifiErrorNo GetSupportFrequencies(int band, std::vector &frequencies) = 0; +}; + +class WifiStaHalInterface : public MockWifiStaHalInterface { +public: + static WifiStaHalInterface &GetInstance(void); + +public: + MOCK_METHOD1(Scan, WifiErrorNo(const WifiScanParam &scanParam)); + MOCK_METHOD1(QueryScanInfos, WifiErrorNo(std::vector &scanInfos)); + MOCK_METHOD1(StartPnoScan, WifiErrorNo(const WifiPnoScanParam &scanParam)); + MOCK_METHOD0(StopPnoScan, WifiErrorNo(void)); + MOCK_METHOD2(GetSupportFrequencies, WifiErrorNo(int band, std::vector &frequencies)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.cpp new file mode 100644 index 000000000..94391d1d9 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.cpp @@ -0,0 +1,25 @@ +/* + * 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 "mock_wifi_supplicant_hal_interface.h" + +namespace OHOS { +namespace Wifi { +WifiSupplicantHalInterface &WifiSupplicantHalInterface::GetInstance(void) +{ + static WifiSupplicantHalInterface inst; + return inst; +} +} // namespace Wifi +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.h new file mode 100644 index 000000000..abe646cbe --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.h @@ -0,0 +1,43 @@ +/* + * 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_WIFISUPPLICANTHALINTERFACE_H +#define OHOS_MOCK_WIFISUPPLICANTHALINTERFACE_H + +#include +#include +#include "supplicant_event_callback.h" +#include "wifi_error_no.h" +#include "i_wifi_struct.h" + +namespace OHOS { +namespace Wifi { +class MockWifiSupplicantHalInterface { +public: + virtual ~MockWifiSupplicantHalInterface() = default; + virtual WifiErrorNo UnRegisterSupplicantEventCallback() = 0; + virtual WifiErrorNo RegisterSupplicantEventCallback(SupplicantEventCallback &callback) = 0; +}; + +class WifiSupplicantHalInterface : public MockWifiSupplicantHalInterface { +public: + static WifiSupplicantHalInterface &GetInstance(void); + +public: + MOCK_METHOD0(UnRegisterSupplicantEventCallback, WifiErrorNo()); + MOCK_METHOD1(RegisterSupplicantEventCallback, WifiErrorNo(SupplicantEventCallback &callback)); +}; +} // namespace Wifi +} // namespace OHOS +#endif diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.cpp new file mode 100644 index 000000000..66c15aa1f --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.cpp @@ -0,0 +1,23 @@ +/* + * 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 "global_test.h" +void GlobalTest::SetUp() +{ + printf("GlobalTest SetUp\n"); +} +void GlobalTest::TearDown() +{ + printf("GlobalTest TearDown\n"); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.h new file mode 100644 index 000000000..82139ba5e --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.h @@ -0,0 +1,23 @@ +/* + * 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 GLOBAL_TEST_H +#define GLOBAL_TEST_H +#include +class GlobalTest : public testing::Environment { +public: + virtual void SetUp(); + virtual void TearDown(); +}; +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface_test.cpp new file mode 100644 index 000000000..513d1b387 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface_test.cpp @@ -0,0 +1,147 @@ +/* + * 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 "scan_interface.h" +#include +#include "mock_wifi_manager.h" +#include "mock_scan_service.h" +#include "mock_wifi_settings.h" +#include "mock_wifi_supplicant_hal_interface.h" +#include "mock_wifi_sta_hal_interface.h" + +using ::testing::_; +using ::testing::AtLeast; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::StrEq; +using ::testing::TypedEq; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class ScanInterfaceTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + void SetUp() override + { + pScanInterface = std::make_unique(); + pScanInterface->pScanService = new MockScanService(); + pScanInterface->mScanSerivceCallbacks = WifiManager::GetInstance().GetScanCallback(); + } + void TearDown() override + { + pScanInterface.reset(); + } + +public: + std::unique_ptr pScanInterface; +}; + +extern "C" IScanService *Create(void); +extern "C" void Destroy(IScanService *pservice); +HWTEST_F(ScanInterfaceTest, GCreateDestroy, TestSize.Level1) +{ + auto p = Create(); + Destroy(p); +} + +HWTEST_F(ScanInterfaceTest, InitTest, TestSize.Level1) +{ + EXPECT_CALL(WifiSettings::GetInstance(), GetSupportHwPnoFlag()).Times(AtLeast(1)); + EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), RegisterSupplicantEventCallback(_)).Times(AtLeast(1)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetSupportFrequencies(_, _)).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScanControlInfo(_)).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScreenState()).Times(AtLeast(1)); + EXPECT_CALL(WifiManager::GetInstance(), DealScanOpenRes()).Times(AtLeast(0)); + EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), UnRegisterSupplicantEventCallback()).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + pScanInterface->Init(); +} + +HWTEST_F(ScanInterfaceTest, UnInitTest, TestSize.Level1) +{ + pScanInterface->UnInit(); +} + +HWTEST_F(ScanInterfaceTest, ScanSuccess, TestSize.Level1) +{ + EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->Scan(true)); +} + +HWTEST_F(ScanInterfaceTest, ScanWithParamSuccess, TestSize.Level1) +{ + WifiScanParams wifiScanParams; + wifiScanParams.ssid = "hmwifi"; + wifiScanParams.bssid = "a3:b1:d7:f2:d2:c2"; + EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->ScanWithParam(wifiScanParams)); +} + +HWTEST_F(ScanInterfaceTest, OnScreenStateChangedSuccess1, TestSize.Level1) +{ + int screenState = STATE_OPEN; + EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->OnScreenStateChanged(screenState)); +} + +HWTEST_F(ScanInterfaceTest, OnScreenStateChangedSuccess2, TestSize.Level1) +{ + int screenState = STATE_CLOSE; + EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->OnScreenStateChanged(screenState)); +} + +HWTEST_F(ScanInterfaceTest, OnScreenStateChangedFail, TestSize.Level1) +{ + int screenState = 0; + EXPECT_EQ(WIFI_OPT_INVALID_PARAM, pScanInterface->OnScreenStateChanged(screenState)); +} + +HWTEST_F(ScanInterfaceTest, OnClientModeStatusChangedSuccess, TestSize.Level1) +{ + EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->OnClientModeStatusChanged(0)); +} + +HWTEST_F(ScanInterfaceTest, OnAppRunningModeChangedSuccess, TestSize.Level1) +{ + EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->OnAppRunningModeChanged(0)); +} + +HWTEST_F(ScanInterfaceTest, OnCustomControlStateChangedSuccess, TestSize.Level1) +{ + int customSceneStatus = STATE_OPEN; + EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->OnCustomControlStateChanged(0, customSceneStatus)); +} + +HWTEST_F(ScanInterfaceTest, OnCustomControlStateChangedFail, TestSize.Level1) +{ + int customSceneStatus = 0; + EXPECT_EQ(WIFI_OPT_INVALID_PARAM, pScanInterface->OnCustomControlStateChanged(0, customSceneStatus)); +} + +HWTEST_F(ScanInterfaceTest, OnControlStrategyChangedSuccess, TestSize.Level1) +{ + EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->OnControlStrategyChanged()); +} + +HWTEST_F(ScanInterfaceTest, RegisterScanCallbacksTest, TestSize.Level1) +{ + IScanSerivceCallbacks callbacks; + EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->RegisterScanCallbacks(callbacks)); +} +} // namespace Wifi +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor_test.cpp new file mode 100644 index 000000000..b02c5556d --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor_test.cpp @@ -0,0 +1,160 @@ +/* + * 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 "scan_monitor.h" +#include "mock_scan_state_machine.h" +#include "mock_wifi_supplicant_hal_interface.h" +#include + +using ::testing::_; +using ::testing::AtLeast; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::StrEq; +using ::testing::TypedEq; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class ScanMonitorTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + void SetUp() override + { + pScanMonitor = std::make_unique(); + pScanStateMachine = std::make_unique(); + pScanMonitor->SetScanStateMachine(pScanStateMachine.get()); + } + void TearDown() override + { + EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), UnRegisterSupplicantEventCallback()); + pScanMonitor.reset(); + pScanStateMachine.reset(); + } + +public: + std::unique_ptr pScanMonitor; + std::unique_ptr pScanStateMachine; + + void InitScanMonitorSuccessTest() + { + EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), RegisterSupplicantEventCallback(_)) + .WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + + EXPECT_EQ(pScanMonitor->InitScanMonitor(), true); + } + + void InitScanMonitorFailTest() + { + EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), RegisterSupplicantEventCallback(_)) + .WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + + EXPECT_EQ(pScanMonitor->InitScanMonitor(), false); + } + + void ReceiveScanEventFromIdlTest() + { + pScanMonitor->ReceiveScanEventFromIdl(0); + } + + void ProcessReceiveScanEventTest1() + { + pScanMonitor->ProcessReceiveScanEvent(SINGLE_SCAN_OVER_OK); + } + + void ProcessReceiveScanEventTest2() + { + pScanMonitor->ProcessReceiveScanEvent(SINGLE_SCAN_FAILED); + } + + void ProcessReceiveScanEventTest3() + { + pScanMonitor->ProcessReceiveScanEvent(PNO_SCAN_OVER_OK); + } + + void ProcessReceiveScanEventTest4() + { + pScanMonitor->ProcessReceiveScanEvent(WPA_CB_CONNECTED); + } + + void SendScanInfoEventTest() + { + pScanMonitor->SendScanInfoEvent(); + } + + void SendPnoScanInfoEventTest() + { + pScanMonitor->SendPnoScanInfoEvent(); + } + + void SendScanFailedEventTest() + { + pScanMonitor->SendScanFailedEvent(); + } +}; + +HWTEST_F(ScanMonitorTest, InitScanMonitorSuccessTest, TestSize.Level1) +{ + InitScanMonitorSuccessTest(); +} + +HWTEST_F(ScanMonitorTest, InitScanMonitorFailTest, TestSize.Level1) +{ + InitScanMonitorFailTest(); +} + +HWTEST_F(ScanMonitorTest, ReceiveScanEventFromIdlTest, TestSize.Level1) +{ + ReceiveScanEventFromIdlTest(); +} + +HWTEST_F(ScanMonitorTest, ProcessReceiveScanEventTest1, TestSize.Level1) +{ + ProcessReceiveScanEventTest1(); +} + +HWTEST_F(ScanMonitorTest, ProcessReceiveScanEventTest2, TestSize.Level1) +{ + ProcessReceiveScanEventTest2(); +} + +HWTEST_F(ScanMonitorTest, ProcessReceiveScanEventTest3, TestSize.Level1) +{ + ProcessReceiveScanEventTest3(); +} + +HWTEST_F(ScanMonitorTest, ProcessReceiveScanEventTest4, TestSize.Level1) +{ + ProcessReceiveScanEventTest4(); +} + +HWTEST_F(ScanMonitorTest, SendScanInfoEventTest, TestSize.Level1) +{ + SendScanInfoEventTest(); +} + +HWTEST_F(ScanMonitorTest, SendPnoScanInfoEventTest, TestSize.Level1) +{ + SendPnoScanInfoEventTest(); +} + +HWTEST_F(ScanMonitorTest, SendScanFailedEventTest, TestSize.Level1) +{ + SendScanFailedEventTest(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service_test.cpp new file mode 100644 index 000000000..3914ad405 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service_test.cpp @@ -0,0 +1,2043 @@ +/* + * 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 "scan_service.h" +#include +#include "mock_wifi_manager.h" +#include "mock_wifi_settings.h" +#include "mock_scan_state_machine.h" +#include "mock_wifi_supplicant_hal_interface.h" +#include "mock_wifi_sta_hal_interface.h" + +using ::testing::_; +using ::testing::AtLeast; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::StrEq; +using ::testing::TypedEq; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +constexpr int FREQ_2_DOT_4_GHZ = 2450; +constexpr int FREQ_5_GHZ = 5200; +class ScanServiceTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + virtual void SetUp() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).Times(AtLeast(0)); + pScanService = std::make_unique(); + pScanService->pScanStateMachine = new MockScanStateMachine(); + pScanService->mScanSerivceCallbacks = WifiManager::GetInstance().GetScanCallback(); + } + virtual void TearDown() + { + pScanService.reset(); + } + +public: + std::unique_ptr pScanService; + + void InitScanServiceSuccess1() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetSupportHwPnoFlag()).Times(AtLeast(1)); + EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), RegisterSupplicantEventCallback(_)).Times(AtLeast(1)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetSupportFrequencies(_, _)).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScanControlInfo(_)).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScreenState()).Times(AtLeast(1)); + EXPECT_CALL(WifiManager::GetInstance(), DealScanOpenRes()).Times(AtLeast(0)); + EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), UnRegisterSupplicantEventCallback()).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_EQ(pScanService->InitScanService(WifiManager::GetInstance().GetScanCallback()), true); + } + + void InitScanServiceSuccess2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetSupportFrequencies(_, _)) + .WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiSettings::GetInstance(), GetSupportHwPnoFlag()).Times(AtLeast(1)); + EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), RegisterSupplicantEventCallback(_)).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScanControlInfo(_)).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScreenState()).Times(AtLeast(1)); + EXPECT_CALL(WifiManager::GetInstance(), DealScanOpenRes()).Times(AtLeast(0)); + EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), UnRegisterSupplicantEventCallback()).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_EQ(pScanService->InitScanService(WifiManager::GetInstance().GetScanCallback()), true); + } + + void UnInitScanServiceSuccess() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanService->UnInitScanService(); + } + + void HandleScanStatusReportSuccess1() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()) + .Times(AtLeast(1)) + .WillRepeatedly(Return(true)); + EXPECT_CALL(WifiManager::GetInstance(), DealScanOpenRes()).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).Times(AtLeast(0)); + ScanStatusReport scanStatusReport; + scanStatusReport.status = SCAN_STARTED_STATUS; + pScanService->HandleScanStatusReport(scanStatusReport); + } + + void HandleScanStatusReportSuccess2() + { + EXPECT_CALL(WifiManager::GetInstance(), DealScanCloseRes()).Times(AtLeast(1)); + ScanStatusReport scanStatusReport; + scanStatusReport.status = SCAN_FINISHED_STATUS; + pScanService->HandleScanStatusReport(scanStatusReport); + } + + void HandleScanStatusReportSuccess3() + { + EXPECT_CALL(WifiManager::GetInstance(), DealScanFinished(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveScanInfoList(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiManager::GetInstance(), DealScanInfoNotify(_)).Times(AtLeast(1)); + ScanStatusReport scanStatusReport; + scanStatusReport.status = COMMON_SCAN_SUCCESS; + pScanService->HandleScanStatusReport(scanStatusReport); + } + + void HandleScanStatusReportSuccess4() + { + EXPECT_CALL(WifiManager::GetInstance(), DealScanFinished(_)).Times(AtLeast(0)); + ScanStatusReport scanStatusReport; + scanStatusReport.status = COMMON_SCAN_FAILED; + pScanService->HandleScanStatusReport(scanStatusReport); + } + + void HandleScanStatusReportSuccess5() + { + EXPECT_CALL(WifiManager::GetInstance(), DealScanInfoNotify(_)).Times(AtLeast(1)); + ScanStatusReport scanStatusReport; + scanStatusReport.status = PNO_SCAN_RESULT; + pScanService->HandleScanStatusReport(scanStatusReport); + } + + void HandleScanStatusReportSuccess6() + { + ScanStatusReport scanStatusReport; + scanStatusReport.status = PNO_SCAN_FAILED; + pScanService->HandleScanStatusReport(scanStatusReport); + } + + void HandleScanStatusReportSuccess7() + { + ScanStatusReport scanStatusReport; + scanStatusReport.status = SCAN_INNER_EVENT; + pScanService->HandleScanStatusReport(scanStatusReport); + } + + void HandleScanStatusReportFail() + { + ScanStatusReport scanStatusReport; + scanStatusReport.status = SCAN_STATUS_INVALID; + pScanService->HandleScanStatusReport(scanStatusReport); + } + + void HandleInnerEventReportSuccess1() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()) + .Times(AtLeast(1)) + .WillRepeatedly(Return(true)); + ScanInnerEventType innerEvent; + innerEvent = SYSTEM_SCAN_TIMER; + pScanService->HandleInnerEventReport(innerEvent); + } + + void HandleInnerEventReportSuccess2() + { + ScanInnerEventType innerEvent; + innerEvent = DISCONNECTED_SCAN_TIMER; + pScanService->HandleInnerEventReport(innerEvent); + } + + void HandleInnerEventReportSuccess3() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetMinRssi2Dot4Ghz()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetMinRssi5Ghz()).Times(AtLeast(0)); + ScanInnerEventType innerEvent; + innerEvent = RESTART_PNO_SCAN_TIMER; + pScanService->HandleInnerEventReport(innerEvent); + } + + void HandleInnerEventReportFail() + { + ScanInnerEventType innerEvent; + innerEvent = SCAN_INNER_EVENT_INVALID; + pScanService->HandleInnerEventReport(innerEvent); + } + + void ScanSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).WillRepeatedly(Return(true)); + pScanService->scanStartedFlag = true; + pScanService->Scan(false); + } + + void ScanFail() + { + pScanService->scanStartedFlag = false; + pScanService->Scan(false); + } + + void ScanWithParamSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).WillRepeatedly(Return(true)); + pScanService->scanStartedFlag = true; + WifiScanParams params; + params.band = SCAN_BAND_BOTH_WITH_DFS; + EXPECT_EQ(WIFI_OPT_SUCCESS, pScanService->ScanWithParam(params)); + } + + void ScanWithParamFail1() + { + pScanService->scanStartedFlag = false; + WifiScanParams params; + params.band = SCAN_BAND_BOTH_WITH_DFS; + EXPECT_EQ(WIFI_OPT_FAILED, pScanService->ScanWithParam(params)); + } + + void ScanWithParamFail2() + { + pScanService->scanStartedFlag = false; + WifiScanParams params; + params.band = -1; + EXPECT_EQ(WIFI_OPT_FAILED, pScanService->ScanWithParam(params)); + } + + void ScanWithParamFail3() + { + pScanService->scanStartedFlag = true; + WifiScanParams params; + params.band = SCAN_BAND_UNSPECIFIED; + EXPECT_EQ(WIFI_OPT_FAILED, pScanService->ScanWithParam(params)); + } + + void ScanWithParamFail4() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).WillRepeatedly(Return(false)); + pScanService->scanStartedFlag = true; + WifiScanParams params; + params.band = SCAN_BAND_UNSPECIFIED; + EXPECT_EQ(WIFI_OPT_FAILED, pScanService->ScanWithParam(params)); + } + + void SingleScanSuccess1() + { + ScanConfig scanConfig; + scanConfig.scanBand = SCAN_BAND_BOTH_WITH_DFS; + scanConfig.externFlag = true; + scanConfig.scanStyle = SCAN_TYPE_HIGH_ACCURACY; + EXPECT_EQ(true, pScanService->SingleScan(scanConfig)); + } + + void SingleScanSuccess2() + { + ScanConfig scanConfig; + scanConfig.scanBand = SCAN_BAND_UNSPECIFIED; + scanConfig.externFlag = true; + scanConfig.scanStyle = SCAN_TYPE_HIGH_ACCURACY; + scanConfig.scanFreqs.push_back(0); + EXPECT_EQ(true, pScanService->SingleScan(scanConfig)); + } + + void SingleScanSuccess3() + { + ScanConfig scanConfig; + scanConfig.scanBand = SCAN_BAND_24_GHZ; + ; + scanConfig.externFlag = true; + scanConfig.scanStyle = SCAN_TYPE_HIGH_ACCURACY; + EXPECT_EQ(true, pScanService->SingleScan(scanConfig)); + } + + void SingleScanFail1() + { + ScanConfig scanConfig; + scanConfig.scanBand = SCAN_BAND_UNSPECIFIED; + scanConfig.externFlag = true; + scanConfig.scanStyle = SCAN_TYPE_HIGH_ACCURACY; + EXPECT_EQ(false, pScanService->SingleScan(scanConfig)); + } + + void GetBandFreqsSuccess1() + { + ScanBandType band = SCAN_BAND_24_GHZ; + std::vector freqs; + EXPECT_EQ(true, pScanService->GetBandFreqs(band, freqs)); + } + + void GetBandFreqsSuccess2() + { + ScanBandType band = SCAN_BAND_5_GHZ; + std::vector freqs; + EXPECT_EQ(true, pScanService->GetBandFreqs(band, freqs)); + } + + void GetBandFreqsSuccess3() + { + ScanBandType band = SCAN_BAND_BOTH; + std::vector freqs; + EXPECT_EQ(true, pScanService->GetBandFreqs(band, freqs)); + } + + void GetBandFreqsSuccess4() + { + ScanBandType band = SCAN_BAND_5_GHZ_DFS_ONLY; + std::vector freqs; + EXPECT_EQ(true, pScanService->GetBandFreqs(band, freqs)); + } + + void GetBandFreqsSuccess5() + { + ScanBandType band = SCAN_BAND_5_GHZ_WITH_DFS; + std::vector freqs; + EXPECT_EQ(true, pScanService->GetBandFreqs(band, freqs)); + } + + void GetBandFreqsSuccess6() + { + ScanBandType band = SCAN_BAND_BOTH_WITH_DFS; + std::vector freqs; + EXPECT_EQ(true, pScanService->GetBandFreqs(band, freqs)); + } + + void GetBandFreqsFail() + { + ScanBandType band = SCAN_BAND_UNSPECIFIED; + std::vector freqs; + EXPECT_EQ(false, pScanService->GetBandFreqs(band, freqs)); + } + + void AddScanMessageBodySuccess() + { + InternalMessage msg; + InterScanConfig interConfig; + interConfig.hiddenNetworkSsid.push_back("hmwifi"); + interConfig.scanFreqs.push_back(FREQ_2_DOT_4_GHZ); + EXPECT_EQ(true, pScanService->AddScanMessageBody(&msg, interConfig)); + } + + void AddScanMessageBodyFail() + { + InterScanConfig interConfig; + EXPECT_EQ(false, pScanService->AddScanMessageBody(nullptr, interConfig)); + } + + void StoreRequestScanConfigSuccess() + { + ScanConfig scanConfig; + InterScanConfig interConfig; + pScanService->StoreRequestScanConfig(scanConfig, interConfig); + } + + void HandleCommonScanFailedSuccess1() + { + EXPECT_CALL(WifiManager::GetInstance(), DealScanFinished(_)).Times(AtLeast(0)); + pScanService->staStatus = static_cast(OperateResState::CONNECT_CONNECTING); + std::vector requestIndexList; + pScanService->HandleCommonScanFailed(requestIndexList); + } + + void HandleCommonScanFailedSuccess2() + { + EXPECT_CALL(WifiManager::GetInstance(), DealScanFinished(_)).Times(AtLeast(0)); + pScanService->staStatus = static_cast(OperateResState::DISCONNECT_DISCONNECTED); + std::vector requestIndexList; + requestIndexList.push_back(0); + pScanService->HandleCommonScanFailed(requestIndexList); + } + + void HandleCommonScanFailedSuccess3() + { + EXPECT_CALL(WifiManager::GetInstance(), DealScanFinished(_)); + pScanService->staStatus = static_cast(OperateResState::DISCONNECT_DISCONNECTED); + StoreScanConfig storeScanConfig; + storeScanConfig.fullScanFlag = true; + pScanService->scanConfigMap.emplace(0, storeScanConfig); + std::vector requestIndexList; + requestIndexList.push_back(0); + pScanService->HandleCommonScanFailed(requestIndexList); + } + + void HandleCommonScanFailedSuccess4() + { + EXPECT_CALL(WifiManager::GetInstance(), DealScanFinished(_)).Times(AtLeast(0)); + pScanService->staStatus = static_cast(OperateResState::DISCONNECT_DISCONNECTED); + StoreScanConfig storeScanConfig; + storeScanConfig.fullScanFlag = false; + pScanService->scanConfigMap.emplace(0, storeScanConfig); + std::vector requestIndexList; + requestIndexList.push_back(0); + pScanService->HandleCommonScanFailed(requestIndexList); + } + + void HandleCommonScanInfoSuccess1() + { + std::vector requestIndexList; + requestIndexList.push_back(0); + std::vector scanInfoList; + pScanService->HandleCommonScanInfo(requestIndexList, scanInfoList); + } + + void HandleCommonScanInfoSuccess2() + { + EXPECT_CALL(WifiSettings::GetInstance(), SaveScanInfoList(_)).Times(AtLeast(1)); + StoreScanConfig storeScanConfig0; + storeScanConfig0.fullScanFlag = true; + StoreScanConfig storeScanConfig1; + storeScanConfig1.fullScanFlag = true; + pScanService->scanConfigMap.emplace(0, storeScanConfig0); + pScanService->scanConfigMap.emplace(1, storeScanConfig1); + std::vector requestIndexList { 0, 1 }; + std::vector scanInfoList; + pScanService->HandleCommonScanInfo(requestIndexList, scanInfoList); + } + + void HandleCommonScanInfoSuccess3() + { + EXPECT_CALL(WifiSettings::GetInstance(), SaveScanInfoList(_)).Times(AtLeast(0)); + StoreScanConfig storeScanConfig; + storeScanConfig.fullScanFlag = false; + pScanService->scanConfigMap.emplace(0, storeScanConfig); + std::vector requestIndexList { 0 }; + std::vector scanInfoList; + pScanService->HandleCommonScanInfo(requestIndexList, scanInfoList); + } + + void StoreFullScanInfoSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), SaveScanInfoList(_)).WillRepeatedly(Return(0)); + StoreScanConfig scanConfig; + std::vector scanInfoList { InterScanInfo() }; + EXPECT_EQ(true, pScanService->StoreFullScanInfo(scanConfig, scanInfoList)); + } + + void StoreFullScanInfoFail() + { + EXPECT_CALL(WifiSettings::GetInstance(), SaveScanInfoList(_)).WillRepeatedly(Return(-1)); + StoreScanConfig scanConfig; + std::vector scanInfoList { InterScanInfo() }; + EXPECT_EQ(false, pScanService->StoreFullScanInfo(scanConfig, scanInfoList)); + } + + void StoreUserScanInfoSuccess1() + { + StoreScanConfig scanConfig; + std::vector scanInfoList { InterScanInfo() }; + EXPECT_EQ(true, pScanService->StoreUserScanInfo(scanConfig, scanInfoList)); + } + + void StoreUserScanInfoSuccess2() + { + StoreScanConfig scanConfig; + scanConfig.scanFreqs.push_back(FREQ_2_DOT_4_GHZ); + std::vector scanInfoList; + InterScanInfo interScanInfo; + interScanInfo.timestamp = 1; + scanInfoList.push_back(interScanInfo); + EXPECT_EQ(true, pScanService->StoreUserScanInfo(scanConfig, scanInfoList)); + } + + void ReportScanInfosSuccess() + { + EXPECT_CALL(WifiManager::GetInstance(), DealScanInfoNotify(_)); + std::vector scanInfoList; + pScanService->ReportScanInfos(scanInfoList); + } + + void BeginPnoScanSuccess1() + { + pScanService->isPnoScanBegined = false; + std::vector results; + WifiDeviceConfig cfg; + cfg.status = static_cast(WifiDeviceConfigStatus::ENABLED); + cfg.isPasspoint = false; + cfg.isEphemeral = false; + results.push_back(cfg); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(results), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), SaveScanInfoList(_)).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetMinRssi2Dot4Ghz()); + EXPECT_CALL(WifiSettings::GetInstance(), GetMinRssi5Ghz()); + EXPECT_EQ(true, pScanService->BeginPnoScan()); + } + + void BeginPnoScanFail1() + { + pScanService->isPnoScanBegined = false; + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveScanInfoList(_)).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_EQ(false, pScanService->BeginPnoScan()); + } + + void BeginPnoScanFail2() + { + pScanService->isPnoScanBegined = false; + pScanService->staStatus = static_cast(OperateResState::OPEN_WIFI_OPENING); + EXPECT_CALL(WifiSettings::GetInstance(), SaveScanInfoList(_)).WillRepeatedly(Return(0)); + EXPECT_EQ(false, pScanService->BeginPnoScan()); + } + + void BeginPnoScanFail3() + { + pScanService->isPnoScanBegined = true; + EXPECT_EQ(false, pScanService->BeginPnoScan()); + } + + void PnoScanSuccess() + { + PnoScanConfig pnoScanConfig; + InterScanConfig interScanConfig; + EXPECT_EQ(true, pScanService->PnoScan(pnoScanConfig, interScanConfig)); + } + + void AddPnoScanMessageBodySuccess() + { + InternalMessage interMessage; + PnoScanConfig pnoScanConfig; + EXPECT_EQ(true, pScanService->AddPnoScanMessageBody(&interMessage, pnoScanConfig)); + } + + void AddPnoScanMessageBodyFail() + { + PnoScanConfig pnoScanConfig; + EXPECT_EQ(false, pScanService->AddPnoScanMessageBody(nullptr, pnoScanConfig)); + } + + void HandlePnoScanInfoSuccess() + { + EXPECT_CALL(WifiManager::GetInstance(), DealScanInfoNotify(_)); + std::vector scanInfoList; + InterScanInfo interScanInfo; + interScanInfo.timestamp = 1000; + scanInfoList.push_back(interScanInfo); + pScanService->pnoScanStartTime = 0; + pScanService->HandlePnoScanInfo(scanInfoList); + } + + void EndPnoScanSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).Times(AtLeast(0)); + pScanService->isPnoScanBegined = true; + pScanService->EndPnoScan(); + } + + void EndPnoScanFail() + { + pScanService->EndPnoScan(); + } + + void HandleScreenStatusChangedSuccess() + { + pScanService->HandleScreenStatusChanged(false); + pScanService->HandleScreenStatusChanged(true); + } + + void HandleStaStatusChangedSuccess1() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()); + int status = static_cast(OperateResState::DISCONNECT_DISCONNECTED); + pScanService->HandleStaStatusChanged(status); + } + + void HandleStaStatusChangedSuccess2() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()); + int status = static_cast(OperateResState::CONNECT_AP_CONNECTED); + pScanService->HandleStaStatusChanged(status); + } + + void HandleStaStatusChangedFail() + { + int status = static_cast(OperateResState::OPEN_WIFI_FAILED); + pScanService->HandleStaStatusChanged(status); + } + + void HandleCustomStatusChangedSuccess1() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).Times(AtLeast(0)); + int customScene = 0; + int customSceneStatus = STATE_CLOSE; + pScanService->HandleCustomStatusChanged(customScene, customSceneStatus); + } + + void HandleCustomStatusChangedSuccess2() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).Times(AtLeast(0)); + int customScene = 0; + int customSceneStatus = STATE_OPEN; + pScanService->HandleCustomStatusChanged(customScene, customSceneStatus); + } + + void SystemScanProcessSuccess1() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()); + pScanService->isScreenOn = true; + ScanIntervalMode mode; + mode.scanMode = ScanMode::SYSTEM_TIMER_SCAN; + mode.isSingle = false; + pScanService->scanControlInfo.scanIntervalList.push_back(mode); + pScanService->SystemScanProcess(true); + } + + void SystemScanProcessSuccess2() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()); + EXPECT_CALL(WifiSettings::GetInstance(), GetMinRssi2Dot4Ghz()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetMinRssi5Ghz()).Times(AtLeast(0)); + pScanService->isScreenOn = false; + pScanService->SystemScanProcess(true); + } + + void StopSystemScanSuccess() + { + pScanService->StopSystemScan(); + } + + void StartSystemTimerScanSuccess() + { + pScanService->StartSystemTimerScan(true); + } + + void HandleSystemScanTimeoutSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()); + pScanService->HandleSystemScanTimeout(); + } + + void DisconnectedTimerScanSuccess() + { + pScanService->DisconnectedTimerScan(); + } + + void HandleDisconnectedScanTimeoutSuccess() + { + pScanService->HandleDisconnectedScanTimeout(); + } + + void RestartPnoScanTimeOutSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetMinRssi2Dot4Ghz()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetMinRssi5Ghz()).Times(AtLeast(0)); + pScanService->RestartPnoScanTimeOut(); + } + + void GetScanControlInfoSuccess() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScanControlInfo(_)).WillRepeatedly(Return(0)); + pScanService->GetScanControlInfo(); + } + + void GetScanControlInfoFail() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScanControlInfo(_)).WillRepeatedly(Return(-1)); + pScanService->GetScanControlInfo(); + } + + void GetScreenStateSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetScreenState()).WillRepeatedly(Return(SCREEN_CLOSED)); + pScanService->GetScreenState(); + } + + void SetOperateAppModeSuccess() + { + pScanService->SetOperateAppMode(0); + } + + void GetOperateAppModeSuccess1() + { + pScanService->operateAppMode = APP_FOREGROUND_SCAN; + EXPECT_EQ(ScanMode::APP_FOREGROUND_SCAN, pScanService->GetOperateAppMode()); + } + + void GetOperateAppModeSuccess2() + { + pScanService->operateAppMode = APP_BACKGROUND_SCAN; + EXPECT_EQ(ScanMode::APP_BACKGROUND_SCAN, pScanService->GetOperateAppMode()); + } + + void GetOperateAppModeSuccess3() + { + pScanService->operateAppMode = SYS_FOREGROUND_SCAN; + EXPECT_EQ(ScanMode::SYS_FOREGROUND_SCAN, pScanService->GetOperateAppMode()); + } + + void GetOperateAppModeSuccess4() + { + pScanService->operateAppMode = SYS_BACKGROUND_SCAN; + EXPECT_EQ(ScanMode::SYS_BACKGROUND_SCAN, pScanService->GetOperateAppMode()); + } + + void GetOperateAppModeFail() + { + pScanService->operateAppMode = MAX_PNO_SCAN_FAILED_NUM; + EXPECT_EQ(ScanMode::SYS_FOREGROUND_SCAN, pScanService->GetOperateAppMode()); + } + + void AllowExternScanSuccess() + { + pScanService->AllowExternScan(0); + } + + void AllowExternScanFail1() + { + int staScene = 0; + StoreScanConfig cfg; + cfg.externFlag = true; + pScanService->scanConfigMap.emplace(staScene, cfg); + pScanService->AllowExternScan(0); + } + + void AllowSystemTimerScanSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()); + ScanIntervalMode mode; + mode.scanMode = ScanMode::SYSTEM_TIMER_SCAN; + mode.isSingle = false; + pScanService->scanControlInfo.scanIntervalList.push_back(mode); + pScanService->AllowSystemTimerScan(); + } + + void AllowPnoScanSuccess() + { + ScanIntervalMode mode; + mode.scanMode = ScanMode::PNO_SCAN; + mode.isSingle = false; + pScanService->scanControlInfo.scanIntervalList.push_back(mode); + pScanService->AllowPnoScan(); + } + + void AllowExternScanByForbidSuccess1() + { + int staScene = 0; + StoreScanConfig cfg; + cfg.externFlag = true; + pScanService->scanConfigMap.emplace(staScene, cfg); + pScanService->isScreenOn = false; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + EXPECT_EQ(pScanService->AllowExternScanByForbid(staScene, scanMode), true); + } + + void AllowExternScanByIntervaluccess() + { + pScanService->AllowExternScanByInterval(0, 0, ScanMode::SYS_FOREGROUND_SCAN); + } + + void GetStaSceneSuccess1() + { + pScanService->staStatus = static_cast(OperateResState::CONNECT_AP_CONNECTED); + EXPECT_EQ(SCAN_SCENE_CONNECTED, pScanService->GetStaScene()); + } + + void GetStaSceneSuccess2() + { + pScanService->staStatus = static_cast(OperateResState::DISCONNECT_DISCONNECTED); + EXPECT_EQ(SCAN_SCENE_DISCONNCTED, pScanService->GetStaScene()); + } + + void GetStaSceneSuccess3() + { + pScanService->staStatus = static_cast(OperateResState::CONNECT_CONNECTING); + EXPECT_EQ(SCAN_SCENE_CONNECTING, pScanService->GetStaScene()); + } + + void GetStaSceneSuccess4() + { + pScanService->staStatus = static_cast(OperateResState::CONNECT_OBTAINING_IP); + EXPECT_EQ(SCAN_SCENE_OBTAINING_IP, pScanService->GetStaScene()); + } + + void GetStaSceneSuccess5() + { + } + + void GetStaSceneSuccess6() + { + } + + void GetStaSceneFail() + { + pScanService->staStatus = static_cast(OperateResState::OPEN_WIFI_FAILED); + EXPECT_EQ(SCAN_SCENE_MAX, pScanService->GetStaScene()); + } + + void IsExternScanningSuccess() + { + StoreScanConfig storeScanConfig; + storeScanConfig.externFlag = true; + pScanService->scanConfigMap.emplace(0, storeScanConfig); + EXPECT_EQ(true, pScanService->IsExternScanning()); + } + + void IsExternScanningFail() + { + StoreScanConfig storeScanConfig; + storeScanConfig.externFlag = false; + pScanService->scanConfigMap.emplace(0, storeScanConfig); + EXPECT_EQ(false, pScanService->IsExternScanning()); + } + + void GetAllowBandFreqsControlInfoSuccess() + { + std::vector freqs; + freqs.push_back(FREQ_2_DOT_4_GHZ); + ScanBandType scanBand = SCAN_BAND_24_GHZ; + pScanService->GetAllowBandFreqsControlInfo(scanBand, freqs); + } + + void ConvertBandNotAllow24GSuccess1() + { + ScanBandType scanBand = SCAN_BAND_24_GHZ; + EXPECT_EQ(SCAN_BAND_UNSPECIFIED, pScanService->ConvertBandNotAllow24G(scanBand)); + } + + void ConvertBandNotAllow24GSuccess2() + { + ScanBandType scanBand = SCAN_BAND_BOTH; + EXPECT_EQ(SCAN_BAND_5_GHZ, pScanService->ConvertBandNotAllow24G(scanBand)); + } + + void ConvertBandNotAllow24GSuccess3() + { + ScanBandType scanBand = SCAN_BAND_BOTH_WITH_DFS; + EXPECT_EQ(SCAN_BAND_5_GHZ_WITH_DFS, pScanService->ConvertBandNotAllow24G(scanBand)); + } + + void ConvertBandNotAllow24GSuccess4() + { + ScanBandType scanBand = SCAN_BAND_5_GHZ; + EXPECT_EQ(SCAN_BAND_5_GHZ, pScanService->ConvertBandNotAllow24G(scanBand)); + } + + void ConvertBandNotAllow24GFail() + { + ScanBandType scanBand = SCAN_BAND_UNSPECIFIED; + EXPECT_EQ(SCAN_BAND_UNSPECIFIED, pScanService->ConvertBandNotAllow24G(scanBand)); + } + + void ConvertBandNotAllow5GSuccess() + { + ScanBandType scanBand = SCAN_BAND_24_GHZ; + EXPECT_EQ(SCAN_BAND_24_GHZ, pScanService->ConvertBandNotAllow5G(scanBand)); + } + + void ConvertBandNotAllow5GFail() + { + ScanBandType scanBand = SCAN_BAND_5_GHZ; + EXPECT_EQ(SCAN_BAND_UNSPECIFIED, pScanService->ConvertBandNotAllow5G(scanBand)); + } + + void Delete24GhzFreqsSuccess() + { + std::vector freqs; + freqs.push_back(FREQ_2_DOT_4_GHZ); + pScanService->Delete24GhzFreqs(freqs); + } + + void Delete5GhzFreqsSuccess() + { + std::vector freqs; + freqs.push_back(FREQ_5_GHZ); + pScanService->Delete5GhzFreqs(freqs); + } + + void GetSavedNetworkSsidListSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).WillRepeatedly(Return(0)); + std::vector savedNetworkSsid; + EXPECT_EQ(true, pScanService->GetSavedNetworkSsidList(savedNetworkSsid)); + } + + void GetSavedNetworkSsidListFail() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).WillRepeatedly(Return(-1)); + std::vector savedNetworkSsid; + EXPECT_EQ(false, pScanService->GetSavedNetworkSsidList(savedNetworkSsid)); + } + + void GetHiddenNetworkSsidListSuccess1() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).WillRepeatedly(Return(0)); + std::vector hiddenNetworkSsid; + EXPECT_EQ(true, pScanService->GetHiddenNetworkSsidList(hiddenNetworkSsid)); + } + + void GetHiddenNetworkSsidListSuccess2() + { + std::vector deviceConfigs; + WifiDeviceConfig cfg; + cfg.hiddenSSID = true; + deviceConfigs.push_back(cfg); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(deviceConfigs), Return(0))); + std::vector hiddenNetworkSsid; + EXPECT_EQ(true, pScanService->GetHiddenNetworkSsidList(hiddenNetworkSsid)); + } + + void GetHiddenNetworkSsidListFail() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).WillRepeatedly(Return(-1)); + std::vector hiddenNetworkSsid; + EXPECT_EQ(false, pScanService->GetHiddenNetworkSsidList(hiddenNetworkSsid)); + } + + void ClearScanControlValueSuccess() + { + pScanService->ClearScanControlValue(); + } + + void SetStaCurrentTimeSuccess() + { + pScanService->SetStaCurrentTime(); + } + + void AllowScanDuringScanningSuccess() + { + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + EXPECT_EQ(pScanService->AllowScanDuringScanning(scanMode), true); + } + + void AllowScanDuringScreenOffSuccess() + { + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + EXPECT_EQ(pScanService->AllowScanDuringScreenOff(scanMode), true); + } + + void AllowScanDuringStaSceneSuccess1() + { + const int staScene = 0; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + time_t nowTime = time(nullptr); + const int timeForTest = 2; + pScanService->staCurrentTime = nowTime - timeForTest; + EXPECT_EQ(pScanService->AllowScanDuringStaScene(staScene, scanMode), true); + } + + void AllowScanDuringCustomSceneSuccess() + { + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + EXPECT_EQ(pScanService->AllowScanDuringCustomScene(scanMode), true); + } + + void AllowExternScanByIntervalMode() + { + pScanService->AllowExternScanByIntervalMode(0, 0, ScanMode::SYS_FOREGROUND_SCAN); + } + + void AllowExternScanByCustomSceneSuccess() + { + pScanService->AllowExternScanByCustomScene(0, ScanMode::SYS_FOREGROUND_SCAN); + } + + void PnoScanByIntervalSuccess1() + { + int fixedScanCount = 0; + time_t fixedScanTime = 0; + int interval = 0; + int count = 0; + EXPECT_EQ(pScanService->PnoScanByInterval(fixedScanCount, fixedScanTime, interval, count), true); + } + + void PnoScanByIntervalSuccess2() + { + int fixedScanCount = 1; + time_t fixedScanTime = time(nullptr) - 1; + int interval = 0; + int count = 0; + EXPECT_EQ(pScanService->PnoScanByInterval(fixedScanCount, fixedScanTime, interval, count), true); + } + + void PnoScanByIntervalSuccess3() + { + int fixedScanCount = 1; + time_t fixedScanTime = time(nullptr) + 1; + int interval = 1; + int count = 1; + EXPECT_EQ(pScanService->PnoScanByInterval(fixedScanCount, fixedScanTime, interval, count), true); + } + + void PnoScanByIntervalFail1() + { + int fixedScanCount = 2; + time_t fixedScanTime = time(nullptr) + 1; + int interval = 1; + int count = 1; + EXPECT_EQ(pScanService->PnoScanByInterval(fixedScanCount, fixedScanTime, interval, count), false); + } + + void SystemScanByIntervalSuccess() + { + int expScanCount = 1; + int interval = 1; + const int constTest = 2; + int count = constTest; + EXPECT_EQ(pScanService->SystemScanByInterval(expScanCount, interval, count), true); + } + + void ExternScanByIntervalSuccess1() + { + SingleAppForbid singleAppForbid; + singleAppForbid.scanIntervalMode.intervalMode = IntervalMode::INTERVAL_FIXED; + EXPECT_EQ(pScanService->ExternScanByInterval(0, singleAppForbid), true); + } + + void ExternScanByIntervalSuccess2() + { + SingleAppForbid singleAppForbid; + singleAppForbid.scanIntervalMode.intervalMode = IntervalMode::INTERVAL_EXP; + EXPECT_EQ(pScanService->ExternScanByInterval(0, singleAppForbid), true); + } + + void ExternScanByIntervalSuccess3() + { + SingleAppForbid singleAppForbid; + singleAppForbid.scanIntervalMode.intervalMode = IntervalMode::INTERVAL_CONTINUE; + EXPECT_EQ(pScanService->ExternScanByInterval(0, singleAppForbid), true); + } + + void ExternScanByIntervalSuccess4() + { + SingleAppForbid singleAppForbid; + singleAppForbid.scanIntervalMode.intervalMode = IntervalMode::INTERVAL_BLOCKLIST; + EXPECT_EQ(pScanService->ExternScanByInterval(0, singleAppForbid), true); + } + + void ExternScanByIntervalSuccess5() + { + SingleAppForbid singleAppForbid; + singleAppForbid.scanIntervalMode.intervalMode = IntervalMode::INTERVAL_MAX; + EXPECT_EQ(pScanService->ExternScanByInterval(0, singleAppForbid), true); + } + + void AllowSingleAppScanByIntervalSuccess1() + { + int appId = 0; + ScanIntervalMode scanIntervalMode; + EXPECT_EQ(pScanService->AllowSingleAppScanByInterval(appId, scanIntervalMode), true); + } + + void AllowSingleAppScanByIntervalSuccess2() + { + int appId = 0; + SingleAppForbid sAppForbid; + sAppForbid.appID = appId; + sAppForbid.scanIntervalMode.scanMode = ScanMode::SCAN_MODE_MAX; + pScanService->appForbidList.push_back(sAppForbid); + ScanIntervalMode scanIntervalMode = sAppForbid.scanIntervalMode; + EXPECT_EQ(pScanService->AllowSingleAppScanByInterval(appId, scanIntervalMode), true); + } + + void AllowSingleAppScanByIntervalFail1() + { + int appId = 0; + SingleAppForbid sAppForbid; + sAppForbid.appID = appId; + sAppForbid.scanIntervalMode.scanMode = ScanMode::SCAN_MODE_MAX; + + sAppForbid.fixedScanCount = 1; + sAppForbid.fixedCurrentTime = time(nullptr) - 1; + const int intervalOrCount = 2; + sAppForbid.scanIntervalMode.interval = intervalOrCount; + sAppForbid.scanIntervalMode.count = 1; + sAppForbid.scanIntervalMode.intervalMode = IntervalMode::INTERVAL_FIXED; + + pScanService->appForbidList.push_back(sAppForbid); + + ScanIntervalMode scanIntervalMode = sAppForbid.scanIntervalMode; + EXPECT_EQ(pScanService->AllowSingleAppScanByInterval(appId, scanIntervalMode), false); + } + + void AllowFullAppScanByIntervalSuccess1() + { + int appId = 0; + ScanIntervalMode scanIntervalMode; + EXPECT_EQ(pScanService->AllowFullAppScanByInterval(appId, scanIntervalMode), true); + } + + void AllowFullAppScanByIntervalSuccess2() + { + int appId = 0; + SingleAppForbid sAppForbid; + sAppForbid.appID = appId; + sAppForbid.scanIntervalMode.scanMode = ScanMode::SCAN_MODE_MAX; + pScanService->fullAppForbidList.push_back(sAppForbid); + ScanIntervalMode scanIntervalMode = sAppForbid.scanIntervalMode; + EXPECT_EQ(pScanService->AllowFullAppScanByInterval(appId, scanIntervalMode), true); + } + + void AllowFullAppScanByIntervalFail1() + { + int appId = 0; + SingleAppForbid sAppForbid; + sAppForbid.appID = appId; + sAppForbid.scanIntervalMode.scanMode = ScanMode::SCAN_MODE_MAX; + + sAppForbid.fixedScanCount = 1; + sAppForbid.fixedCurrentTime = time(nullptr) - 1; + const int intervalOrCount = 2; + sAppForbid.scanIntervalMode.interval = intervalOrCount; + sAppForbid.scanIntervalMode.count = 1; + sAppForbid.scanIntervalMode.intervalMode = IntervalMode::INTERVAL_FIXED; + + pScanService->fullAppForbidList.push_back(sAppForbid); + + ScanIntervalMode scanIntervalMode = sAppForbid.scanIntervalMode; + EXPECT_EQ(pScanService->AllowFullAppScanByInterval(appId, scanIntervalMode), false); + } + + void AllowScanByIntervalFixedSuccess1() + { + int fixedScanCount = 0; + time_t fixedScanTime = 0; + int interval = 0; + int count = 0; + bool rlt = pScanService->AllowScanByIntervalFixed(fixedScanCount, fixedScanTime, interval, count); + EXPECT_EQ(rlt, true); + } + + void AllowScanByIntervalFixedSuccess2() + { + int fixedScanCount = 1; + time_t fixedScanTime = 0; + int interval = 0; + int count = 0; + bool rlt = pScanService->AllowScanByIntervalFixed(fixedScanCount, fixedScanTime, interval, count); + EXPECT_EQ(rlt, true); + fixedScanTime = time(nullptr); + interval = 0; + count = 1; + rlt = pScanService->AllowScanByIntervalFixed(fixedScanCount, fixedScanTime, interval, count); + EXPECT_EQ(rlt, true); + } + + void AllowScanByIntervalFixedSuccess3() + { + int fixedScanCount = 1; + time_t fixedScanTime = time(nullptr) - 1; + const int intervalOrCount = 2; + int interval = intervalOrCount; + int count = intervalOrCount; + bool rlt = pScanService->AllowScanByIntervalFixed(fixedScanCount, fixedScanTime, interval, count); + EXPECT_EQ(rlt, true); + } + + void AllowScanByIntervalFixedFail1() + { + int fixedScanCount = 1; + time_t fixedScanTime = time(nullptr) - 1; + const int intervalOrCount = 2; + int interval = intervalOrCount; + int count = 1; + bool rlt = pScanService->AllowScanByIntervalFixed(fixedScanCount, fixedScanTime, interval, count); + EXPECT_EQ(rlt, false); + } + + void AllowScanByIntervalExpSuccess() + { + int expScanCount = 1; + int interval = 1; + const int conutTest = 2; + int count = conutTest; + EXPECT_EQ(pScanService->AllowScanByIntervalExp(expScanCount, interval, count), true); + } + + void AllowScanByIntervalContinueSuccess1() + { + time_t continueScanTime = 0; + int lessThanIntervalCount = 0; + int interval = 0; + int count = 0; + bool rlt = pScanService->AllowScanByIntervalContinue(continueScanTime, lessThanIntervalCount, interval, count); + EXPECT_EQ(rlt, true); + } + + void AllowScanByIntervalContinueSuccess2() + { + const int timeTest = 2; + time_t continueScanTime = time(nullptr) - timeTest; + const int intervalTest = 5; + int interval = intervalTest; + int lessThanIntervalCount = 0; + const int countTest = 2; + int count = countTest; + bool rlt = pScanService->AllowScanByIntervalContinue(continueScanTime, lessThanIntervalCount, interval, count); + EXPECT_EQ(rlt, true); + } + + void AllowScanByIntervalContinueSuccess3() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).Times(AtLeast(0)); + + const int timeTest = 5; + time_t continueScanTime = time(nullptr) - timeTest; + int lessThanIntervalCount = 0; + const int intervalTest = 1; + int interval = intervalTest; + int count = 0; + bool rlt = pScanService->AllowScanByIntervalContinue(continueScanTime, lessThanIntervalCount, interval, count); + EXPECT_EQ(rlt, true); + } + + void AllowScanByIntervalContinueFail1() + { + const int timeTest = 2; + time_t continueScanTime = time(nullptr) - timeTest; + const int intervalTest = 5; + int interval = intervalTest; + int lessThanIntervalCount = 0; + const int countTest = 1; + int count = countTest; + // lessThanIntervalCount = 0 branch. + bool rlt = pScanService->AllowScanByIntervalContinue(continueScanTime, lessThanIntervalCount, interval, count); + EXPECT_EQ(rlt, false); + } + + void AllowScanByIntervalBlocklistSuccess1() + { + int appId = 0; + const int timeTest = 2; + time_t blockListScanTime = time(nullptr) - timeTest; + int lessThanIntervalCount = 0; + int interval = 0; + int count = 0; + pScanService->scanBlocklist.push_back(appId); + pScanService->scanBlocklist.push_back(1); + // blockListScanTime now; branch. + bool rlt = pScanService->AllowScanByIntervalBlocklist(appId, blockListScanTime, lessThanIntervalCount, interval, + count); + EXPECT_EQ(rlt, true); + } + + void AllowScanByIntervalBlocklistSuccess2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).Times(AtLeast(0)); + + int appId = 0; + const int timeTest = 2; + time_t blockListScanTime = 0; + int lessThanIntervalCount = 0; + int interval = time(nullptr) + timeTest; + int count = 0; + // if blockListScanTime 0 branch. + bool rlt = pScanService->AllowScanByIntervalBlocklist(appId, blockListScanTime, lessThanIntervalCount, interval, + count); + EXPECT_EQ(rlt, true); + } + + void AllowScanByIntervalBlocklistSuccess3() + { + int appId = 0; + const int timeTest = 5; + time_t blockListScanTime = time(nullptr) - timeTest; + int lessThanIntervalCount = 0; + const int intervalTest = 10; + int interval = intervalTest; + const int countTest = 2; + int count = countTest; + // if lessThanIntervalCount count branch. + bool rlt = pScanService->AllowScanByIntervalBlocklist(appId, blockListScanTime, lessThanIntervalCount, interval, + count); + EXPECT_EQ(rlt, true); + } + + void AllowScanByIntervalBlocklistFail1() + { + int appId = 0; + const int timeTest = 5; + time_t blockListScanTime = time(nullptr) - timeTest; + int lessThanIntervalCount = 0; + const int intervalTest = 10; + int interval = intervalTest; + int count = 0; + pScanService->scanBlocklist.push_back(appId); + // if find scanBlocklist.begin() branch. + bool rlt = pScanService->AllowScanByIntervalBlocklist(appId, blockListScanTime, lessThanIntervalCount, interval, + count); + EXPECT_EQ(rlt, false); + } + + void AllowScanByIntervalBlocklistFail2() + { + int appId = 0; + const int timeTest = 5; + time_t blockListScanTime = time(nullptr) - timeTest; + int lessThanIntervalCount = 0; + const int intervalTest = 10; + int interval = intervalTest; + int count = 0; + // scanBlocklist (appId) branch. + bool rlt = pScanService->AllowScanByIntervalBlocklist(appId, blockListScanTime, lessThanIntervalCount, interval, + count); + EXPECT_EQ(rlt, false); + } +}; + +HWTEST_F(ScanServiceTest, InitScanServiceSuccess1, TestSize.Level1) +{ + InitScanServiceSuccess1(); +} + +HWTEST_F(ScanServiceTest, InitScanServiceSuccess2, TestSize.Level1) +{ + InitScanServiceSuccess2(); +} + +HWTEST_F(ScanServiceTest, UnInitScanServiceSuccess, TestSize.Level1) +{ + UnInitScanServiceSuccess(); +} + +HWTEST_F(ScanServiceTest, HandleScanStatusReportSuccess1, TestSize.Level1) +{ + HandleScanStatusReportSuccess1(); +} + +HWTEST_F(ScanServiceTest, HandleScanStatusReportSuccess2, TestSize.Level1) +{ + HandleScanStatusReportSuccess2(); +} + +HWTEST_F(ScanServiceTest, HandleScanStatusReportSuccess3, TestSize.Level1) +{ + HandleScanStatusReportSuccess3(); +} + +HWTEST_F(ScanServiceTest, HandleScanStatusReportSuccess4, TestSize.Level1) +{ + HandleScanStatusReportSuccess4(); +} + +HWTEST_F(ScanServiceTest, HandleScanStatusReportSuccess5, TestSize.Level1) +{ + HandleScanStatusReportSuccess5(); +} + +HWTEST_F(ScanServiceTest, HandleScanStatusReportSuccess6, TestSize.Level1) +{ + HandleScanStatusReportSuccess6(); +} + +HWTEST_F(ScanServiceTest, HandleScanStatusReportSuccess7, TestSize.Level1) +{ + HandleScanStatusReportSuccess7(); +} + +HWTEST_F(ScanServiceTest, HandleScanStatusReportFail, TestSize.Level1) +{ + HandleScanStatusReportFail(); +} + +HWTEST_F(ScanServiceTest, HandleInnerEventReportSuccess1, TestSize.Level1) +{ + HandleInnerEventReportSuccess1(); +} + +HWTEST_F(ScanServiceTest, HandleInnerEventReportSuccess2, TestSize.Level1) +{ + HandleInnerEventReportSuccess2(); +} + +HWTEST_F(ScanServiceTest, HandleInnerEventReportSuccess3, TestSize.Level1) +{ + HandleInnerEventReportSuccess3(); +} + +HWTEST_F(ScanServiceTest, HandleInnerEventReportFail, TestSize.Level1) +{ + HandleInnerEventReportFail(); +} + +HWTEST_F(ScanServiceTest, ScanSuccess, TestSize.Level1) +{ + ScanSuccess(); +} + +HWTEST_F(ScanServiceTest, ScanFail, TestSize.Level1) +{ + ScanFail(); +} + +HWTEST_F(ScanServiceTest, ScanWithParamSuccess, TestSize.Level1) +{ + ScanWithParamSuccess(); +} + +HWTEST_F(ScanServiceTest, ScanWithParamFail1, TestSize.Level1) +{ + ScanWithParamFail1(); +} + +HWTEST_F(ScanServiceTest, ScanWithParamFail2, TestSize.Level1) +{ + ScanWithParamFail2(); +} + +HWTEST_F(ScanServiceTest, ScanWithParamFail3, TestSize.Level1) +{ + ScanWithParamFail3(); +} + +HWTEST_F(ScanServiceTest, ScanWithParamFail4, TestSize.Level1) +{ + ScanWithParamFail4(); +} + +HWTEST_F(ScanServiceTest, SingleScanSuccess1, TestSize.Level1) +{ + SingleScanSuccess1(); +} + +HWTEST_F(ScanServiceTest, SingleScanSuccess2, TestSize.Level1) +{ + SingleScanSuccess2(); +} + +HWTEST_F(ScanServiceTest, SingleScanFail1, TestSize.Level1) +{ + SingleScanFail1(); +} + +HWTEST_F(ScanServiceTest, GetBandFreqsSuccess1, TestSize.Level1) +{ + GetBandFreqsSuccess1(); +} + +HWTEST_F(ScanServiceTest, GetBandFreqsSuccess2, TestSize.Level1) +{ + GetBandFreqsSuccess2(); +} + +HWTEST_F(ScanServiceTest, GetBandFreqsSuccess3, TestSize.Level1) +{ + GetBandFreqsSuccess3(); +} + +HWTEST_F(ScanServiceTest, GetBandFreqsSuccess4, TestSize.Level1) +{ + GetBandFreqsSuccess4(); +} + +HWTEST_F(ScanServiceTest, GetBandFreqsSuccess5, TestSize.Level1) +{ + GetBandFreqsSuccess5(); +} + +HWTEST_F(ScanServiceTest, GetBandFreqsSuccess6, TestSize.Level1) +{ + GetBandFreqsSuccess6(); +} + +HWTEST_F(ScanServiceTest, GetBandFreqsFail, TestSize.Level1) +{ + GetBandFreqsFail(); +} + +HWTEST_F(ScanServiceTest, AddScanMessageBodySuccess, TestSize.Level1) +{ + AddScanMessageBodySuccess(); +} + +HWTEST_F(ScanServiceTest, AddScanMessageBodyFail, TestSize.Level1) +{ + AddScanMessageBodyFail(); +} + +HWTEST_F(ScanServiceTest, StoreRequestScanConfigSuccess, TestSize.Level1) +{ + StoreRequestScanConfigSuccess(); +} + +HWTEST_F(ScanServiceTest, HandleCommonScanFailedSuccess1, TestSize.Level1) +{ + HandleCommonScanFailedSuccess1(); +} + +HWTEST_F(ScanServiceTest, HandleCommonScanFailedSuccess2, TestSize.Level1) +{ + HandleCommonScanFailedSuccess2(); +} + +HWTEST_F(ScanServiceTest, HandleCommonScanFailedSuccess3, TestSize.Level1) +{ + HandleCommonScanFailedSuccess3(); +} + +HWTEST_F(ScanServiceTest, HandleCommonScanFailedSuccess4, TestSize.Level1) +{ + HandleCommonScanFailedSuccess4(); +} + +HWTEST_F(ScanServiceTest, HandleCommonScanInfoSuccess1, TestSize.Level1) +{ + HandleCommonScanInfoSuccess1(); +} + +HWTEST_F(ScanServiceTest, HandleCommonScanInfoSuccess2, TestSize.Level1) +{ + HandleCommonScanInfoSuccess2(); +} + +HWTEST_F(ScanServiceTest, HandleCommonScanInfoSuccess3, TestSize.Level1) +{ + HandleCommonScanInfoSuccess3(); +} + +HWTEST_F(ScanServiceTest, StoreFullScanInfoSuccess, TestSize.Level1) +{ + StoreFullScanInfoSuccess(); +} + +HWTEST_F(ScanServiceTest, StoreFullScanInfoFail, TestSize.Level1) +{ + StoreFullScanInfoFail(); +} + +HWTEST_F(ScanServiceTest, StoreUserScanInfoSuccess1, TestSize.Level1) +{ + StoreUserScanInfoSuccess1(); +} + +HWTEST_F(ScanServiceTest, StoreUserScanInfoSuccess2, TestSize.Level1) +{ + StoreUserScanInfoSuccess2(); +} + +HWTEST_F(ScanServiceTest, ReportScanInfosSuccess, TestSize.Level1) +{ + ReportScanInfosSuccess(); +} + +HWTEST_F(ScanServiceTest, BeginPnoScanSuccess1, TestSize.Level1) +{ + BeginPnoScanSuccess1(); +} + +HWTEST_F(ScanServiceTest, BeginPnoScanFail1, TestSize.Level1) +{ + BeginPnoScanFail1(); +} + +HWTEST_F(ScanServiceTest, BeginPnoScanFail2, TestSize.Level1) +{ + BeginPnoScanFail2(); +} + +HWTEST_F(ScanServiceTest, BeginPnoScanFail3, TestSize.Level1) +{ + BeginPnoScanFail3(); +} + +HWTEST_F(ScanServiceTest, PnoScanSuccess, TestSize.Level1) +{ + PnoScanSuccess(); +} + +HWTEST_F(ScanServiceTest, AddPnoScanMessageBodySuccess, TestSize.Level1) +{ + AddPnoScanMessageBodySuccess(); +} + +HWTEST_F(ScanServiceTest, AddPnoScanMessageBodyFail, TestSize.Level1) +{ + AddPnoScanMessageBodyFail(); +} + +HWTEST_F(ScanServiceTest, HandlePnoScanInfoSuccess, TestSize.Level1) +{ + HandlePnoScanInfoSuccess(); +} + +HWTEST_F(ScanServiceTest, EndPnoScanSuccess, TestSize.Level1) +{ + EndPnoScanSuccess(); +} + +HWTEST_F(ScanServiceTest, EndPnoScanFail, TestSize.Level1) +{ + EndPnoScanFail(); +} + +HWTEST_F(ScanServiceTest, HandleScreenStatusChangedSuccess, TestSize.Level1) +{ + HandleScreenStatusChangedSuccess(); +} + +HWTEST_F(ScanServiceTest, HandleStaStatusChangedSuccess1, TestSize.Level1) +{ + HandleStaStatusChangedSuccess1(); +} + +HWTEST_F(ScanServiceTest, HandleStaStatusChangedSuccess2, TestSize.Level1) +{ + HandleStaStatusChangedSuccess2(); +} + +HWTEST_F(ScanServiceTest, HandleStaStatusChangedFail, TestSize.Level1) +{ + HandleStaStatusChangedFail(); +} + +HWTEST_F(ScanServiceTest, HandleCustomStatusChangedSuccess1, TestSize.Level1) +{ + HandleCustomStatusChangedSuccess1(); +} + +HWTEST_F(ScanServiceTest, HandleCustomStatusChangedSuccess2, TestSize.Level1) +{ + HandleCustomStatusChangedSuccess2(); +} + +HWTEST_F(ScanServiceTest, SystemScanProcessSuccess1, TestSize.Level1) +{ + SystemScanProcessSuccess1(); +} + +HWTEST_F(ScanServiceTest, SystemScanProcessSuccess2, TestSize.Level1) +{ + SystemScanProcessSuccess2(); +} + +HWTEST_F(ScanServiceTest, StopSystemScanSuccess, TestSize.Level1) +{ + StopSystemScanSuccess(); +} + +HWTEST_F(ScanServiceTest, StartSystemTimerScanSuccess, TestSize.Level1) +{ + StartSystemTimerScanSuccess(); +} + +HWTEST_F(ScanServiceTest, HandleSystemScanTimeoutSuccess, TestSize.Level1) +{ + HandleSystemScanTimeoutSuccess(); +} + +HWTEST_F(ScanServiceTest, DisconnectedTimerScanSuccess, TestSize.Level1) +{ + DisconnectedTimerScanSuccess(); +} + +HWTEST_F(ScanServiceTest, HandleDisconnectedScanTimeoutSuccess, TestSize.Level1) +{ + HandleDisconnectedScanTimeoutSuccess(); +} + +HWTEST_F(ScanServiceTest, RestartPnoScanTimeOutSuccess, TestSize.Level1) +{ + RestartPnoScanTimeOutSuccess(); +} + +HWTEST_F(ScanServiceTest, GetScanControlInfoSuccess, TestSize.Level1) +{ + GetScanControlInfoSuccess(); +} + +HWTEST_F(ScanServiceTest, GetScanControlInfoFail, TestSize.Level1) +{ + GetScanControlInfoFail(); +} + +HWTEST_F(ScanServiceTest, GetScreenStateSuccess, TestSize.Level1) +{ + GetScreenStateSuccess(); +} + +HWTEST_F(ScanServiceTest, SetOperateAppModeSuccess, TestSize.Level1) +{ + SetOperateAppModeSuccess(); +} + +HWTEST_F(ScanServiceTest, GetOperateAppModeSuccess1, TestSize.Level1) +{ + GetOperateAppModeSuccess1(); +} + +HWTEST_F(ScanServiceTest, GetOperateAppModeSuccess2, TestSize.Level1) +{ + GetOperateAppModeSuccess2(); +} + +HWTEST_F(ScanServiceTest, GetOperateAppModeSuccess3, TestSize.Level1) +{ + GetOperateAppModeSuccess3(); +} + +HWTEST_F(ScanServiceTest, GetOperateAppModeSuccess4, TestSize.Level1) +{ + GetOperateAppModeSuccess4(); +} + +HWTEST_F(ScanServiceTest, GetOperateAppModeFail, TestSize.Level1) +{ + GetOperateAppModeFail(); +} + +HWTEST_F(ScanServiceTest, AllowExternScanSuccess, TestSize.Level1) +{ + AllowExternScanSuccess(); +} + +HWTEST_F(ScanServiceTest, AllowExternScanFail1, TestSize.Level1) +{ + AllowExternScanFail1(); +} + +HWTEST_F(ScanServiceTest, AllowSystemTimerScanSuccess, TestSize.Level1) +{ + AllowSystemTimerScanSuccess(); +} + +HWTEST_F(ScanServiceTest, AllowPnoScanSuccess, TestSize.Level1) +{ + AllowPnoScanSuccess(); +} + +HWTEST_F(ScanServiceTest, AllowExternScanByForbidSuccess1, TestSize.Level1) +{ + AllowExternScanByForbidSuccess1(); +} + +HWTEST_F(ScanServiceTest, AllowExternScanByIntervaluccess, TestSize.Level1) +{ + AllowExternScanByIntervaluccess(); +} + +HWTEST_F(ScanServiceTest, GetStaSceneSuccess1, TestSize.Level1) +{ + GetStaSceneSuccess1(); +} + +HWTEST_F(ScanServiceTest, GetStaSceneSuccess2, TestSize.Level1) +{ + GetStaSceneSuccess2(); +} + +HWTEST_F(ScanServiceTest, GetStaSceneSuccess3, TestSize.Level1) +{ + GetStaSceneSuccess3(); +} + +HWTEST_F(ScanServiceTest, GetStaSceneSuccess4, TestSize.Level1) +{ + GetStaSceneSuccess4(); +} + +HWTEST_F(ScanServiceTest, GetStaSceneSuccess5, TestSize.Level1) +{ + GetStaSceneSuccess5(); +} + +HWTEST_F(ScanServiceTest, GetStaSceneSuccess6, TestSize.Level1) +{ + GetStaSceneSuccess6(); +} + +HWTEST_F(ScanServiceTest, GetStaSceneFail, TestSize.Level1) +{ + GetStaSceneFail(); +} + +HWTEST_F(ScanServiceTest, IsExternScanningSuccess, TestSize.Level1) +{ + IsExternScanningSuccess(); +} + +HWTEST_F(ScanServiceTest, IsExternScanningFail, TestSize.Level1) +{ + IsExternScanningFail(); +} + +HWTEST_F(ScanServiceTest, GetAllowBandFreqsControlInfoSuccess, TestSize.Level1) +{ + GetAllowBandFreqsControlInfoSuccess(); +} + +HWTEST_F(ScanServiceTest, ConvertBandNotAllow24GSuccess1, TestSize.Level1) +{ + ConvertBandNotAllow24GSuccess1(); +} + +HWTEST_F(ScanServiceTest, ConvertBandNotAllow24GSuccess2, TestSize.Level1) +{ + ConvertBandNotAllow24GSuccess2(); +} + +HWTEST_F(ScanServiceTest, ConvertBandNotAllow24GSuccess3, TestSize.Level1) +{ + ConvertBandNotAllow24GSuccess3(); +} + +HWTEST_F(ScanServiceTest, ConvertBandNotAllow24GSuccess4, TestSize.Level1) +{ + ConvertBandNotAllow24GSuccess4(); +} + +HWTEST_F(ScanServiceTest, ConvertBandNotAllow24GFail, TestSize.Level1) +{ + ConvertBandNotAllow24GFail(); +} + +HWTEST_F(ScanServiceTest, ConvertBandNotAllow5GSuccess, TestSize.Level1) +{ + ConvertBandNotAllow5GSuccess(); +} + +HWTEST_F(ScanServiceTest, ConvertBandNotAllow5GFail, TestSize.Level1) +{ + ConvertBandNotAllow5GFail(); +} + +HWTEST_F(ScanServiceTest, Delete24GhzFreqsSuccess, TestSize.Level1) +{ + Delete24GhzFreqsSuccess(); +} + +HWTEST_F(ScanServiceTest, Delete5GhzFreqsSuccess, TestSize.Level1) +{ + Delete5GhzFreqsSuccess(); +} + +HWTEST_F(ScanServiceTest, GetSavedNetworkSsidListSuccess, TestSize.Level1) +{ + GetSavedNetworkSsidListSuccess(); +} + +HWTEST_F(ScanServiceTest, GetSavedNetworkSsidListFail, TestSize.Level1) +{ + GetSavedNetworkSsidListFail(); +} + +HWTEST_F(ScanServiceTest, GetHiddenNetworkSsidListSuccess, TestSize.Level1) +{ + GetHiddenNetworkSsidListSuccess1(); +} + +HWTEST_F(ScanServiceTest, GetHiddenNetworkSsidListSuccess2, TestSize.Level1) +{ + GetHiddenNetworkSsidListSuccess2(); +} + +HWTEST_F(ScanServiceTest, GetHiddenNetworkSsidListFail, TestSize.Level1) +{ + GetHiddenNetworkSsidListFail(); +} + +HWTEST_F(ScanServiceTest, ClearScanControlValueSuccess, TestSize.Level1) +{ + ClearScanControlValueSuccess(); +} + +HWTEST_F(ScanServiceTest, SetStaCurrentTimeSuccess, TestSize.Level1) +{ + SetStaCurrentTimeSuccess(); +} + +HWTEST_F(ScanServiceTest, AllowScanDuringScanningSuccess, TestSize.Level1) +{ + AllowScanDuringScanningSuccess(); +} + +HWTEST_F(ScanServiceTest, AllowScanDuringScreenOffSuccess, TestSize.Level1) +{ + AllowScanDuringScreenOffSuccess(); +} + +HWTEST_F(ScanServiceTest, AllowScanDuringStaSceneSuccess, TestSize.Level1) +{ + AllowScanDuringStaSceneSuccess1(); +} + +HWTEST_F(ScanServiceTest, AllowScanDuringCustomSceneSuccess, TestSize.Level1) +{ + AllowScanDuringCustomSceneSuccess(); +} + +HWTEST_F(ScanServiceTest, AllowExternScanByIntervalMode, TestSize.Level1) +{ + AllowExternScanByIntervalMode(); +} + +HWTEST_F(ScanServiceTest, AllowExternScanByCustomSceneSuccess, TestSize.Level1) +{ + AllowExternScanByCustomSceneSuccess(); +} + +HWTEST_F(ScanServiceTest, PnoScanByIntervalSuccess1, TestSize.Level1) +{ + PnoScanByIntervalSuccess1(); +} + +HWTEST_F(ScanServiceTest, PnoScanByIntervalSuccess2, TestSize.Level1) +{ + PnoScanByIntervalSuccess2(); +} + +HWTEST_F(ScanServiceTest, PnoScanByIntervalSuccess3, TestSize.Level1) +{ + PnoScanByIntervalSuccess3(); +} + +HWTEST_F(ScanServiceTest, PnoScanByIntervalFail1, TestSize.Level1) +{ + PnoScanByIntervalFail1(); +} + +HWTEST_F(ScanServiceTest, SystemScanByIntervalSuccess, TestSize.Level1) +{ + SystemScanByIntervalSuccess(); +} + +HWTEST_F(ScanServiceTest, ExternScanByIntervalSuccess1, TestSize.Level1) +{ + ExternScanByIntervalSuccess1(); +} + +HWTEST_F(ScanServiceTest, ExternScanByIntervalSuccess2, TestSize.Level1) +{ + ExternScanByIntervalSuccess2(); +} + +HWTEST_F(ScanServiceTest, ExternScanByIntervalSuccess3, TestSize.Level1) +{ + ExternScanByIntervalSuccess3(); +} + +HWTEST_F(ScanServiceTest, ExternScanByIntervalSuccess4, TestSize.Level1) +{ + ExternScanByIntervalSuccess4(); +} + +HWTEST_F(ScanServiceTest, ExternScanByIntervalSuccess5, TestSize.Level1) +{ + ExternScanByIntervalSuccess5(); +} + +HWTEST_F(ScanServiceTest, AllowSingleAppScanByIntervalSuccess1, TestSize.Level1) +{ + AllowSingleAppScanByIntervalSuccess1(); +} + +HWTEST_F(ScanServiceTest, AllowSingleAppScanByIntervalSuccess2, TestSize.Level1) +{ + AllowSingleAppScanByIntervalSuccess2(); +} + +HWTEST_F(ScanServiceTest, AllowSingleAppScanByIntervalFail1, TestSize.Level1) +{ + AllowSingleAppScanByIntervalFail1(); +} + +HWTEST_F(ScanServiceTest, AllowFullAppScanByIntervalSuccess1, TestSize.Level1) +{ + AllowFullAppScanByIntervalSuccess1(); +} + +HWTEST_F(ScanServiceTest, AllowFullAppScanByIntervalSuccess2, TestSize.Level1) +{ + AllowFullAppScanByIntervalSuccess2(); +} + +HWTEST_F(ScanServiceTest, AllowFullAppScanByIntervalFail1, TestSize.Level1) +{ + AllowFullAppScanByIntervalFail1(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalFixedSuccess1, TestSize.Level1) +{ + AllowScanByIntervalFixedSuccess1(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalFixedSuccess2, TestSize.Level1) +{ + AllowScanByIntervalFixedSuccess2(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalFixedSuccess3, TestSize.Level1) +{ + AllowScanByIntervalFixedSuccess3(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalFixedFail1, TestSize.Level1) +{ + AllowScanByIntervalFixedFail1(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalExpSuccess, TestSize.Level1) +{ + AllowScanByIntervalExpSuccess(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalContinueSuccess1, TestSize.Level1) +{ + AllowScanByIntervalContinueSuccess1(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalContinueSuccess2, TestSize.Level1) +{ + AllowScanByIntervalContinueSuccess2(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalContinueSuccess3, TestSize.Level1) +{ + AllowScanByIntervalContinueSuccess3(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalContinueFail1, TestSize.Level1) +{ + AllowScanByIntervalContinueFail1(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalBlocklistSuccess1, TestSize.Level1) +{ + AllowScanByIntervalBlocklistSuccess1(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalBlocklistSuccess2, TestSize.Level1) +{ + AllowScanByIntervalBlocklistSuccess2(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalBlocklistSuccess3, TestSize.Level1) +{ + AllowScanByIntervalBlocklistSuccess3(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalBlocklistFail1, TestSize.Level1) +{ + AllowScanByIntervalBlocklistFail1(); +} + +HWTEST_F(ScanServiceTest, AllowScanByIntervalBlocklistFail2, TestSize.Level1) +{ + AllowScanByIntervalBlocklistFail2(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine_test.cpp new file mode 100644 index 000000000..bdaced736 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine_test.cpp @@ -0,0 +1,1946 @@ +/* + * 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 "mock_wifi_manager.h" +#include "mock_wifi_settings.h" +#include "mock_wifi_sta_hal_interface.h" +#include "mock_scan_service.h" +#include "scan_state_machine.h" + +#include +#include +#include +#include + +using ::testing::_; +using ::testing::AtLeast; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::StrEq; +using ::testing::TypedEq; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +constexpr int FREQ_2_DOT_4_GHZ_VALUE = 2410; +constexpr int FREQ_5_GHZ_VALUE = 5010; + +class ScanStateMachineTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + void SetUp() override + { + EXPECT_CALL(WifiSettings::GetInstance(), GetSupportHwPnoFlag()).Times(AtLeast(0)); + pScanStateMachine = std::make_unique(); + pScanStateMachine->InitScanStateMachine(); + pScanService = std::make_unique(); + pScanStateMachine->EnrollScanStatusListener( + std::bind(&MockScanService::HandleScanStatusReport, pScanService.get(), std::placeholders::_1)); + } + void TearDown() override + { + pScanStateMachine.reset(); + pScanService.reset(); + } + + std::unique_ptr pScanService; + std::unique_ptr pScanStateMachine; + +public: + void InitGoInStateTest() + { + pScanStateMachine->initState->GoInState(); + } + + void InitGoOutStateTest() + { + pScanStateMachine->initState->GoOutState(); + } + + void InitExeMsgSuccess1() + { + InternalMessage msg; + msg.SetMessageName(CMD_SCAN_PREPARE); + pScanStateMachine->initState->ExecuteStateMsg(&msg); + } + + void InitExeMsgSuccess2() + { + InternalMessage msg; + msg.SetMessageName(CMD_SCAN_FINISH); + pScanStateMachine->initState->ExecuteStateMsg(&msg); + } + + void InitExeMsgSuccess3() + { + InternalMessage msg; + msg.SetMessageName(CMD_START_COMMON_SCAN); + pScanStateMachine->initState->ExecuteStateMsg(&msg); + } + + void InitExeMsgSuccess4() + { + InternalMessage msg; + msg.SetMessageName(CMD_START_PNO_SCAN); + pScanStateMachine->initState->ExecuteStateMsg(&msg); + } + + void InitExeMsgSuccess5() + { + InternalMessage msg; + msg.SetMessageName(CMD_STOP_PNO_SCAN); + pScanStateMachine->initState->ExecuteStateMsg(&msg); + } + + void InitExeMsgSuccess6() + { + InternalMessage msg; + msg.SetMessageName(HARDWARE_LOAD_EVENT); + pScanStateMachine->initState->ExecuteStateMsg(&msg); + } + + void InitExeMsgSuccess7() + { + InternalMessage msg; + msg.SetMessageName(HARDWARE_UNLOAD_EVENT); + pScanStateMachine->initState->ExecuteStateMsg(&msg); + } + + void InitExeMsgSuccess8() + { + InternalMessage msg; + msg.SetMessageName(CMD_STOP_COMMON_SCAN); + pScanStateMachine->initState->ExecuteStateMsg(&msg); + } + + void InitExeMsgSuccess9() + { + InternalMessage msg; + msg.SetMessageName(SYSTEM_SCAN_TIMER); + pScanStateMachine->initState->ExecuteStateMsg(&msg); + } + + void InitExeMsgSuccess10() + { + InternalMessage msg; + msg.SetMessageName(SCAN_INNER_EVENT_INVALID); + pScanStateMachine->initState->ExecuteStateMsg(&msg); + } + + void InitExeMsgFail() + { + pScanStateMachine->initState->ExecuteStateMsg(nullptr); + } + + void LoadDriverTest() + { + pScanStateMachine->initState->LoadDriver(); + } + + void UnLoadDriverTest() + { + pScanStateMachine->initState->UnLoadDriver(); + } + + void HardwareReadyGoInStateTest() + { + pScanStateMachine->hardwareReadyState->GoInState(); + } + + void HardwareReadyGoOutStateMsgTest() + { + pScanStateMachine->hardwareReadyState->GoOutState(); + } + + void HardwareReadyExeMsgSuccess1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + msg.SetMessageName(CMD_START_COMMON_SCAN); + pScanStateMachine->hardwareReadyState->ExecuteStateMsg(&msg); + } + + void HardwareReadyExeMsgSuccess2() + { + InternalMessage msg; + msg.SetMessageName(CMD_START_PNO_SCAN); + pScanStateMachine->hardwareReadyState->ExecuteStateMsg(&msg); + } + + void HardwareReadyExeMsgFail() + { + pScanStateMachine->hardwareReadyState->ExecuteStateMsg(nullptr); + } + + void CommonScanGoInStateTest() + { + pScanStateMachine->commonScanState->GoInState(); + } + + void CommonScanGoOutStateTest() + { + pScanStateMachine->commonScanState->GoOutState(); + } + + void CommonScanExeMsgSuccess() + { + InternalMessage msg; + msg.SetMessageName(CMD_STOP_COMMON_SCAN); + pScanStateMachine->commonScanState->ExecuteStateMsg(&msg); + } + + void CommonScanExeMsgFail() + { + pScanStateMachine->commonScanState->ExecuteStateMsg(nullptr); + } + + void CommonScanUnworkedGoInStateTest() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanStateMachine->commonScanUnworkedState->GoInState(); + } + + void CommonScanUnworkedGoOutStateTest() + { + pScanStateMachine->commonScanUnworkedState->GoOutState(); + } + + void CommonScanUnworkedExeMsgSuccess1() + { + InternalMessage msg; + msg.SetMessageName(CMD_START_COMMON_SCAN); + pScanStateMachine->commonScanUnworkedState->ExecuteStateMsg(&msg); + } + + void CommonScanUnworkedExeMsgSuccess2() + { + InternalMessage msg; + msg.SetMessageName(CMD_START_PNO_SCAN); + pScanStateMachine->commonScanUnworkedState->ExecuteStateMsg(&msg); + } + + void CommonScanUnworkedExeMsgSuccess3() + { + InternalMessage msg; + msg.SetMessageName(CMD_SCAN_PREPARE); + pScanStateMachine->commonScanUnworkedState->ExecuteStateMsg(&msg); + } + + void CommonScanUnworkedExeMsgFail() + { + pScanStateMachine->commonScanUnworkedState->ExecuteStateMsg(nullptr); + } + + void CommonScanningGoInStateTest() + { + pScanStateMachine->commonScanningState->GoInState(); + } + + void CommonScanningGoOutStateTest() + { + pScanStateMachine->commonScanningState->GoOutState(); + } + + void CommonScanningExeMsgSuccess1() + { + InternalMessage msg; + msg.SetMessageName(CMD_START_COMMON_SCAN); + pScanStateMachine->commonScanningState->ExecuteStateMsg(&msg); + } + + void CommonScanningExeMsgSuccess2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), QueryScanInfos(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + msg.SetMessageName(SCAN_RESULT_EVENT); + pScanStateMachine->commonScanningState->ExecuteStateMsg(&msg); + } + + void CommonScanningExeMsgSuccess3() + { + InternalMessage msg; + msg.SetMessageName(SCAN_FAILED_EVENT); + pScanStateMachine->commonScanningState->ExecuteStateMsg(&msg); + } + + void CommonScanningExeMsgSuccess4() + { + InternalMessage msg; + msg.SetMessageName(WAIT_SCAN_RESULT_TIMER); + pScanStateMachine->commonScanningState->ExecuteStateMsg(&msg); + } + + void CommonScanningExeMsgSuccess5() + { + InternalMessage msg; + msg.SetMessageName(CMD_START_PNO_SCAN); + pScanStateMachine->commonScanningState->ExecuteStateMsg(&msg); + } + + void CommonScanningExeMsgSuccess6() + { + InternalMessage msg; + msg.SetMessageName(CMD_SCAN_FINISH); + pScanStateMachine->commonScanningState->ExecuteStateMsg(&msg); + } + + void CommonScanningExeMsgFail() + { + pScanStateMachine->commonScanningState->ExecuteStateMsg(nullptr); + } + + void PnoScanGoInStateTest() + { + pScanStateMachine->pnoScanState->GoInState(); + } + + void PnoScanGoOutStateTest() + { + pScanStateMachine->pnoScanState->GoOutState(); + } + + void PnoScanExeMsgSuccess() + { + InternalMessage msg; + pScanStateMachine->pnoScanState->ExecuteStateMsg(&msg); + } + + void PnoScanExeMsgFail() + { + pScanStateMachine->pnoScanState->ExecuteStateMsg(nullptr); + } + + void PnoScanHardwareGoInStateTest() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartPnoScan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanStateMachine->pnoScanHardwareState->GoInState(); + } + + void PnoScanHardwareGoOutStateTest() + { + pScanStateMachine->pnoScanHardwareState->GoOutState(); + } + + void PnoScanHardwareExeMsgSuccess1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartPnoScan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + msg.SetMessageName(CMD_START_PNO_SCAN); + pScanStateMachine->pnoScanHardwareState->ExecuteStateMsg(&msg); + } + + void PnoScanHardwareExeMsgSuccess2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + msg.SetMessageName(CMD_STOP_PNO_SCAN); + pScanStateMachine->pnoScanHardwareState->ExecuteStateMsg(&msg); + } + + void PnoScanHardwareExeMsgSuccess3() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartPnoScan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + msg.SetMessageName(CMD_RESTART_PNO_SCAN); + pScanStateMachine->pnoScanHardwareState->ExecuteStateMsg(&msg); + } + + void PnoScanHardwareExeMsgSuccess4() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), QueryScanInfos(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + msg.SetMessageName(PNO_SCAN_RESULT_EVENT); + pScanStateMachine->pnoScanHardwareState->ExecuteStateMsg(&msg); + } + + void PnoScanHardwareExeMsgSuccess5() + { + InternalMessage msg; + msg.SetMessageName(CMD_START_COMMON_SCAN); + pScanStateMachine->pnoScanHardwareState->ExecuteStateMsg(&msg); + } + + void PnoScanHardwareExeMsgSuccess6() + { + InternalMessage msg; + msg.SetMessageName(CMD_SCAN_FINISH); + pScanStateMachine->pnoScanHardwareState->ExecuteStateMsg(&msg); + } + + void PnoScanHardwareExeMsgFail() + { + pScanStateMachine->pnoScanHardwareState->ExecuteStateMsg(nullptr); + } + + void CommonScanAfterPnoGoInStateTest() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanStateMachine->commonScanAfterPnoState->GoInState(); + } + + void CommonScanAfterPnoGoOutStateTest() + { + pScanStateMachine->commonScanAfterPnoState->GoOutState(); + } + + void CommonScanAfterPnoExeMsgSuccess1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), QueryScanInfos(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + msg.SetMessageName(SCAN_RESULT_EVENT); + pScanStateMachine->commonScanAfterPnoState->ExecuteStateMsg(&msg); + } + + void CommonScanAfterPnoExeMsgSuccess2() + { + InternalMessage msg; + msg.SetMessageName(SCAN_FAILED_EVENT); + pScanStateMachine->commonScanAfterPnoState->ExecuteStateMsg(&msg); + } + + void CommonScanAfterPnoExeMsgSuccess3() + { + InternalMessage msg; + msg.SetMessageName(CMD_START_PNO_SCAN); + pScanStateMachine->commonScanAfterPnoState->ExecuteStateMsg(&msg); + } + + void CommonScanAfterPnoExeMsgSuccess4() + { + InternalMessage msg; + msg.SetMessageName(CMD_START_COMMON_SCAN); + pScanStateMachine->commonScanAfterPnoState->ExecuteStateMsg(&msg); + } + + void CommonScanAfterPnoExeMsgSuccess5() + { + InternalMessage msg; + msg.SetMessageName(CMD_RESTART_PNO_SCAN); + pScanStateMachine->commonScanAfterPnoState->ExecuteStateMsg(&msg); + } + + void CommonScanAfterPnoExeMsgSuccess6() + { + InternalMessage msg; + msg.SetMessageName(CMD_SCAN_FINISH); + pScanStateMachine->commonScanAfterPnoState->ExecuteStateMsg(&msg); + } + + void CommonScanAfterPnoExeMsgFail() + { + pScanStateMachine->commonScanAfterPnoState->ExecuteStateMsg(nullptr); + } + + void PnoScanSoftwareGoInStateTest() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanStateMachine->pnoScanSoftwareState->GoInState(); + } + + void PnoScanSoftwareGoOutStateTest() + { + pScanStateMachine->pnoScanSoftwareState->GoOutState(); + } + + void PnoScanSoftwareExeMsgSuccess1() + { + InternalMessage msg; + msg.SetMessageName(CMD_STOP_PNO_SCAN); + pScanStateMachine->pnoScanSoftwareState->ExecuteStateMsg(&msg); + } + + void PnoScanSoftwareExeMsgSuccess2() + { + InternalMessage msg; + msg.SetMessageName(CMD_SCAN_FINISH); + pScanStateMachine->pnoScanSoftwareState->ExecuteStateMsg(&msg); + } + + void PnoScanSoftwareExeMsgFail() + { + pScanStateMachine->pnoScanSoftwareState->ExecuteStateMsg(nullptr); + } + + void PnoSwScanFreeGoInStateTest() + { + pScanStateMachine->pnoSwScanFreeState->GoInState(); + } + + void PnoSwScanFreeGoOutStateTest() + { + pScanStateMachine->pnoSwScanFreeState->GoOutState(); + } + + void PnoSwScanFreeExeMsgSuccess1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + msg.SetMessageName(CMD_START_PNO_SCAN); + pScanStateMachine->pnoSwScanFreeState->ExecuteStateMsg(&msg); + } + + void PnoSwScanFreeExeMsgSuccess2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + msg.SetMessageName(CMD_RESTART_PNO_SCAN); + pScanStateMachine->pnoSwScanFreeState->ExecuteStateMsg(&msg); + } + + void PnoSwScanFreeExeMsgSuccess3() + { + InternalMessage msg; + msg.SetMessageName(CMD_START_COMMON_SCAN); + pScanStateMachine->pnoSwScanFreeState->ExecuteStateMsg(&msg); + } + + void PnoSwScanFreeExeMsgSuccess4() + { + InternalMessage msg; + msg.SetMessageName(SOFTWARE_PNO_SCAN_TIMER); + pScanStateMachine->pnoSwScanFreeState->ExecuteStateMsg(&msg); + } + + void PnoSwScanFreeExeMsgSuccess5() + { + InternalMessage msg; + msg.SetMessageName(CMD_SCAN_FINISH); + pScanStateMachine->pnoSwScanFreeState->ExecuteStateMsg(&msg); + } + + void PnoSwScanFreeExeMsgFail() + { + pScanStateMachine->pnoSwScanFreeState->ExecuteStateMsg(nullptr); + } + + void PnoSwScanningGoInStateTest() + { + pScanStateMachine->pnoSwScanningState->GoInState(); + } + + void PnoSwScanningGoOutStateTest() + { + pScanStateMachine->pnoSwScanningState->GoOutState(); + } + + void PnoSwScanningExeMsgSuccess1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), QueryScanInfos(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + msg.SetMessageName(SCAN_RESULT_EVENT); + pScanStateMachine->pnoSwScanningState->ExecuteStateMsg(&msg); + } + + void PnoSwScanningExeMsgSuccess2() + { + InternalMessage msg; + msg.SetMessageName(SCAN_FAILED_EVENT); + pScanStateMachine->pnoSwScanningState->ExecuteStateMsg(&msg); + } + + void PnoSwScanningExeMsgSuccess3() + { + InternalMessage msg; + msg.SetMessageName(WAIT_SCAN_RESULT_TIMER); + pScanStateMachine->pnoSwScanningState->ExecuteStateMsg(&msg); + } + + void PnoSwScanningExeMsgSuccess4() + { + InternalMessage msg; + msg.SetMessageName(CMD_START_PNO_SCAN); + pScanStateMachine->pnoSwScanningState->ExecuteStateMsg(&msg); + } + + void PnoSwScanningExeMsgSuccess5() + { + InternalMessage msg; + msg.SetMessageName(CMD_RESTART_PNO_SCAN); + pScanStateMachine->pnoSwScanningState->ExecuteStateMsg(&msg); + } + + void PnoSwScanningExeMsgSuccess6() + { + InternalMessage msg; + msg.SetMessageName(SOFTWARE_PNO_SCAN_TIMER); + pScanStateMachine->pnoSwScanningState->ExecuteStateMsg(&msg); + } + + void PnoSwScanningExeMsgSuccess7() + { + InternalMessage msg; + msg.SetMessageName(SCAN_INNER_EVENT_INVALID); + pScanStateMachine->pnoSwScanningState->ExecuteStateMsg(&msg); + } + + void PnoSwScanningExeMsgFail() + { + pScanStateMachine->pnoSwScanningState->ExecuteStateMsg(nullptr); + } + + void CommonScanRequestProcessTest() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + pScanStateMachine->CommonScanRequestProcess(&msg); + } + + void GetCommonScanRequestInfoTest1() + { + InternalMessage interMessage; + int requestIndex = 0; + InterScanConfig scanConfig; + pScanStateMachine->GetCommonScanRequestInfo(&interMessage, requestIndex, scanConfig); + } + + void GetCommonScanRequestInfoTest2() + { + int requestIndex = 0; + InterScanConfig scanConfig; + pScanStateMachine->GetCommonScanRequestInfo(nullptr, requestIndex, scanConfig); + } + + void GetCommonScanConfigSuccess() + { + InternalMessage msg; + msg.AddIntMessageBody(1); + msg.AddStringMessageBody("hmwifi1"); + msg.AddIntMessageBody(1); + msg.AddStringMessageBody("hmwifi2"); + InterScanConfig scanConfig; + pScanStateMachine->GetCommonScanConfig(&msg, scanConfig); + } + + void GetCommonScanConfigFail1() + { + InterScanConfig scanConfig; + pScanStateMachine->GetCommonScanConfig(nullptr, scanConfig); + } + + void GetCommonScanConfigFail2() + { + InternalMessage msg; + msg.AddIntMessageBody(1); + InterScanConfig scanConfig; + pScanStateMachine->GetCommonScanConfig(&msg, scanConfig); + } + + void GetCommonScanConfigFail3() + { + InternalMessage msg; + msg.AddIntMessageBody(1); + msg.AddStringMessageBody("hmwifi1"); + msg.AddIntMessageBody(1); + InterScanConfig scanConfig; + pScanStateMachine->GetCommonScanConfig(&msg, scanConfig); + } + + void StartNewCommonScanTest1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InterScanConfig interScanConfig; + pScanStateMachine->waitingScans.emplace(0, interScanConfig); + pScanStateMachine->StartNewCommonScan(); + } + + void StartNewCommonScanTest2() + { + pScanStateMachine->StartNewCommonScan(); + } + + void ClearRunningScanSettingsTest() + { + pScanStateMachine->ClearRunningScanSettings(); + } + + void StartSingleCommonScanSuccess() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + WifiScanParam scanParam; + pScanStateMachine->StartSingleCommonScan(scanParam); + } + + void StartSingleCommonScanFail() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + WifiScanParam scanParam; + pScanStateMachine->StartSingleCommonScan(scanParam); + } + + void CommonScanWhenRunningSuccess() + { + InternalMessage msg; + pScanStateMachine->CommonScanWhenRunning(&msg); + } + + void CommonScanWhenRunningFail() + { + pScanStateMachine->CommonScanWhenRunning(nullptr); + } + + void ActiveCoverNewScanSuccess() + { + pScanStateMachine->runningFullScanFlag = true; + InterScanConfig interScanConfig; + interScanConfig.scanStyle = SCAN_TYPE_HIGH_ACCURACY; + pScanStateMachine->ActiveCoverNewScan(interScanConfig); + } + + void ActiveCoverNewScanFail() + { + pScanStateMachine->runningFullScanFlag = true; + InterScanConfig interScanConfig; + interScanConfig.scanStyle = SCAN_TYPE_INVALID; + pScanStateMachine->ActiveCoverNewScan(interScanConfig); + } + + void CommonScanInfoProcessTest() + { + pScanStateMachine->CommonScanInfoProcess(); + } + + void ReportStatusChangeTest() + { + ScanStatus status = SCAN_STARTED_STATUS; + pScanStateMachine->ReportStatusChange(status); + } + + void ReportScanInnerEventTest() + { + ScanInnerEventType innerEvent = WAIT_SCAN_RESULT_TIMER; + pScanStateMachine->ReportScanInnerEvent(innerEvent); + } + + void ReportCommonScanFailedTest() + { + pScanStateMachine->ReportCommonScanFailed(0); + } + + void ReportCommonScanFailedAndClearTest1() + { + pScanStateMachine->ReportCommonScanFailedAndClear(true); + } + + void ReportCommonScanFailedAndClearTest2() + { + pScanStateMachine->ReportCommonScanFailedAndClear(false); + } + + void GetRunningIndexListTest() + { + InterScanConfig interScanConfig; + pScanStateMachine->runningScans.emplace(0, interScanConfig); + std::vector runningIndexList; + pScanStateMachine->GetRunningIndexList(runningIndexList); + } + + void GetWaitingIndexListTest() + { + InterScanConfig interScanConfig; + pScanStateMachine->waitingScans.emplace(0, interScanConfig); + std::vector waitingIndexList; + pScanStateMachine->GetRunningIndexList(waitingIndexList); + } + + void VerifyScanStyleSuccess() + { + int scanStyle = SCAN_TYPE_HIGH_ACCURACY; + EXPECT_EQ(true, pScanStateMachine->VerifyScanStyle(scanStyle)); + } + + void VerifyScanStyleFail() + { + int scanStyle = SCAN_TYPE_INVALID; + EXPECT_EQ(false, pScanStateMachine->VerifyScanStyle(scanStyle)); + } + + void ActiveScanStyleTest1() + { + pScanStateMachine->runningScanSettings.scanStyle = SCAN_TYPE_LOW_SPAN; + int scanStyle = SCAN_TYPE_LOW_POWER; + pScanStateMachine->ActiveScanStyle(scanStyle); + } + + void ActiveScanStyleTest2() + { + pScanStateMachine->runningScanSettings.scanStyle = SCAN_TYPE_HIGH_ACCURACY; + int scanStyle = SCAN_TYPE_LOW_POWER; + pScanStateMachine->ActiveScanStyle(scanStyle); + } + + void ActiveScanStyleTest3() + { + pScanStateMachine->runningScanSettings.scanStyle = SCAN_TYPE_INVALID; + int scanStyle = SCAN_TYPE_LOW_POWER; + pScanStateMachine->ActiveScanStyle(scanStyle); + } + + void MergeScanStyleTest1() + { + int currentScanStyle = SCAN_TYPE_LOW_SPAN; + int newScanStyle = SCAN_TYPE_HIGH_ACCURACY; + pScanStateMachine->MergeScanStyle(currentScanStyle, newScanStyle); + } + + void MergeScanStyleTest2() + { + int currentScanStyle = SCAN_TYPE_HIGH_ACCURACY; + int newScanStyle = SCAN_TYPE_HIGH_ACCURACY; + pScanStateMachine->MergeScanStyle(currentScanStyle, newScanStyle); + } + + void MergeScanStyleTest3() + { + int currentScanStyle = SCAN_TYPE_INVALID; + int newScanStyle = SCAN_TYPE_HIGH_ACCURACY; + pScanStateMachine->MergeScanStyle(currentScanStyle, newScanStyle); + } + + void RemoveCommonScanRequestTest() + { + InterScanConfig interScanConfig; + pScanStateMachine->runningScans.emplace(0, interScanConfig); + pScanStateMachine->waitingScans.emplace(0, interScanConfig); + pScanStateMachine->RemoveCommonScanRequest(0); + } + + void PnoScanRequestProcessTest() + { + InternalMessage msg; + pScanStateMachine->PnoScanRequestProcess(&msg); + } + + void ContinuePnoScanProcess() + { + pScanStateMachine->pnoConfigStoredFlag = true; + pScanStateMachine->ContinuePnoScanProcess(); + } + + void PnoScanHardwareProcessTest1() + { + pScanStateMachine->runningHwPnoFlag = false; + InternalMessage msg; + pScanStateMachine->PnoScanHardwareProcess(&msg); + } + + void PnoScanHardwareProcessTest2() + { + pScanStateMachine->runningHwPnoFlag = true; + InternalMessage msg; + pScanStateMachine->PnoScanHardwareProcess(&msg); + } + + void StartPnoScanHardwareSuccess1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartPnoScan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanStateMachine->runningHwPnoFlag = false; + pScanStateMachine->pnoConfigStoredFlag = true; + EXPECT_EQ(true, pScanStateMachine->StartPnoScanHardware()); + } + + void StartPnoScanHardwareSuccess2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartPnoScan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanStateMachine->runningHwPnoFlag = true; + pScanStateMachine->pnoConfigStoredFlag = true; + EXPECT_EQ(true, pScanStateMachine->StartPnoScanHardware()); + } + + void StartPnoScanHardwareSuccess3() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartPnoScan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanStateMachine->runningHwPnoFlag = false; + pScanStateMachine->pnoConfigStoredFlag = false; + EXPECT_EQ(true, pScanStateMachine->StartPnoScanHardware()); + } + + void StopPnoScanHardwareTest1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanStateMachine->supportHwPnoFlag = true; + pScanStateMachine->runningHwPnoFlag = true; + pScanStateMachine->StopPnoScanHardware(); + } + + void StopPnoScanHardwareTest2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanStateMachine->supportHwPnoFlag = false; + pScanStateMachine->runningHwPnoFlag = true; + pScanStateMachine->StopPnoScanHardware(); + } + + void StopPnoScanHardwareTest3() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + pScanStateMachine->supportHwPnoFlag = true; + pScanStateMachine->runningHwPnoFlag = true; + pScanStateMachine->StopPnoScanHardware(); + } + + void UpdatePnoScanRequestTest() + { + InternalMessage msg; + pScanStateMachine->UpdatePnoScanRequest(&msg); + } + + void GetPnoScanRequestInfoTest1() + { + InternalMessage msg; + pScanStateMachine->GetPnoScanRequestInfo(&msg); + } + + void GetPnoScanRequestInfoTest2() + { + pScanStateMachine->GetPnoScanRequestInfo(nullptr); + } + + void GetPnoScanConfigSuccess() + { + InternalMessage msg; + msg.AddIntMessageBody(0); + msg.AddIntMessageBody(0); + msg.AddIntMessageBody(0); + msg.AddIntMessageBody(1); + msg.AddStringMessageBody("hmwifi1"); + msg.AddIntMessageBody(0); + msg.AddStringMessageBody("hmwifi2"); + msg.AddIntMessageBody(1); + msg.AddIntMessageBody(FREQ_2_DOT_4_GHZ_VALUE); + PnoScanConfig pnoScanConfig; + EXPECT_EQ(true, pScanStateMachine->GetPnoScanConfig(&msg, pnoScanConfig)); + } + + void GetPnoScanConfigFail1() + { + PnoScanConfig pnoScanConfig; + EXPECT_EQ(false, pScanStateMachine->GetPnoScanConfig(nullptr, pnoScanConfig)); + } + + void GetPnoScanConfigFail2() + { + InternalMessage msg; + msg.AddIntMessageBody(0); + msg.AddIntMessageBody(0); + msg.AddIntMessageBody(0); + msg.AddIntMessageBody(1); + PnoScanConfig pnoScanConfig; + EXPECT_EQ(false, pScanStateMachine->GetPnoScanConfig(&msg, pnoScanConfig)); + } + + void HwPnoScanInfoProcessTest1() + { + std::vector scanInfos = { InterScanInfo() }; + EXPECT_CALL(WifiStaHalInterface::GetInstance(), QueryScanInfos(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(scanInfos), Return(WIFI_IDL_OPT_OK))); + pScanStateMachine->runningHwPnoFlag = true; + pScanStateMachine->HwPnoScanInfoProcess(); + } + + void HwPnoScanInfoProcessTest2() + { + std::vector scanInfos = { InterScanInfo() }; + EXPECT_CALL(WifiStaHalInterface::GetInstance(), QueryScanInfos(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(scanInfos), Return(WIFI_IDL_OPT_OK))); + pScanStateMachine->runningHwPnoFlag = false; + pScanStateMachine->HwPnoScanInfoProcess(); + } + + void HwPnoScanInfoProcessTest3() + { + std::vector scanInfos = { InterScanInfo() }; + EXPECT_CALL(WifiStaHalInterface::GetInstance(), QueryScanInfos(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(scanInfos), Return(WIFI_IDL_OPT_FAILED))); + pScanStateMachine->runningHwPnoFlag = true; + pScanStateMachine->HwPnoScanInfoProcess(); + } + + void ReportPnoScanInfosTest() + { + std::vector scanInfos = { InterScanInfo() }; + pScanStateMachine->ReportPnoScanInfos(scanInfos); + } + + void NeedCommonScanAfterPnoTest() + { + std::vector scanInfos = { InterScanInfo() }; + EXPECT_EQ(false, pScanStateMachine->NeedCommonScanAfterPno(scanInfos)); + } + + void CommonScanAfterPnoProcessTest1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanStateMachine->CommonScanAfterPnoProcess(); + } + + void CommonScanAfterPnoProcessTest2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + pScanStateMachine->CommonScanAfterPnoProcess(); + } + + void CommonScanAfterPnoResultTest1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), QueryScanInfos(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanStateMachine->CommonScanAfterPnoResult(); + } + + void CommonScanAfterPnoResultTest2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), QueryScanInfos(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + pScanStateMachine->CommonScanAfterPnoResult(); + } + + void PnoScanFailedProcessSuccessTest() + { + pScanStateMachine->PnoScanFailedProcess(); + } + + void ClearPnoScanConfigTest() + { + pScanStateMachine->ClearPnoScanConfig(); + } + + void GetScanInfosSuccess() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), QueryScanInfos(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + std::vector scanInfos; + EXPECT_EQ(true, pScanStateMachine->GetScanInfos(scanInfos)); + } + + void GetScanInfosFail() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), QueryScanInfos(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + std::vector scanInfos; + EXPECT_EQ(false, pScanStateMachine->GetScanInfos(scanInfos)); + } + + void GetSecurityTypeAndBandTest() + { + std::vector scanInfos; + InterScanInfo interScanInfo; + interScanInfo.frequency = FREQ_2_DOT_4_GHZ_VALUE; + interScanInfo.capabilities = "WAPI-PSK"; + scanInfos.push_back(interScanInfo); + interScanInfo.frequency = FREQ_5_GHZ_VALUE; + interScanInfo.capabilities = "PSK"; + scanInfos.push_back(interScanInfo); + interScanInfo.frequency = FREQ_5_GHZ_VALUE; + interScanInfo.capabilities = "WEP"; + scanInfos.push_back(interScanInfo); + interScanInfo.frequency = FREQ_5_GHZ_VALUE; + interScanInfo.capabilities = "EAP_SUITE_B_192"; + scanInfos.push_back(interScanInfo); + interScanInfo.frequency = FREQ_5_GHZ_VALUE; + interScanInfo.capabilities = "EAP"; + scanInfos.push_back(interScanInfo); + interScanInfo.frequency = FREQ_5_GHZ_VALUE; + interScanInfo.capabilities = "SAE"; + scanInfos.push_back(interScanInfo); + interScanInfo.frequency = FREQ_5_GHZ_VALUE; + interScanInfo.capabilities = "OWE"; + scanInfos.push_back(interScanInfo); + interScanInfo.frequency = FREQ_5_GHZ_VALUE; + interScanInfo.capabilities = "CERT"; + scanInfos.push_back(interScanInfo); + pScanStateMachine->GetSecurityTypeAndBand(scanInfos); + } + + void StartNewSoftwareScanTest() + { + pScanStateMachine->StartNewSoftwareScan(); + } + + void RepeatStartCommonScanTest1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanStateMachine->pnoConfigStoredFlag = true; + EXPECT_EQ(true, pScanStateMachine->RepeatStartCommonScan()); + } + + void RepeatStartCommonScanTest2() + { + pScanStateMachine->pnoConfigStoredFlag = false; + EXPECT_EQ(false, pScanStateMachine->RepeatStartCommonScan()); + } + + void RepeatStartCommonScanTest3() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + pScanStateMachine->pnoConfigStoredFlag = true; + EXPECT_EQ(false, pScanStateMachine->RepeatStartCommonScan()); + } + + void StopPnoScanSoftwareTest() + { + pScanStateMachine->StopPnoScanSoftware(); + } + + void PnoScanSoftwareProcessTest1() + { + InternalMessage msg; + pScanStateMachine->runningSwPnoFlag = false; + pScanStateMachine->PnoScanSoftwareProcess(&msg); + } + + void PnoScanSoftwareProcessTest2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + pScanStateMachine->runningSwPnoFlag = true; + pScanStateMachine->PnoScanSoftwareProcess(&msg); + } + + void PnoScanSoftwareProcessTest3() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + InternalMessage msg; + pScanStateMachine->runningSwPnoFlag = true; + pScanStateMachine->PnoScanSoftwareProcess(&msg); + } + + void SoftwareScanInfoProcessTest1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), QueryScanInfos(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pScanStateMachine->SoftwareScanInfoProcess(); + } + + void SoftwareScanInfoProcessTest2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), QueryScanInfos(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + pScanStateMachine->SoftwareScanInfoProcess(); + } + + void InitCommonScanStateTest() + { + pScanStateMachine->InitCommonScanState(); + } + + void InitPnoScanState() + { + pScanStateMachine->InitPnoScanState(); + } + + void BuildScanStateTreeTest() + { + pScanStateMachine->BuildScanStateTree(); + } +}; + +HWTEST_F(ScanStateMachineTest, InitGoInStateTest, TestSize.Level1) +{ + InitGoInStateTest(); +} + +HWTEST_F(ScanStateMachineTest, InitGoOutStateTest, TestSize.Level1) +{ + InitGoOutStateTest(); +} + +HWTEST_F(ScanStateMachineTest, InitExeMsgSuccess1, TestSize.Level1) +{ + InitExeMsgSuccess1(); +} + +HWTEST_F(ScanStateMachineTest, InitExeMsgSuccess2, TestSize.Level1) +{ + InitExeMsgSuccess2(); +} + +HWTEST_F(ScanStateMachineTest, InitExeMsgSuccess3, TestSize.Level1) +{ + InitExeMsgSuccess3(); +} + +HWTEST_F(ScanStateMachineTest, InitExeMsgSuccess4, TestSize.Level1) +{ + InitExeMsgSuccess4(); +} + +HWTEST_F(ScanStateMachineTest, InitExeMsgSuccess5, TestSize.Level1) +{ + InitExeMsgSuccess5(); +} + +HWTEST_F(ScanStateMachineTest, InitExeMsgSuccess6, TestSize.Level1) +{ + InitExeMsgSuccess6(); +} + +HWTEST_F(ScanStateMachineTest, InitExeMsgSuccess7, TestSize.Level1) +{ + InitExeMsgSuccess7(); +} + +HWTEST_F(ScanStateMachineTest, InitExeMsgSuccess8, TestSize.Level1) +{ + InitExeMsgSuccess8(); +} + +HWTEST_F(ScanStateMachineTest, InitExeMsgSuccess9, TestSize.Level1) +{ + InitExeMsgSuccess9(); +} + +HWTEST_F(ScanStateMachineTest, InitExeMsgSuccess10, TestSize.Level1) +{ + InitExeMsgSuccess10(); +} + +HWTEST_F(ScanStateMachineTest, InitExeMsgFail, TestSize.Level1) +{ + InitExeMsgFail(); +} + +HWTEST_F(ScanStateMachineTest, HardwareReadyGoInStateTest, TestSize.Level1) +{ + HardwareReadyGoInStateTest(); +} + +HWTEST_F(ScanStateMachineTest, HardwareReadyGoOutStateMsgTest, TestSize.Level1) +{ + HardwareReadyGoOutStateMsgTest(); +} + +HWTEST_F(ScanStateMachineTest, HardwareReadyExeMsgSuccess1, TestSize.Level1) +{ + HardwareReadyExeMsgSuccess1(); +} + +HWTEST_F(ScanStateMachineTest, HardwareReadyExeMsgSuccess2, TestSize.Level1) +{ + HardwareReadyExeMsgSuccess2(); +} + +HWTEST_F(ScanStateMachineTest, HardwareReadyExeMsgFail, TestSize.Level1) +{ + HardwareReadyExeMsgFail(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanGoInStateTest, TestSize.Level1) +{ + CommonScanGoInStateTest(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanGoOutStateTest, TestSize.Level1) +{ + CommonScanGoOutStateTest(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanExeMsgSuccess, TestSize.Level1) +{ + CommonScanExeMsgSuccess(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanExeMsgFail, TestSize.Level1) +{ + CommonScanExeMsgFail(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanUnworkedGoInStateTest, TestSize.Level1) +{ + CommonScanUnworkedGoInStateTest(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanUnworkedGoOutStateTest, TestSize.Level1) +{ + CommonScanUnworkedGoOutStateTest(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanUnworkedExeMsgSuccess1, TestSize.Level1) +{ + CommonScanUnworkedExeMsgSuccess1(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanUnworkedExeMsgSuccess2, TestSize.Level1) +{ + CommonScanUnworkedExeMsgSuccess2(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanUnworkedExeMsgSuccess3, TestSize.Level1) +{ + CommonScanUnworkedExeMsgSuccess3(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanUnworkedExeMsgFail, TestSize.Level1) +{ + CommonScanUnworkedExeMsgFail(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanningGoInStateTest, TestSize.Level1) +{ + CommonScanningGoInStateTest(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanningGoOutStateTest, TestSize.Level1) +{ + CommonScanningGoOutStateTest(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanningExeMsgSuccess1, TestSize.Level1) +{ + CommonScanningExeMsgSuccess1(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanningExeMsgSuccess2, TestSize.Level1) +{ + CommonScanningExeMsgSuccess2(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanningExeMsgSuccess3, TestSize.Level1) +{ + CommonScanningExeMsgSuccess3(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanningExeMsgSuccess4, TestSize.Level1) +{ + CommonScanningExeMsgSuccess4(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanningExeMsgSuccess5, TestSize.Level1) +{ + CommonScanningExeMsgSuccess5(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanningExeMsgSuccess6, TestSize.Level1) +{ + CommonScanningExeMsgSuccess6(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanningExeMsgFail, TestSize.Level1) +{ + CommonScanningExeMsgFail(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanGoInStateTest, TestSize.Level1) +{ + PnoScanGoInStateTest(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanGoOutStateTest, TestSize.Level1) +{ + PnoScanGoOutStateTest(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanExeMsgSuccess, TestSize.Level1) +{ + PnoScanExeMsgSuccess(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanExeMsgFail, TestSize.Level1) +{ + PnoScanExeMsgFail(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanHardwareGoInStateTest, TestSize.Level1) +{ + PnoScanHardwareGoInStateTest(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanHardwareGoOutStateTest, TestSize.Level1) +{ + PnoScanHardwareGoOutStateTest(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanHardwareExeMsgSuccess1, TestSize.Level1) +{ + PnoScanHardwareExeMsgSuccess1(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanHardwareExeMsgSuccess2, TestSize.Level1) +{ + PnoScanHardwareExeMsgSuccess2(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanHardwareExeMsgSuccess3, TestSize.Level1) +{ + PnoScanHardwareExeMsgSuccess3(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanHardwareExeMsgSuccess4, TestSize.Level1) +{ + PnoScanHardwareExeMsgSuccess4(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanHardwareExeMsgSuccess5, TestSize.Level1) +{ + PnoScanHardwareExeMsgSuccess5(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanHardwareExeMsgSuccess6, TestSize.Level1) +{ + PnoScanHardwareExeMsgSuccess6(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanHardwareExeMsgFail, TestSize.Level1) +{ + PnoScanHardwareExeMsgFail(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanAfterPnoGoInStateTest, TestSize.Level1) +{ + CommonScanAfterPnoGoInStateTest(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanAfterPnoGoOutStateTest, TestSize.Level1) +{ + CommonScanAfterPnoGoOutStateTest(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanAfterPnoExeMsgSuccess1, TestSize.Level1) +{ + CommonScanAfterPnoExeMsgSuccess1(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanAfterPnoExeMsgSuccess2, TestSize.Level1) +{ + CommonScanAfterPnoExeMsgSuccess2(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanAfterPnoExeMsgSuccess3, TestSize.Level1) +{ + CommonScanAfterPnoExeMsgSuccess3(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanAfterPnoExeMsgSuccess4, TestSize.Level1) +{ + CommonScanAfterPnoExeMsgSuccess4(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanAfterPnoExeMsgSuccess5, TestSize.Level1) +{ + CommonScanAfterPnoExeMsgSuccess5(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanAfterPnoExeMsgSuccess6, TestSize.Level1) +{ + CommonScanAfterPnoExeMsgSuccess6(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanAfterPnoExeMsgFail, TestSize.Level1) +{ + CommonScanAfterPnoExeMsgFail(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanSoftwareGoInStateTest, TestSize.Level1) +{ + PnoScanSoftwareGoInStateTest(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanSoftwareGoOutStateTest, TestSize.Level1) +{ + PnoScanSoftwareGoOutStateTest(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanSoftwareExeMsgSuccess1, TestSize.Level1) +{ + PnoScanSoftwareExeMsgSuccess1(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanSoftwareExeMsgSuccess2, TestSize.Level1) +{ + PnoScanSoftwareExeMsgSuccess2(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanSoftwareExeMsgFail, TestSize.Level1) +{ + PnoScanSoftwareExeMsgFail(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanFreeGoInStateTest, TestSize.Level1) +{ + PnoSwScanFreeGoInStateTest(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanFreeGoOutStateTest, TestSize.Level1) +{ + PnoSwScanFreeGoOutStateTest(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanFreeExeMsgSuccess1, TestSize.Level1) +{ + PnoSwScanFreeExeMsgSuccess1(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanFreeExeMsgSuccess2, TestSize.Level1) +{ + PnoSwScanFreeExeMsgSuccess2(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanFreeExeMsgSuccess3, TestSize.Level1) +{ + PnoSwScanFreeExeMsgSuccess3(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanFreeExeMsgSuccess4, TestSize.Level1) +{ + PnoSwScanFreeExeMsgSuccess4(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanFreeExeMsgSuccess5, TestSize.Level1) +{ + PnoSwScanFreeExeMsgSuccess5(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanFreeExeMsgFail, TestSize.Level1) +{ + PnoSwScanFreeExeMsgFail(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanningGoInStateTest, TestSize.Level1) +{ + PnoSwScanningGoInStateTest(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanningGoOutStateTest, TestSize.Level1) +{ + PnoSwScanningGoOutStateTest(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanningExeMsgSuccess1, TestSize.Level1) +{ + PnoSwScanningExeMsgSuccess1(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanningExeMsgSuccess2, TestSize.Level1) +{ + PnoSwScanningExeMsgSuccess2(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanningExeMsgSuccess3, TestSize.Level1) +{ + PnoSwScanningExeMsgSuccess3(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanningExeMsgSuccess4, TestSize.Level1) +{ + PnoSwScanningExeMsgSuccess4(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanningExeMsgSuccess5, TestSize.Level1) +{ + PnoSwScanningExeMsgSuccess5(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanningExeMsgSuccess6, TestSize.Level1) +{ + PnoSwScanningExeMsgSuccess6(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanningExeMsgSuccess7, TestSize.Level1) +{ + PnoSwScanningExeMsgSuccess7(); +} + +HWTEST_F(ScanStateMachineTest, PnoSwScanningExeMsgFail, TestSize.Level1) +{ + PnoSwScanningExeMsgFail(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanRequestProcessTest, TestSize.Level1) +{ + CommonScanRequestProcessTest(); +} + +HWTEST_F(ScanStateMachineTest, GetCommonScanRequestInfoTest1, TestSize.Level1) +{ + GetCommonScanRequestInfoTest1(); +} + +HWTEST_F(ScanStateMachineTest, GetCommonScanRequestInfoTest2, TestSize.Level1) +{ + GetCommonScanRequestInfoTest2(); +} + +HWTEST_F(ScanStateMachineTest, GetCommonScanConfigSuccess, TestSize.Level1) +{ + GetCommonScanConfigSuccess(); +} + +HWTEST_F(ScanStateMachineTest, GetCommonScanConfigFail1, TestSize.Level1) +{ + GetCommonScanConfigFail1(); +} + +HWTEST_F(ScanStateMachineTest, GetCommonScanConfigFail2, TestSize.Level1) +{ + GetCommonScanConfigFail2(); +} + +HWTEST_F(ScanStateMachineTest, GetCommonScanConfigFail3, TestSize.Level1) +{ + GetCommonScanConfigFail3(); +} + +HWTEST_F(ScanStateMachineTest, StartNewCommonScanTest1, TestSize.Level1) +{ + StartNewCommonScanTest1(); +} + +HWTEST_F(ScanStateMachineTest, StartNewCommonScanTest2, TestSize.Level1) +{ + StartNewCommonScanTest2(); +} + +HWTEST_F(ScanStateMachineTest, ClearRunningScanSettingsTest, TestSize.Level1) +{ + ClearRunningScanSettingsTest(); +} + +HWTEST_F(ScanStateMachineTest, StartSingleCommonScanSuccess, TestSize.Level1) +{ + StartSingleCommonScanSuccess(); +} + +HWTEST_F(ScanStateMachineTest, StartSingleCommonScanFail, TestSize.Level1) +{ + StartSingleCommonScanFail(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanWhenRunningSuccess, TestSize.Level1) +{ + CommonScanWhenRunningSuccess(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanWhenRunningFail, TestSize.Level1) +{ + CommonScanWhenRunningFail(); +} + +HWTEST_F(ScanStateMachineTest, ActiveCoverNewScanSuccess, TestSize.Level1) +{ + ActiveCoverNewScanSuccess(); +} + +HWTEST_F(ScanStateMachineTest, ActiveCoverNewScanFail, TestSize.Level1) +{ + ActiveCoverNewScanFail(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanInfoProcessTest, TestSize.Level1) +{ + CommonScanInfoProcessTest(); +} + +HWTEST_F(ScanStateMachineTest, ReportStatusChangeTest, TestSize.Level1) +{ + ReportStatusChangeTest(); +} + +HWTEST_F(ScanStateMachineTest, ReportScanInnerEventTest, TestSize.Level1) +{ + ReportScanInnerEventTest(); +} + +HWTEST_F(ScanStateMachineTest, ReportCommonScanFailedTest, TestSize.Level1) +{ + ReportCommonScanFailedTest(); +} + +HWTEST_F(ScanStateMachineTest, ReportCommonScanFailedAndClearTest1, TestSize.Level1) +{ + ReportCommonScanFailedAndClearTest1(); +} + +HWTEST_F(ScanStateMachineTest, ReportCommonScanFailedAndClearTest2, TestSize.Level1) +{ + ReportCommonScanFailedAndClearTest2(); +} + +HWTEST_F(ScanStateMachineTest, GetRunningIndexListTest, TestSize.Level1) +{ + GetRunningIndexListTest(); +} + +HWTEST_F(ScanStateMachineTest, GetWaitingIndexListTest, TestSize.Level1) +{ + GetWaitingIndexListTest(); +} + +HWTEST_F(ScanStateMachineTest, VerifyScanStyleSuccess, TestSize.Level1) +{ + VerifyScanStyleSuccess(); +} + +HWTEST_F(ScanStateMachineTest, VerifyScanStyleFail, TestSize.Level1) +{ + VerifyScanStyleFail(); +} + +HWTEST_F(ScanStateMachineTest, ActiveScanStyleTest1, TestSize.Level1) +{ + ActiveScanStyleTest1(); +} + +HWTEST_F(ScanStateMachineTest, ActiveScanStyleTest2, TestSize.Level1) +{ + ActiveScanStyleTest2(); +} + +HWTEST_F(ScanStateMachineTest, ActiveScanStyleTest3, TestSize.Level1) +{ + ActiveScanStyleTest3(); +} + +HWTEST_F(ScanStateMachineTest, MergeScanStyleTest1, TestSize.Level1) +{ + MergeScanStyleTest1(); +} + +HWTEST_F(ScanStateMachineTest, MergeScanStyleTest2, TestSize.Level1) +{ + MergeScanStyleTest2(); +} + +HWTEST_F(ScanStateMachineTest, MergeScanStyleTest3, TestSize.Level1) +{ + MergeScanStyleTest3(); +} + +HWTEST_F(ScanStateMachineTest, RemoveCommonScanRequestTest, TestSize.Level1) +{ + RemoveCommonScanRequestTest(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanRequestProcessTest, TestSize.Level1) +{ + PnoScanRequestProcessTest(); +} + +HWTEST_F(ScanStateMachineTest, ContinuePnoScanProcess, TestSize.Level1) +{ + ContinuePnoScanProcess(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanHardwareProcessTest1, TestSize.Level1) +{ + PnoScanHardwareProcessTest1(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanHardwareProcessTest2, TestSize.Level1) +{ + PnoScanHardwareProcessTest2(); +} + +HWTEST_F(ScanStateMachineTest, StartPnoScanHardwareSuccess1, TestSize.Level1) +{ + StartPnoScanHardwareSuccess1(); +} + +HWTEST_F(ScanStateMachineTest, StartPnoScanHardwareSuccess2, TestSize.Level1) +{ + StartPnoScanHardwareSuccess2(); +} + +HWTEST_F(ScanStateMachineTest, StartPnoScanHardwareSuccess3, TestSize.Level1) +{ + StartPnoScanHardwareSuccess3(); +} + +HWTEST_F(ScanStateMachineTest, StopPnoScanHardwareTest1, TestSize.Level1) +{ + StopPnoScanHardwareTest1(); +} + +HWTEST_F(ScanStateMachineTest, StopPnoScanHardwareTest2, TestSize.Level1) +{ + StopPnoScanHardwareTest2(); +} + +HWTEST_F(ScanStateMachineTest, StopPnoScanHardwareTest3, TestSize.Level1) +{ + StopPnoScanHardwareTest3(); +} + +HWTEST_F(ScanStateMachineTest, UpdatePnoScanRequestTest, TestSize.Level1) +{ + UpdatePnoScanRequestTest(); +} + +HWTEST_F(ScanStateMachineTest, GetPnoScanRequestInfoTest1, TestSize.Level1) +{ + GetPnoScanRequestInfoTest1(); +} + +HWTEST_F(ScanStateMachineTest, GetPnoScanRequestInfoTest2, TestSize.Level1) +{ + GetPnoScanRequestInfoTest2(); +} + +HWTEST_F(ScanStateMachineTest, GetPnoScanConfigSuccess, TestSize.Level1) +{ + GetPnoScanConfigSuccess(); +} + +HWTEST_F(ScanStateMachineTest, GetPnoScanConfigFail1, TestSize.Level1) +{ + GetPnoScanConfigFail1(); +} + +HWTEST_F(ScanStateMachineTest, GetPnoScanConfigFail2, TestSize.Level1) +{ + GetPnoScanConfigFail2(); +} + +HWTEST_F(ScanStateMachineTest, HwPnoScanInfoProcessTest1, TestSize.Level1) +{ + HwPnoScanInfoProcessTest1(); +} + +HWTEST_F(ScanStateMachineTest, HwPnoScanInfoProcessTest2, TestSize.Level1) +{ + HwPnoScanInfoProcessTest2(); +} + +HWTEST_F(ScanStateMachineTest, HwPnoScanInfoProcessTest3, TestSize.Level1) +{ + HwPnoScanInfoProcessTest3(); +} + +HWTEST_F(ScanStateMachineTest, ReportPnoScanInfosTest, TestSize.Level1) +{ + ReportPnoScanInfosTest(); +} + +HWTEST_F(ScanStateMachineTest, NeedCommonScanAfterPnoTest, TestSize.Level1) +{ + NeedCommonScanAfterPnoTest(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanAfterPnoProcessTest1, TestSize.Level1) +{ + CommonScanAfterPnoProcessTest1(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanAfterPnoProcessTest2, TestSize.Level1) +{ + CommonScanAfterPnoProcessTest2(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanAfterPnoResultTest1, TestSize.Level1) +{ + CommonScanAfterPnoResultTest1(); +} + +HWTEST_F(ScanStateMachineTest, CommonScanAfterPnoResultTest2, TestSize.Level1) +{ + CommonScanAfterPnoResultTest2(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanFailedProcessSuccessTest, TestSize.Level1) +{ + PnoScanFailedProcessSuccessTest(); +} + +HWTEST_F(ScanStateMachineTest, ClearPnoScanConfigTest, TestSize.Level1) +{ + ClearPnoScanConfigTest(); +} + +HWTEST_F(ScanStateMachineTest, GetScanInfosSuccess, TestSize.Level1) +{ + GetScanInfosSuccess(); +} + +HWTEST_F(ScanStateMachineTest, GetScanInfosFail, TestSize.Level1) +{ + GetScanInfosFail(); +} + +HWTEST_F(ScanStateMachineTest, GetSecurityTypeAndBandTest, TestSize.Level1) +{ + GetSecurityTypeAndBandTest(); +} + +HWTEST_F(ScanStateMachineTest, StartNewSoftwareScanTest, TestSize.Level1) +{ + StartNewSoftwareScanTest(); +} + +HWTEST_F(ScanStateMachineTest, RepeatStartCommonScanTest1, TestSize.Level1) +{ + RepeatStartCommonScanTest1(); +} + +HWTEST_F(ScanStateMachineTest, RepeatStartCommonScanTest2, TestSize.Level1) +{ + RepeatStartCommonScanTest2(); +} + +HWTEST_F(ScanStateMachineTest, RepeatStartCommonScanTest3, TestSize.Level1) +{ + RepeatStartCommonScanTest3(); +} + +HWTEST_F(ScanStateMachineTest, StopPnoScanSoftwareTest, TestSize.Level1) +{ + StopPnoScanSoftwareTest(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanSoftwareProcessTest1, TestSize.Level1) +{ + PnoScanSoftwareProcessTest1(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanSoftwareProcessTest2, TestSize.Level1) +{ + PnoScanSoftwareProcessTest2(); +} + +HWTEST_F(ScanStateMachineTest, PnoScanSoftwareProcessTest3, TestSize.Level1) +{ + PnoScanSoftwareProcessTest3(); +} + +HWTEST_F(ScanStateMachineTest, SoftwareScanInfoProcessTest1, TestSize.Level1) +{ + SoftwareScanInfoProcessTest1(); +} + +HWTEST_F(ScanStateMachineTest, SoftwareScanInfoProcessTest2, TestSize.Level1) +{ + SoftwareScanInfoProcessTest2(); +} + +HWTEST_F(ScanStateMachineTest, InitCommonScanStateTest, TestSize.Level1) +{ + InitCommonScanStateTest(); +} + +HWTEST_F(ScanStateMachineTest, InitPnoScanState, TestSize.Level1) +{ + InitPnoScanState(); +} + +HWTEST_F(ScanStateMachineTest, BuildScanStateTreeTest, TestSize.Level1) +{ + BuildScanStateTreeTest(); +} + +HWTEST_F(ScanStateMachineTest, LoadDriverTest, TestSize.Level1) +{ + LoadDriverTest(); +} + +HWTEST_F(ScanStateMachineTest, UnLoadDriverTest, TestSize.Level1) +{ + UnLoadDriverTest(); +} +} // namespace Wifi +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/wifi_scan_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/wifi_scan_test.cpp new file mode 100644 index 000000000..067af39ab --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/wifi_scan_test.cpp @@ -0,0 +1,24 @@ +/* + * 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 "global_test.h" + +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + testing::Environment *env = new GlobalTest(); + testing::AddGlobalTestEnvironment(env); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn new file mode 100644 index 000000000..ed8238a2c --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn @@ -0,0 +1,129 @@ +# 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. + +import("//build/test.gni") +SUBSYSTEM_DIR = "//foundation/communication" +module_output_path = "wifi_standard/sta_test" + +defines = [] +defines += [ "OHOS_WIFI_STA_TEST" ] + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + ] +} + +ohos_unittest("wifi_sta_unittest") { + module_out_path = module_output_path + sources = [ + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/http_request.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp", + + #"//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_extern_device_appraisal.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_speed.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp", + "Mock/mock_dhcp_service.cpp", + "Mock/mock_if_config.cpp", + "Mock/mock_mac_address.cpp", + "Mock/mock_sta_auto_connect_service.cpp", + "Mock/mock_sta_network_check.cpp", + "Mock/mock_sta_state_machine.cpp", + "Mock/mock_wifi_chip_hal_interface.cpp", + "Mock/mock_wifi_manager.cpp", + "Mock/mock_wifi_settings.cpp", + "Mock/mock_wifi_sta_hal_interface.cpp", + "Mock/mock_wifi_supplicant_hal_interface.cpp", + "global_test.cpp", + "sta_auto_connect_service_test.cpp", + "sta_interface_test.cpp", + "sta_monitor_test.cpp", + "sta_network_check_test.cpp", + "sta_saved_device_appraisal_test.cpp", + "sta_service_test.cpp", + "sta_state_machine_test.cpp", + "wifi_sta_test.cpp", + ] + + include_dirs = [ + "./", + "./Mock", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf", + "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/include", + "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", + "//foundation/communication/wifi/services/wifi_standard/interface", + "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_aware", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", + + "//third_party/googletest/googlemock/include", + "//third_party/googletest/googletest/include", + + "//base/notification/ces_standard/cesfwk/kits/native/include", + "//out/ohos-arm-release/innerkits/ohos-arm/ces_standard/cesfwk_kits/include", + + "//utils/native/base/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//foundation/ace/ace_engine/frameworks/base/utils", + "//foundation/ace/ace_engine/frameworks", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk/", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content/", + "//foundation/aafwk/aafwk_lite/interfaces/kits/want_lite/", + ] + + deps = [ + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + part_name = "wifi_standard" + subsystem_name = "communication" +} + +group("unittest") { + testonly = true + deps = [ ":wifi_sta_unittest" ] +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_device_appraisal.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_device_appraisal.h new file mode 100644 index 000000000..c819b04c0 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_device_appraisal.h @@ -0,0 +1,31 @@ +/* + * 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_DEVICEAPPRAISAL_H +#define OHOS_MOCK_DEVICEAPPRAISAL_H + +#include +#include "sta_device_appraisal.h" +namespace OHOS { +namespace Wifi { + class MockDeviceAppraisal : public StaDeviceAppraisal { + public: + MockDeviceAppraisal() = default; + ~MockDeviceAppraisal() = default; + MOCK_METHOD3(DeviceAppraisals, ErrCode(WifiDeviceConfig &electedDevice, std::vector &scanInfos, + WifiLinkedInfo &info)); + }; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.cpp new file mode 100644 index 000000000..fc6ec1ac2 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.cpp @@ -0,0 +1,131 @@ +/* + * 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 "mock_dhcp_service.h" +#include "wifi_logger.h" + +DEFINE_WIFILOG_DHCP_LABEL("DhcpService"); + +namespace OHOS { +namespace Wifi { +int DhcpService::StartDhcpClient(const std::string &ifname, bool bIpv6) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].ifname:%{public}s, isIpv6:%{public}d", __FUNCTION__, ifname.c_str(), + bIpv6); + return 0; +} + +int DhcpService::StopDhcpClient(const std::string &ifname, bool bIpv6) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].ifname:%{public}s, isIpv6:%{public}d", __FUNCTION__, ifname.c_str(), + bIpv6); + return 0; +} + +int DhcpService::GetDhcpResult(const std::string &ifname, IDhcpResultNotify *pResultNotify, int timeouts) +{ + pResultNotify = nullptr; + WIFI_LOGD("Enter DhcpService::[%{public}s].ifname:%{public}s, timeouts:%{public}d", __FUNCTION__, ifname.c_str(), + timeouts); + return 0; +} + +int DhcpService::GetDhcpInfo(const std::string &ifname, DhcpServiceInfo &dhcp) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].ifname:%{public}s, dhcp.clientRunStatus:%{public}d", __FUNCTION__, + ifname.c_str(), dhcp.clientRunStatus); + return 0; +} + +int DhcpService::RenewDhcpClient(const std::string &ifname) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].ifname:%{public}s", __FUNCTION__, ifname.c_str()); + return 0; +} + +int DhcpService::ReleaseDhcpClient(const std::string &ifname) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].ifname:%{public}s", __FUNCTION__, ifname.c_str()); + return 0; +} + +int DhcpService::StartDhcpServer(const std::string &ifname) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].ifname:%{public}s", __FUNCTION__, ifname.c_str()); + return 0; +} + +int DhcpService::StopDhcpServer(const std::string &ifname) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].ifname:%{public}s", __FUNCTION__, ifname.c_str()); + return 0; +} + +int DhcpService::GetServerStatus(void) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].", __FUNCTION__); + return 0; +} + +int DhcpService::PutDhcpRange(const std::string &tagName, const DhcpRange &range) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].tagName:%{public}s, range.iptype:%{public}d", __FUNCTION__, + tagName.c_str(), range.iptype); + return 0; +} + +int DhcpService::RemoveDhcpRange(const std::string &tagName, const DhcpRange &range) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].tagName:%{public}s, range.iptype:%{public}d", __FUNCTION__, + tagName.c_str(), range.iptype); + return 0; +} + +int DhcpService::RemoveAllDhcpRange(const std::string &tagName) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].tagName:%{public}s", __FUNCTION__, tagName.c_str()); + return 0; +} + +int DhcpService::SetDhcpRange(const std::string &ifname, const DhcpRange &range) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].tagName:%{public}s, range.iptype:%{public}d", __FUNCTION__, + ifname.c_str(), range.iptype); + return 0; +} + +int DhcpService::SetDhcpRange(const std::string &ifname, const std::string &tagName) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].ifname:%{public}s, tagName:%{public}s", __FUNCTION__, ifname.c_str(), + tagName.c_str()); + return 0; +} + +int DhcpService::GetLeases(const std::string&, std::vector& leases) +{ + WIFI_LOGD("Enter DhcpService::[%{public}s].", __FUNCTION__); + if (leases.size() == 0) { + return -1; + } + return 0; +} + +int DhcpService::GetDhcpSerProExit(const std::string &ifname, IDhcpResultNotify *pResultNotify) +{ + pResultNotify = nullptr; + WIFI_LOGD("Enter DhcpService::[%{public}s].ifname:%{public}s", __FUNCTION__, ifname.c_str()); + return 0; +} +} // namespace Wifi +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.h new file mode 100644 index 000000000..276240266 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.h @@ -0,0 +1,46 @@ +/* + * 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_DHCPSERVICE_H +#define OHOS_MOCK_DHCPSERVICE_H +#include +#include +#include "i_dhcp_service.h" + +namespace OHOS { +namespace Wifi { +class DhcpService : public IDhcpService { +public: + DhcpService() = default; + ~DhcpService() = default; + int StartDhcpClient(const std::string& ifname, bool bIpv6); + int StopDhcpClient(const std::string& ifname, bool bIpv6); + int GetDhcpResult(const std::string& ifname, IDhcpResultNotify *pResultNotify, int timeouts); + int GetDhcpInfo(const std::string& ifname, DhcpServiceInfo& dhcp); + int RenewDhcpClient(const std::string& ifname); + int ReleaseDhcpClient(const std::string& ifname); + int StartDhcpServer(const std::string& ifname); + int StopDhcpServer(const std::string& ifname); + int GetServerStatus(void); + int PutDhcpRange(const std::string& tagName, const DhcpRange& range); + int RemoveDhcpRange(const std::string& tagName, const DhcpRange& range); + int RemoveAllDhcpRange(const std::string& tagName); + int SetDhcpRange(const std::string& ifname, const DhcpRange& range); + int SetDhcpRange(const std::string& ifname, const std::string& tagName); + int GetLeases(const std::string& ifname, std::vector& leases); + int GetDhcpSerProExit(const std::string& ifname, IDhcpResultNotify *pResultNotify); +}; +} // namespace Wifi +} // namespace OHOS +#endif diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.cpp new file mode 100644 index 000000000..318da4e33 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.cpp @@ -0,0 +1,25 @@ +/* + * 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 "mock_if_config.h" + +namespace OHOS { +namespace Wifi { + IfConfig &IfConfig::GetInstance(void) + { + static IfConfig ifConfig; + return ifConfig; + } +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.h new file mode 100644 index 000000000..0d2746349 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.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_MOCK_IF_CONFIG_H +#define OHOS_MOCK_IF_CONFIG_H + +#include +#include "dhcp_define.h" + +namespace OHOS { +namespace Wifi { +class MockIfConfig { +public: + virtual ~MockIfConfig() = default; + virtual int SetIfAddr(const DhcpResult &dhcpInfo, int ipType) = 0; + virtual void SetProxy(bool isAuto, const std::string &proxy, const std::string &port, const std::string &noProxys, + const std::string &pac) = 0; + virtual void FlushIpAddr(const std::string &ifName, const int &ipType) = 0; +}; + +class IfConfig : public MockIfConfig { +public: + IfConfig() = default; + ~IfConfig() = default; + static IfConfig &GetInstance(void); + MOCK_METHOD2(SetIfAddr, int(const DhcpResult &dhcpInfo, int ipType)); + MOCK_METHOD5(SetProxy, void(bool isAuto, const std::string &proxy, const std::string &port, + const std::string &noProxys, const std::string &pac)); + MOCK_METHOD2(FlushIpAddr, void(const std::string &ifName, const int &ipType)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.cpp new file mode 100644 index 000000000..c02af5159 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.cpp @@ -0,0 +1,25 @@ +/* + * 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 "mock_mac_address.h" + +namespace OHOS { +namespace Wifi { +MacAddress &MacAddress::GetInstance(void) +{ + static MacAddress init; + return init; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.h new file mode 100644 index 000000000..5e6433290 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.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_MOCK_MAC_ADDRESS_H +#define OHOS_MOCK_MAC_ADDRESS_H + +#include + +namespace OHOS { +namespace Wifi { +class MockMacAddress { +public: + virtual ~MockMacAddress() = default; + + virtual bool IsValidMac(const char *mac) = 0; + +}; + +class MacAddress : public MockMacAddress { +public: + static MacAddress &GetInstance(void); + + MOCK_METHOD1(IsValidMac, bool(const char *mac)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.cpp new file mode 100644 index 000000000..56de28674 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.cpp @@ -0,0 +1,63 @@ +/* + * 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 "mock_sta_auto_connect_service.h" +#include "wifi_errcode.h" +#include "wifi_logger.h" + +DEFINE_WIFILOG_LABEL("MockStaAutoConnectService"); + +namespace OHOS { +namespace Wifi { +ErrCode MockStaAutoConnectService::InitAutoConnectService() +{ + WIFI_LOGI("Enter MockStaAutoConnectService::InitAutoConnectService.\n"); + return WIFI_OPT_SUCCESS; +} + +void MockStaAutoConnectService::OnScanInfosReadyHandler(const std::vector &scanInfos) +{ + (void) scanInfos; + WIFI_LOGI("Enter MockStaAutoConnectService::OnScanInfosReadyHandler.\n"); +} + +bool MockStaAutoConnectService::EnableOrDisableBssid(std::string bssid, bool enable, int reason) +{ + (void) bssid; + (void) enable; + (void) reason; + WIFI_LOGI("Enter MockStaAutoConnectService::EnableOrDisableBssid.\n"); + return true; +} + +ErrCode MockStaAutoConnectService::AutoSelectDevice(WifiDeviceConfig &electedDevice, + const std::vector &scanInfos, std::vector &blockedBssids, WifiLinkedInfo &info) +{ + (void) electedDevice; + (void) scanInfos; + (void) blockedBssids; + (void) info; + WIFI_LOGI("Enter MockStaAutoConnectService::AutoSelectDevice.\n"); + return WIFI_OPT_SUCCESS; +} + +bool MockStaAutoConnectService::RegisterDeviceAppraisal(StaDeviceAppraisal *appraisal, int priority) +{ + (void) appraisal; + (void) priority; + WIFI_LOGI("Enter MockStaAutoConnectService::RegisterDeviceAppraisal.\n"); + return true; +} +} // namespace Wifi +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.h new file mode 100644 index 000000000..26c299aa0 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.h @@ -0,0 +1,43 @@ +/* + * 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_STA_AUTO_CONNECT_SERVICE_H +#define OHOS_MOCK_STA_AUTO_CONNECT_SERVICE_H + +#include "sta_auto_connect_service.h" +#include +#include +#include +#include "wifi_msg.h" +#include "wifi_internal_msg.h" +#include "sta_device_appraisal.h" +#include "wifi_errcode.h" + + +namespace OHOS { +namespace Wifi { +class MockStaAutoConnectService : public StaAutoConnectService { +public: + explicit MockStaAutoConnectService(StaStateMachine *staStateMachine):StaAutoConnectService(staStateMachine) {} + ~MockStaAutoConnectService(){} + ErrCode InitAutoConnectService() override; + void OnScanInfosReadyHandler(const std::vector &scanInfos) override; + bool EnableOrDisableBssid(std::string bssid, bool enable, int reason) override; + ErrCode AutoSelectDevice(WifiDeviceConfig &electedDevice, const std::vector &scanInfos, + std::vector &blockedBssids, WifiLinkedInfo &info) override; + bool RegisterDeviceAppraisal(StaDeviceAppraisal *appraisal, int priority) override; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_monitor.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_monitor.h new file mode 100644 index 000000000..a7d549f21 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_monitor.h @@ -0,0 +1,52 @@ +/* + * 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_STA_MONITOR_H +#define OHOS_MOCK_STA_MONITOR_H + +#include + +#include "sta_state_machine.h" +#include "wifi_errcode.h" + +namespace OHOS { +namespace Wifi { +class MockStaMonitor { +public: + virtual ~MockStaMonitor() = default; + virtual ErrCode InitStaMonitor() = 0; + virtual ErrCode UnInitStaMonitor() const = 0; + virtual void SetStateMachine(StaStateMachine *paraStaStateMachine) = 0; + virtual void OnConnectChangedCallBack(int status, int networkId, const std::string &bssid) = 0; + virtual void OnWpaStateChangedCallBack(int status, void *pInstance) = 0; + virtual void OnWpaSsidWrongKeyCallBack(int status, void *pInstance) = 0; + virtual void OnWpsPbcOverlapCallBack(int status, void *pInstance) = 0; + virtual void OnWpsTimeOutCallBack(int status, void *pInstance) = 0; +}; + +class StaMonitor : public MockStaMonitor { +public: + + MOCK_METHOD0(InitStaMonitor, ErrCode()); + MOCK_CONST_METHOD0(UnInitStaMonitor, ErrCode()); + MOCK_METHOD1(SetStateMachine, void(StaStateMachine *paraStaStateMachine)); + MOCK_METHOD4(OnConnectChangedCallBack, void(int status, int networkId, const std::string &bssid); + MOCK_METHOD2(OnWpaStateChangedCallBack, void(int status, void *pInstance)); + MOCK_METHOD2(OnWpaSsidWrongKeyCallBack, void(int status, void *pInstance)); + MOCK_METHOD2(OnWpsPbcOverlapCallBack, void(int status, void *pInstance)); + MOCK_METHOD2(OnWpsTimeOutCallBack, void(int status, void *pInstance)); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.cpp new file mode 100644 index 000000000..621dd0be1 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.cpp @@ -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. + */ +#include "mock_sta_network_check.h" +#include "wifi_logger.h" + +DEFINE_WIFILOG_LABEL("MockStaNetworkCheck"); + +namespace OHOS { +namespace Wifi { +ErrCode MockStaNetworkCheck::InitNetCheckThread() +{ + WIFI_LOGD("Enter MockDhcpService::[%{public}s].", __FUNCTION__); + return WIFI_OPT_SUCCESS; +} +void MockStaNetworkCheck::SignalNetCheckThread() +{ + WIFI_LOGD("Enter MockDhcpService::[%{public}s].", __FUNCTION__); +} +void MockStaNetworkCheck::StopNetCheckThread() +{ + WIFI_LOGD("Enter MockDhcpService::[%{public}s].", __FUNCTION__); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.h new file mode 100644 index 000000000..81c1607b3 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.h @@ -0,0 +1,33 @@ +/* + * 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_STANETWORKCHECK_H +#define OHOS_MOCK_STANETWORKCHECK_H +#include +#include +#include "sta_network_check.h" + +namespace OHOS { +namespace Wifi { +class MockStaNetworkCheck : public StaNetworkCheck { +public: + explicit MockStaNetworkCheck(NetStateHandler handle) : StaNetworkCheck(handle) {} + ~MockStaNetworkCheck() = default; + ErrCode InitNetCheckThread() override; + void SignalNetCheckThread() override; + void StopNetCheckThread() override; +}; +} // namespace OHOS +} // namespace OHOS +#endif diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_service.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_service.h new file mode 100644 index 000000000..c931a5922 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_service.h @@ -0,0 +1,47 @@ +/* + * 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_WIFISTASERVICE_H +#define OHOS_MOCK_WIFISTASERVICE_H + +#include +#include "sta_service.h" + +namespace OHOS { +namespace Wifi { +class MockWifiStaService : public StaService { +public: + MockWifiStaService() {} + virtual ~MockWifiStaService() {} + MOCK_METHOD1(InitStaService, ErrCode(const StaServiceCallback &callbacks)); + MOCK_CONST_METHOD0(EnableWifi, ErrCode()); + MOCK_CONST_METHOD0(DisableWifi, ErrCode()); + MOCK_CONST_METHOD1(ConnectToDevice, ErrCode(const WifiDeviceConfig &config)); + MOCK_CONST_METHOD1(ConnectToNetwork, ErrCode(int networkId)); + MOCK_CONST_METHOD0(Disconnect, ErrCode()); + MOCK_CONST_METHOD0(ReAssociate, ErrCode()); + MOCK_CONST_METHOD1(AddDeviceConfig, int(const WifiDeviceConfig &config)); + MOCK_CONST_METHOD1(UpdateDeviceConfig, int(const WifiDeviceConfig &config)); + MOCK_CONST_METHOD1(RemoveDevice, ErrCode(int networkId)); + MOCK_CONST_METHOD2(EnableDeviceConfig, ErrCode(int networkId, bool attemptEnable)); + MOCK_CONST_METHOD1(DisableDeviceConfig, ErrCode(int networkId)); + MOCK_CONST_METHOD1(StartWps, ErrCode(const WpsConfig &config)); + MOCK_CONST_METHOD0(CancelWps, ErrCode()); + MOCK_CONST_METHOD1(SetCountryCode, ErrCode(const std::string &countryCode)); + MOCK_METHOD1(AutoConnectService, ErrCode(const std::vector &scanInfos)); + MOCK_CONST_METHOD1(RegisterStaServiceCallback, void(const StaServiceCallback &callbacks)); +}; +} // namespace OHOS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.cpp new file mode 100644 index 000000000..637183f4f --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.cpp @@ -0,0 +1,64 @@ +/* + * 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 "mock_sta_state_machine.h" +#include "wifi_logger.h" + +DEFINE_WIFILOG_LABEL("MockStaStateMachine"); + +namespace OHOS { +namespace Wifi { +void MockStaStateMachine::SendMessage(int msgName) +{ + WIFI_LOGD("MockStaStateMachine::SendMessage, msgName is %{public}d.", msgName); +} + +void MockStaStateMachine::SendMessage(int msgName, int param1) +{ + WIFI_LOGD("MockStaStateMachine::SendMessage, msgName is %{public}d, param1 is %{public}d.", msgName, param1); +} + +void MockStaStateMachine::SendMessage(int msgName, int param1, int param2) +{ + WIFI_LOGD("MockStaStateMachine::SendMessage, msgName is %{public}d, param1 is %{public}d, param2 is %{public}d.", + msgName, param1, param2); +} + +void MockStaStateMachine::SendMessage(InternalMessage *msg) +{ + if (msg == nullptr) { + return; + } + WIFI_LOGD("MockStaStateMachine::SendMessage, msg is %{public}d.", msg->GetMessageName()); +} + +void MockStaStateMachine::SendMessage(int msgName, const std::any &messageObj) +{ + (void)messageObj; + WIFI_LOGD("MockStaStateMachine::SendMessage, msgName is %{public}d.", msgName); +} + +void MockStaStateMachine::SendMessage(int msgName, int param1, int param2, const std::any &messageObj) +{ + (void)messageObj; + WIFI_LOGD("MockStaStateMachine::SendMessage, msgName is %{public}d, param1 is %{public}d, param2 is %{public}d.", + msgName, param1, param2); +} + +void MockStaStateMachine::StartRoamToNetwork(std::string bssid) +{ + WIFI_LOGD("MockStaStateMachine::StartRoamToNetwork, bssid is %{private}s.", bssid.c_str()); +} +} // namespace Wifi +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.h new file mode 100644 index 000000000..b7d4b6792 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.h @@ -0,0 +1,37 @@ +/* + * 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_STASTATEMACHINE_H +#define OHOS_MOCK_STASTATEMACHINE_H + +#include +#include "sta_state_machine.h" + +namespace OHOS { +namespace Wifi { +class MockStaStateMachine : public StaStateMachine { +public: + MockStaStateMachine() {} + ~MockStaStateMachine() {} + void SendMessage(int msgName); + void SendMessage(int msgName, int param1); + void SendMessage(int msgName, int param1, int param2); + void SendMessage(InternalMessage *msg); + void SendMessage(int msgName, const std::any &messageObj); + void SendMessage(int msgName, int param1, int param2, const std::any &messageObj); + void StartRoamToNetwork(std::string bssid); +}; +} // namespace OHOS +} // namespace Wifi +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.cpp new file mode 100644 index 000000000..8b2cd3745 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.cpp @@ -0,0 +1,25 @@ +/* + * 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 "mock_wifi_chip_hal_interface.h" + +namespace OHOS { +namespace Wifi { +WifiChipHalInterface &WifiChipHalInterface::GetInstance(void) +{ + static WifiChipHalInterface init; + return init; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.h new file mode 100644 index 000000000..07a25e39e --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.h @@ -0,0 +1,62 @@ +/* + * 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_WIFI_CHIP_HAL_INTERFACE_H +#define OHOS_MOCK_WIFI_CHIP_HAL_INTERFACE_H + +#include +#include +#include "sta_state_machine.h" +#include "wifi_error_no.h" +#include "i_wifi_struct.h" +#include "wifi_chip_event_callback.h" + +namespace OHOS { +namespace Wifi { +class MockWifiChipHalInterface { +public: + virtual ~MockWifiChipHalInterface() = default; + virtual WifiErrorNo GetWifiChipObject(int id, IWifiChip &chip) = 0; + virtual WifiErrorNo GetChipIds(std::vector &ids) = 0; + virtual WifiErrorNo GetUsedChipId(int &id) = 0; + virtual WifiErrorNo GetChipCapabilities(int &capabilities) = 0; + virtual WifiErrorNo GetSupportedModes(std::vector &modes) = 0; + virtual WifiErrorNo ConfigRunModes(int mode) = 0; + virtual WifiErrorNo GetCurrentMode(int &mode) = 0; + virtual WifiErrorNo RegisterChipEventCallback(WifiChipEventCallback &callback) = 0; + virtual WifiErrorNo RequestFirmwareDebugInfo(std::string &debugInfo) = 0; + virtual WifiErrorNo SetWifiPowerMode(int mode) = 0; + virtual WifiErrorNo GetChipIfaceFactoryMacAddress(const std::string &ifaceName, std::string &macAddress) = 0; +}; + +class WifiChipHalInterface : public MockWifiChipHalInterface { +public: + static WifiChipHalInterface &GetInstance(void); + + MOCK_METHOD2(GetWifiChipObject, WifiErrorNo(int id, IWifiChip &chip)); + MOCK_METHOD1(GetChipIds, WifiErrorNo(std::vector &ids)); + MOCK_METHOD1(GetUsedChipId, WifiErrorNo(int &id)); + MOCK_METHOD1(GetChipCapabilities, WifiErrorNo(int &capabilities)); + MOCK_METHOD1(GetSupportedModes, WifiErrorNo(std::vector &modes)); + MOCK_METHOD1(ConfigRunModes, WifiErrorNo(int mode)); + MOCK_METHOD1(GetCurrentMode, WifiErrorNo(int &mode)); + MOCK_METHOD1(RegisterChipEventCallback, WifiErrorNo(WifiChipEventCallback &callback)); + MOCK_METHOD1(RequestFirmwareDebugInfo, WifiErrorNo(std::string &debugInfo)); + MOCK_METHOD1(SetWifiPowerMode, WifiErrorNo(int mode)); + MOCK_METHOD2(GetChipIfaceFactoryMacAddress, WifiErrorNo(const std::string &ifaceName, std::string &macAddress)); +}; +} // namespace OHOS +} // namespace Wifi + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.cpp new file mode 100644 index 000000000..96ae8b876 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.cpp @@ -0,0 +1,47 @@ +/* + * 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 "mock_wifi_manager.h" + +namespace OHOS { +namespace Wifi { +WifiManager &WifiManager::GetInstance() +{ + static WifiManager gWifiManager; + return gWifiManager; +} + +WifiManager::WifiManager() +{ + InitStaCallback(); +} + +StaServiceCallback WifiManager::GetStaCallback() +{ + return mStaCallback; +} + +void WifiManager::InitStaCallback(void) +{ + using namespace std::placeholders; + mStaCallback.OnStaOpenRes = std::bind(&WifiManager::DealStaOpenRes, this, _1); + mStaCallback.OnStaCloseRes = std::bind(&WifiManager::DealStaCloseRes, this, _1); + mStaCallback.OnStaConnChanged = std::bind(&WifiManager::DealStaConnChanged, this, _1, _2); + mStaCallback.OnWpsChanged = std::bind(&WifiManager::DealWpsChanged, this, _1, _2); + mStaCallback.OnStaStreamChanged = std::bind(&WifiManager::DealStreamChanged, this, _1); + mStaCallback.OnStaRssiLevelChanged = std::bind(&WifiManager::DealRssiChanged, this, _1); + return; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.h new file mode 100644 index 000000000..bc33b647c --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.h @@ -0,0 +1,53 @@ +/* + * 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_WIFI_STA_MANAGER_H +#define OHOS_MOCK_WIFI_STA_MANAGER_H + +#include +#include "sta_service_callback.h" + +namespace OHOS { +namespace Wifi { +class MockWifiManager { +public: + virtual ~MockWifiManager() = default; + virtual void DealStaOpenRes(OperateResState state) = 0; + virtual void DealStaCloseRes(OperateResState state) = 0; + virtual void DealStaConnChanged(OperateResState state, const WifiLinkedInfo &info) = 0; + virtual void DealWpsChanged(WpsStartState state, const int pinCode) = 0; + virtual void DealStreamChanged(StreamDirection state) = 0; + virtual void DealRssiChanged(int rssi) = 0; +}; + +class WifiManager : public MockWifiManager { +public: + WifiManager(); + ~WifiManager() = default; + static WifiManager &GetInstance(); + StaServiceCallback GetStaCallback(); + MOCK_METHOD1(DealStaOpenRes, void(OperateResState state)); + MOCK_METHOD1(DealStaCloseRes, void(OperateResState state)); + MOCK_METHOD2(DealStaConnChanged, void(OperateResState type, const WifiLinkedInfo &info)); + MOCK_METHOD2(DealWpsChanged, void(WpsStartState state, const int pinCode)); + MOCK_METHOD1(DealStreamChanged, void(StreamDirection state)); + MOCK_METHOD1(DealRssiChanged, void(int rssi)); +private: + StaServiceCallback mStaCallback; + void InitStaCallback(void); +}; +} // namespace OHOS +} // namespace Wifi + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.cpp new file mode 100644 index 000000000..80bb67d0d --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.cpp @@ -0,0 +1,25 @@ +/* + * 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 "mock_wifi_settings.h" + +namespace OHOS { +namespace Wifi { + WifiSettings &WifiSettings::GetInstance(void) + { + static WifiSettings inst; + return inst; + } +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.h new file mode 100644 index 000000000..eb1aa29b2 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.h @@ -0,0 +1,121 @@ +/* + * 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_WIFISETTINGS_H +#define OHOS_MOCK_WIFISETTINGS_H + +#include "wifi_msg.h" +#include +#include "wifi_internal_msg.h" + +namespace OHOS { +namespace Wifi { +class MockWifiSettings { +public: + virtual ~MockWifiSettings() = default; + virtual int SetWifiState(int state) = 0; + virtual int AddDeviceConfig(const WifiDeviceConfig &config) = 0; + virtual int RemoveDevice(int networkId) = 0; + virtual void ClearDeviceConfig() = 0; + virtual int GetDeviceConfig(std::vector &results) = 0; + virtual int GetDeviceConfig(const int &networkId, WifiDeviceConfig &config) = 0; + virtual int GetDeviceConfig(const std::string &ssid, const std::string &keymgmt, WifiDeviceConfig &config) = 0; + virtual int GetDeviceConfig(const std::string &index, const int &indexType, WifiDeviceConfig &config) = 0; + virtual int SetDeviceState(int networkId, int state, bool bSetOther = false) = 0; + virtual int SyncDeviceConfig() = 0; + virtual int ReloadDeviceConfig() = 0; + virtual int GetIpInfo(IpInfo &info) = 0; + virtual int SaveIpInfo(const IpInfo &info) = 0; + virtual int GetLinkedInfo(WifiLinkedInfo &info) = 0; + virtual int SaveLinkedInfo(const WifiLinkedInfo &info) = 0; + virtual int SetMacAddress(const std::string &macAddress) = 0; + virtual int GetMacAddress(std::string &macAddress) = 0; + virtual int SetCountryCode(const std::string &countryCode) = 0; + virtual int GetCountryCode(std::string &countryCode) = 0; + virtual int GetSignalLevel(const int &rssi, const int &band) = 0; + virtual bool EnableNetwork(int networkId, bool disableOthers) = 0; + virtual void SetUserLastSelectedNetworkId(int networkId) = 0; + virtual int GetUserLastSelectedNetworkId() = 0; + virtual time_t GetUserLastSelectedNetworkTimeVal() = 0; + virtual int GetDhcpIpType() = 0; + virtual int SetDhcpIpType(int dhcpIpType) = 0; + virtual int SetWhetherToAllowNetworkSwitchover(bool bSwitch) = 0; + virtual bool GetWhetherToAllowNetworkSwitchover() = 0; + virtual int AddWpsDeviceConfig(const WifiDeviceConfig &config) = 0; + + virtual int GetSavedDeviceAppraisalPriority() = 0; + virtual int GetExternDeviceAppraisalPriority() = 0; + virtual int GetScoretacticsScoreSlope() = 0; + virtual int GetScoretacticsInitScore() = 0; + virtual int GetScoretacticsSameBssidScore() = 0; + virtual int GetScoretacticsSameNetworkScore() = 0; + virtual int GetScoretacticsFrequency5GHzScore() = 0; + virtual int GetScoretacticsLastSelectionScore() = 0; + virtual int GetScoretacticsSecurityScore() = 0; + virtual std::string GetStrDnsBak() const = 0; + virtual int GetScanInfoList(std::vector &results) = 0; +}; + +class WifiSettings : public MockWifiSettings { +public: + WifiSettings() = default; + ~WifiSettings() = default; + static WifiSettings &GetInstance(void); + + MOCK_METHOD1(SetWifiState, int(int state)); + MOCK_METHOD1(AddDeviceConfig, int(const WifiDeviceConfig &config)); + MOCK_METHOD1(RemoveDevice, int(int networkId)); + MOCK_METHOD0(ClearDeviceConfig, void()); + MOCK_METHOD1(GetDeviceConfig, int(std::vector &results)); + MOCK_METHOD2(GetDeviceConfig, int(const int &networkId, WifiDeviceConfig &config)); + MOCK_METHOD3(GetDeviceConfig, int(const std::string &ssid, const std::string &keymgmt, WifiDeviceConfig &config)); + MOCK_METHOD3(GetDeviceConfig, int(const std::string &index, const int &indexType, WifiDeviceConfig &config)); + MOCK_METHOD3(SetDeviceState, int(int networkId, int state, bool bSetOther)); + MOCK_METHOD0(SyncDeviceConfig, int()); + MOCK_METHOD0(ReloadDeviceConfig, int()); + MOCK_METHOD1(GetIpInfo, int(IpInfo &info)); + MOCK_METHOD1(SaveIpInfo, int(const IpInfo &info)); + MOCK_METHOD1(GetLinkedInfo, int(WifiLinkedInfo &info)); + MOCK_METHOD1(SaveLinkedInfo, int(const WifiLinkedInfo &info)); + MOCK_METHOD1(SetMacAddress, int(const std::string &macAddress)); + MOCK_METHOD1(GetMacAddress, int(std::string &macAddress)); + MOCK_METHOD1(SetCountryCode, int(const std::string &countryCode)); + MOCK_METHOD1(GetCountryCode, int(std::string &countryCode)); + MOCK_METHOD2(GetSignalLevel, int(const int &rssi, const int &band)); + MOCK_METHOD2(EnableNetwork, bool(int networkId, bool disableOthers)); + MOCK_METHOD1(SetUserLastSelectedNetworkId, void(int networkId)); + MOCK_METHOD0(GetUserLastSelectedNetworkId, int()); + MOCK_METHOD0(GetUserLastSelectedNetworkTimeVal, time_t()); + MOCK_METHOD0(GetDhcpIpType, int()); + MOCK_METHOD1(SetDhcpIpType, int(int dhcpIpType)); + MOCK_METHOD1(SetWhetherToAllowNetworkSwitchover, int(bool bSwitch)); + MOCK_METHOD0(GetWhetherToAllowNetworkSwitchover, bool()); + MOCK_METHOD1(AddWpsDeviceConfig, int(const WifiDeviceConfig &config)); + + MOCK_METHOD0(GetSavedDeviceAppraisalPriority, int()); + MOCK_METHOD0(GetExternDeviceAppraisalPriority, int()); + MOCK_METHOD0(GetScoretacticsScoreSlope, int()); + MOCK_METHOD0(GetScoretacticsInitScore, int()); + MOCK_METHOD0(GetScoretacticsSameBssidScore, int()); + MOCK_METHOD0(GetScoretacticsSameNetworkScore, int()); + MOCK_METHOD0(GetScoretacticsFrequency5GHzScore, int()); + MOCK_METHOD0(GetScoretacticsLastSelectionScore, int()); + MOCK_METHOD0(GetScoretacticsSecurityScore, int()); + MOCK_CONST_METHOD0(GetStrDnsBak, std::string()); + MOCK_METHOD1(GetScanInfoList, int(std::vector &results)); +}; +} // namespace OHOS +} // namespace Wifi + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.cpp new file mode 100644 index 000000000..1bb828e3b --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.cpp @@ -0,0 +1,25 @@ +/* + * 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 "mock_wifi_sta_hal_interface.h" + +namespace OHOS { +namespace Wifi { + WifiStaHalInterface &WifiStaHalInterface::GetInstance(void) + { + static WifiStaHalInterface inst; + return inst; + } +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.h new file mode 100644 index 000000000..e43e76e3a --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.h @@ -0,0 +1,109 @@ +/* + * 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_WIFISTAHALINTERFACE_H +#define OHOS_MOCK_WIFISTAHALINTERFACE_H + +#include +#include +#include +#include +#include "wifi_msg.h" +#include "wifi_error_no.h" +#include "wifi_idl_struct.h" +#include "wifi_sta_request.h" +#include "wifi_event_callback.h" + +namespace OHOS { +namespace Wifi { +class MockWifiStaHalInterface { +public: + virtual ~MockWifiStaHalInterface() = default; + virtual WifiErrorNo StartWifi() = 0; + virtual WifiErrorNo StopWifi() = 0; + virtual WifiErrorNo Connect(int networkId) = 0; + virtual WifiErrorNo Reconnect() = 0; + virtual WifiErrorNo Reassociate() = 0; + virtual WifiErrorNo Disconnect() = 0; + virtual WifiErrorNo GetStaCapabilities(unsigned int &capabilities) = 0; + virtual WifiErrorNo GetStaDeviceMacAddress(std::string &mac) = 0; + virtual WifiErrorNo GetSupportFrequencies(int band, std::vector &frequencies) = 0; + virtual WifiErrorNo SetConnectMacAddr(const std::string &mac) = 0; + virtual WifiErrorNo SetScanMacAddress(const std::string &mac) = 0; + virtual WifiErrorNo DisconnectLastRoamingBssid(const std::string &mac) = 0; + virtual WifiErrorNo GetSupportFeature(long &feature) = 0; + virtual WifiErrorNo SendRequest(const WifiStaRequest &request) = 0; + virtual WifiErrorNo SetTxPower(int power) = 0; + virtual WifiErrorNo RemoveDevice(int networkId) = 0; + virtual WifiErrorNo ClearDeviceConfig() const = 0; + virtual WifiErrorNo GetNextNetworkId(int &networkId) = 0; + virtual WifiErrorNo EnableNetwork(int networkId) = 0; + virtual WifiErrorNo DisableNetwork(int networkId) = 0; + virtual WifiErrorNo SetDeviceConfig(int networkId, const WifiIdlDeviceConfig &config) = 0; + virtual WifiErrorNo GetDeviceConfig(WifiIdlGetDeviceConfig &config) = 0; + virtual WifiErrorNo SaveDeviceConfig() = 0; + virtual WifiErrorNo RegisterStaEventCallback(const WifiEventCallback &callback) = 0; + virtual WifiErrorNo StartWpsPbcMode(const WifiIdlWpsConfig &config) = 0; + virtual WifiErrorNo StartWpsPinMode(const WifiIdlWpsConfig &config, int &pinCode) = 0; + virtual WifiErrorNo StopWps() = 0; + virtual WifiErrorNo GetRoamingCapabilities(WifiIdlRoamCapability &capability) = 0; + virtual WifiErrorNo SetRoamConfig(const WifiIdlRoamConfig &config) = 0; + virtual WifiErrorNo WpaAutoConnect(int enable) = 0; + virtual WifiErrorNo WpaBlocklistClear() = 0; + virtual WifiErrorNo GetNetworkList(std::vector &networkList) = 0; + virtual WifiErrorNo GetConnectSignalInfo(const std::string &endBssid, WifiWpaSignalInfo &info) = 0; +}; + +class WifiStaHalInterface : public MockWifiStaHalInterface { +public: + static WifiStaHalInterface &GetInstance(void); + +public: + MOCK_METHOD0(StartWifi, WifiErrorNo()); + MOCK_METHOD0(StopWifi, WifiErrorNo()); + MOCK_METHOD1(Connect, WifiErrorNo(int networkId)); + MOCK_METHOD0(Reconnect, WifiErrorNo()); + MOCK_METHOD0(Reassociate, WifiErrorNo()); + MOCK_METHOD0(Disconnect, WifiErrorNo()); + MOCK_METHOD1(GetStaCapabilities, WifiErrorNo(unsigned int &capabilities)); + MOCK_METHOD1(GetStaDeviceMacAddress, WifiErrorNo(std::string &mac)); + MOCK_METHOD2(GetSupportFrequencies, WifiErrorNo(int band, std::vector &frequencies)); + MOCK_METHOD1(SetConnectMacAddr, WifiErrorNo(const std::string &mac)); + MOCK_METHOD1(SetScanMacAddress, WifiErrorNo(const std::string &mac)); + MOCK_METHOD1(DisconnectLastRoamingBssid, WifiErrorNo(const std::string &mac)); + MOCK_METHOD1(GetSupportFeature, WifiErrorNo(long &feature)); + MOCK_METHOD1(SendRequest, WifiErrorNo(const WifiStaRequest &request)); + MOCK_METHOD1(SetTxPower, WifiErrorNo(int power)); + MOCK_METHOD1(RemoveDevice, WifiErrorNo(int networkId)); + MOCK_CONST_METHOD0(ClearDeviceConfig, WifiErrorNo()); + MOCK_METHOD1(GetNextNetworkId, WifiErrorNo(int &networkId)); + MOCK_METHOD1(EnableNetwork, WifiErrorNo(int networkId)); + MOCK_METHOD1(DisableNetwork, WifiErrorNo(int networkId)); + MOCK_METHOD2(SetDeviceConfig, WifiErrorNo(int networkId, const WifiIdlDeviceConfig &config)); + MOCK_METHOD1(GetDeviceConfig, WifiErrorNo(WifiIdlGetDeviceConfig &config)); + MOCK_METHOD0(SaveDeviceConfig, WifiErrorNo()); + MOCK_METHOD1(RegisterStaEventCallback, WifiErrorNo(const WifiEventCallback &callback)); + MOCK_METHOD1(StartWpsPbcMode, WifiErrorNo(const WifiIdlWpsConfig &config)); + MOCK_METHOD2(StartWpsPinMode, WifiErrorNo(const WifiIdlWpsConfig &config, int &pinCode)); + MOCK_METHOD0(StopWps, WifiErrorNo()); + MOCK_METHOD1(GetRoamingCapabilities, WifiErrorNo(WifiIdlRoamCapability &capability)); + MOCK_METHOD1(SetRoamConfig, WifiErrorNo(const WifiIdlRoamConfig &config)); + MOCK_METHOD1(WpaAutoConnect, WifiErrorNo(int enable)); + MOCK_METHOD0(WpaBlocklistClear, WifiErrorNo()); + MOCK_METHOD1(GetNetworkList, WifiErrorNo(std::vector &networkList)); + MOCK_METHOD2(GetConnectSignalInfo, WifiErrorNo(const std::string &endBssid, WifiWpaSignalInfo &info)); +}; +} // namespace OHOS +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.cpp new file mode 100644 index 000000000..b240296b5 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.cpp @@ -0,0 +1,25 @@ +/* + * 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 "mock_wifi_supplicant_hal_interface.h" + +namespace OHOS { +namespace Wifi { + WifiSupplicantHalInterface &WifiSupplicantHalInterface::GetInstance(void) + { + static WifiSupplicantHalInterface inst; + return inst; + } +} // namespace Wifi +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.h new file mode 100644 index 000000000..8b2f9ab65 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.h @@ -0,0 +1,43 @@ +/* + * 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_WIFISUPPLICANTHALINTERFACE_H +#define OHOS_MOCK_WIFISUPPLICANTHALINTERFACE_H + +#include +#include +#include "wifi_error_no.h" +#include "i_wifi_struct.h" + +namespace OHOS { +namespace Wifi { +class MockWifiSupplicantHalInterface { +public: + virtual ~MockWifiSupplicantHalInterface() = default; + virtual WifiErrorNo StartSupplicant(void) = 0; + virtual WifiErrorNo WpaSetCountryCode(const std::string &countryCode) const = 0; + +}; + +class WifiSupplicantHalInterface : public MockWifiSupplicantHalInterface { +public: + static WifiSupplicantHalInterface &GetInstance(void); + +public: + MOCK_METHOD0(StartSupplicant, WifiErrorNo()); + MOCK_CONST_METHOD1(WpaSetCountryCode, WifiErrorNo(const std::string &countryCode)); +}; +} // namespace OHOS +} // namespace OHOS +#endif diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.cpp new file mode 100644 index 000000000..580444d60 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.cpp @@ -0,0 +1,23 @@ +/* + * 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"global_test.h" +void GlobalTest::SetUp() +{ + printf("GlobalTest SetUp\n"); +} +void GlobalTest::TearDown() +{ + printf("GlobalTest TearDown\n"); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.h new file mode 100644 index 000000000..d3b34fd84 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.h @@ -0,0 +1,25 @@ +/* + * 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 GLOBAL_TEST_H +#define GLOBAL_TEST_H +#include +class GlobalTest:public testing::Environment +{ +public: + virtual void SetUp(); + virtual void TearDown(); +}; +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service_test.cpp new file mode 100644 index 000000000..e0c4c8d80 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service_test.cpp @@ -0,0 +1,1710 @@ +/* + * 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 "sta_auto_connect_service.h" +#include "mock_sta_state_machine.h" +#include "mock_wifi_sta_hal_interface.h" +#include "mock_wifi_settings.h" +#include "mock_device_appraisal.h" +#include +#include + +#include "wifi_errcode.h" +#include "wifi_internal_msg.h" +#include "wifi_msg.h" +#include "sta_device_appraisal.h" +#include "wifi_idl_struct.h" +#include "wifi_error_no.h" + +using ::testing::_; +using ::testing::AtLeast; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::StrEq; +using ::testing::TypedEq; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +constexpr int NETWORK_ID = 15; +constexpr int BAND = 2; +constexpr int RSSI = 8; +constexpr int SMALLER_THAN_RSSI_DELIMITING_VALUE = -66; + +class StaAutoConnectServiceTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + virtual void SetUp() + { + pStaStateMachine = new (std::nothrow) MockStaStateMachine(); + pStaAutoConnectService = new (std::nothrow) StaAutoConnectService(pStaStateMachine); + pMockDeviceAppraisal = new (std::nothrow) MockDeviceAppraisal(); + InitAutoConnectService(); + } + virtual void TearDown() + { + if (pStaStateMachine != nullptr) { + delete pStaStateMachine; + pStaStateMachine = nullptr; + } + + if (pStaAutoConnectService != nullptr) { + delete pStaAutoConnectService; + pStaAutoConnectService = nullptr; + } + + if (pMockDeviceAppraisal != nullptr) { + delete pMockDeviceAppraisal; + pMockDeviceAppraisal = nullptr; + } + } + +public: + StaStateMachine *pStaStateMachine; + StaAutoConnectService *pStaAutoConnectService; + MockDeviceAppraisal *pMockDeviceAppraisal; + +public: + void InitAutoConnectService(); + void GetScanInfoConfig(InterScanInfo &scanInfo) const; + void GetWifiDeviceConfig(WifiDeviceConfig &deviceConfig) const; + void GetInterScanInfoVector(std::vector &scanInfos) const; + void GetWifiLinkedInfo(WifiLinkedInfo &info); + void GetAllDeviceInfos(WifiDeviceConfig &deviceConfig, std::vector &scanInfos, + std::vector &blockedBssids, WifiLinkedInfo &info); + + void InitAutoConnectServiceSuccess(); + void ClearSecondaryStateMachinePtrSuccess(); + void OnScanResultsReadyHandlerSuccess1(); + void OnScanResultsReadyHandlerSuccess2(); + void OnScanResultsReadyHandlerSuccess3(); + void OnScanResultsReadyHandlerFail1(); + void OnScanResultsReadyHandlerFail2(); + void OnScanResultsReadyHandlerFail3(); + void OnScanResultsReadyHandlerFail4(); + void OnScanResultsReadyHandlerFail5(); + void OnScanResultsReadyHandlerFail6(); + void OnScanResultsReadyHandlerFail7(); + void EnableOrDisableBssidSuccess1(); + void EnableOrDisableBssidSuccess2(); + void EnableOrDisableBssidFail1(); + void EnableOrDisableBssidFail2(); + void EnableOrDisableBssidFail3(); + void EnableOrDisableBssidFail4(); + void AutoSelectDeviceSuccess1(); + void AutoSelectDeviceSuccess2(); + void AutoSelectDeviceSuccess3(); + void AutoSelectDeviceFail1(); + void AutoSelectDeviceFail2(); + void AutoSelectDeviceFail3(); + void AutoSelectDeviceFail4(); + void AutoSelectDeviceFail5(); + void AutoSelectDeviceFail6(); + void RegisterDeviceAppraisalSuccess(); + void RegisterDeviceAppraisalFail1(); + void RegisterDeviceAppraisalFail2(); + void ClearOvertimeBlockedBssidSuccess1(); + void ClearOvertimeBlockedBssidSuccess2(); + void GetBlockedBssidsSuccess(); + void AddOrDelBlockedBssidsSuccess(); + void AddOrDelBlockedBssidsFail(); + void ObtainRoamCapFromFirmwareSuccess(); + void ObtainRoamCapFromFirmwareFail1(); + void ObtainRoamCapFromFirmwareFail2(); + void SetRoamBlockedBssidFirmwareSuccess(); + void SetRoamBlockedBssidFirmwareFail1(); + void SetRoamBlockedBssidFirmwareFail2(); + void SetRoamBlockedBssidFirmwareFail3(); + void SetRoamBlockedBssidFirmwareFail4(); + void ConnectElectedDeviceSuccess1(); + void ConnectElectedDeviceSuccess2(); + void ConnectElectedDeviceFail1(); + void GetAvailableScanInfosSuccess(); + void AllowAutoSelectDeviceSuccess1(); + void AllowAutoSelectDeviceSuccess2(); + void AllowAutoSelectDeviceSuccess3(); + void AllowAutoSelectDeviceFail1(); + void AllowAutoSelectDeviceFail2(); + void AllowAutoSelectDeviceFail3(); + void AllowAutoSelectDeviceFail4(); + void CurrentDeviceGoodEnoughSuccess(); + void CurrentDeviceGoodEnoughFail1(); + void CurrentDeviceGoodEnoughFail2(); + void CurrentDeviceGoodEnoughFail3(); + void CurrentDeviceGoodEnoughFail4(); + void CurrentDeviceGoodEnoughFail5(); + void WhetherDevice5GAvailableSuccess(); + void WhetherDevice5GAvailableFail(); + void RoamingEncryptionModeCheckSuccess(); + void RoamingEncryptionModeCheckFail1(); + void RoamingEncryptionModeCheckFail2(); + void RoamingEncryptionModeCheckFail3(); + void RoamingEncryptionModeCheckFail4(); + void RefreshConfigDeviceSuccess(); + void RoamingSelectionSuccess1(); + void RoamingSelectionFail1(); + void RoamingSelectionFail2(); + void RoamingSelectionFail3(); + void RoamingSelectionFail4(); + void SyncBlockedSsidFirmwareSuccess(); + void SyncBlockedSsidFirmwareFail(); +}; + +void StaAutoConnectServiceTest::InitAutoConnectService() +{ + WifiIdlRoamCapability capability; + capability.maxBlocklistSize = 2; + + EXPECT_CALL(WifiStaHalInterface::GetInstance(), RegisterStaEventCallback(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartWifi()).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), WpaAutoConnect(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetStaDeviceMacAddress(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetStaCapabilities(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsScoreSlope()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsInitScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsSameBssidScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsSameNetworkScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsFrequency5GHzScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsLastSelectionScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsSecurityScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetSavedDeviceAppraisalPriority()).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetExternDeviceAppraisalPriority()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ReloadDeviceConfig()).Times(AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), ClearDeviceConfig()).Times(AtLeast(0)); + + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetRoamingCapabilities(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(capability), Return(WIFI_IDL_OPT_OK))); + + pStaAutoConnectService->InitAutoConnectService(); + for (int i = 0; i < MAX_APPRAISAL_NUM; i++) { + pStaAutoConnectService->pAppraisals[i] = nullptr; + } + pStaAutoConnectService->pAppraisals[0] = pMockDeviceAppraisal; +} + +void StaAutoConnectServiceTest::GetScanInfoConfig(InterScanInfo &scanInfo) const +{ + scanInfo.bssid = "2a:76:93:47:e2:8a"; + scanInfo.ssid = "HMWIFI_W2_EAP_G2_03"; + scanInfo.band = NETWORK_ID; + scanInfo.rssi = RSSI; + scanInfo.securityType = WifiSecurity::OPEN; +} + +void StaAutoConnectServiceTest::GetWifiDeviceConfig(WifiDeviceConfig &deviceConfig) const +{ + deviceConfig.bssid = "2a:76:93:47:e2:8a"; + deviceConfig.band = BAND; + deviceConfig.networkId = NETWORK_ID; + deviceConfig.ssid = "HMWIFI_W2_EAP_G2_03"; + deviceConfig.keyMgmt = "123456"; +} + +void StaAutoConnectServiceTest::GetInterScanInfoVector(std::vector &scanInfos) const +{ + InterScanInfo scanInfo; + GetScanInfoConfig(scanInfo); + scanInfos.push_back(scanInfo); +} + +void StaAutoConnectServiceTest::GetWifiLinkedInfo(WifiLinkedInfo &info) +{ + info.detailedState = DetailedState::WORKING; // WORKING + info.bssid = "2a:76:93:47:e2:8a"; + info.ssid = "HMWIFI_W2_EAP_G2_03"; + info.networkId = NETWORK_ID; + info.connState = ConnState::CONNECTED; +} + +void StaAutoConnectServiceTest::GetAllDeviceInfos(WifiDeviceConfig &deviceConfig, std::vector &scanInfos, + std::vector &blockedBssids, WifiLinkedInfo &info) +{ + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + pStaAutoConnectService->GetBlockedBssids(blockedBssids); + GetWifiLinkedInfo(info); +} + +void StaAutoConnectServiceTest::InitAutoConnectServiceSuccess() +{ + EXPECT_CALL(WifiStaHalInterface::GetInstance(), RegisterStaEventCallback(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartWifi()).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), WpaAutoConnect(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetStaDeviceMacAddress(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsScoreSlope()) + .Times(AtLeast(1)) + .WillOnce(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsInitScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsSameBssidScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsSameNetworkScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsFrequency5GHzScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsLastSelectionScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsSecurityScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ReloadDeviceConfig()).Times(AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), ClearDeviceConfig()).Times(AtLeast(0)); + + int capabilities = 1; + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetStaCapabilities(_)) + .WillOnce(DoAll(SetArgReferee<0>(capabilities), Return(WIFI_IDL_OPT_OK))); + + WifiIdlRoamCapability capability; + capability.maxBlocklistSize = 2; + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetRoamingCapabilities(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(capability), Return(WIFI_IDL_OPT_OK))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetRoamConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetSavedDeviceAppraisalPriority()).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetExternDeviceAppraisalPriority()).Times(AtLeast(0)); + + EXPECT_TRUE(pStaAutoConnectService->InitAutoConnectService() == WIFI_OPT_SUCCESS); +} + +void StaAutoConnectServiceTest::OnScanResultsReadyHandlerSuccess1() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo infoPrimary, infoSecondary; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, infoPrimary); + + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(infoPrimary), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).WillOnce(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillRepeatedly(Return(-1)); // if it is false, it will do process. + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).WillOnce(Return(WIFI_OPT_SUCCESS)); + pStaAutoConnectService->OnScanInfosReadyHandler(scanInfos); +} + + +void StaAutoConnectServiceTest::OnScanResultsReadyHandlerSuccess2() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo infoPrimary, infoSecondary; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, infoPrimary); + infoPrimary.detailedState = DetailedState::DISCONNECTED; // DISCONNECTED + + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(infoPrimary), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).WillOnce(Return(WIFI_OPT_SUCCESS)); + + pStaAutoConnectService->OnScanInfosReadyHandler(scanInfos); +} + + +void StaAutoConnectServiceTest::OnScanResultsReadyHandlerSuccess3() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo infoPrimary, infoSecondary; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, infoPrimary); + infoPrimary.detailedState = DetailedState::NOTWORKING; // NOTWORKING + + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(infoPrimary), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()) + .Times(AtLeast(1)) + .WillOnce(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).WillOnce(Return(WIFI_OPT_SUCCESS)); + + pStaAutoConnectService->OnScanInfosReadyHandler(scanInfos); +} + +void StaAutoConnectServiceTest::OnScanResultsReadyHandlerFail1() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo infoPrimary, infoSecondary; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, infoPrimary); + + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(infoPrimary), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).WillOnce(Return(false)); + + pStaAutoConnectService->OnScanInfosReadyHandler(scanInfos); +} + +void StaAutoConnectServiceTest::OnScanResultsReadyHandlerFail2() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo infoPrimary, infoSecondary; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, infoPrimary); + + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(infoPrimary), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).WillOnce(Return(true)); + /* CurrentDeviceGoodEnough:: There is enough devices, so need not devices at start. */ + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillRepeatedly(Return(0)); // if it is true, it will do not process. + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()).Times(AtLeast(1)).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkTimeVal()).Times(AtLeast(0)); + EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).Times(AtLeast(0)); + pStaAutoConnectService->OnScanInfosReadyHandler(scanInfos); +} + +void StaAutoConnectServiceTest::OnScanResultsReadyHandlerFail3() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo infoPrimary, infoSecondary; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, infoPrimary); + + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(infoPrimary), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).WillOnce(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillRepeatedly(Return(-1)); // if it is false, it will do process. + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).WillOnce(Return(WIFI_OPT_FAILED)); + + pStaAutoConnectService->OnScanInfosReadyHandler(scanInfos); +} + +void StaAutoConnectServiceTest::OnScanResultsReadyHandlerFail4() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo infoPrimary, infoSecondary; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, infoPrimary); + infoPrimary.detailedState = DetailedState::DISCONNECTED; // DISCONNECTED + + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(infoPrimary), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).WillOnce(Return(WIFI_OPT_FAILED)); + + pStaAutoConnectService->OnScanInfosReadyHandler(scanInfos); +} + +void StaAutoConnectServiceTest::OnScanResultsReadyHandlerFail5() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo infoPrimary, infoSecondary; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, infoPrimary); + infoPrimary.detailedState = DetailedState::NOTWORKING; // NOTWORKING + + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(infoPrimary), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()) + .Times(AtLeast(1)) + .WillOnce(Return(false)); + + pStaAutoConnectService->OnScanInfosReadyHandler(scanInfos); +} + +void StaAutoConnectServiceTest::OnScanResultsReadyHandlerFail6() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo infoPrimary, infoSecondary; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, infoPrimary); + infoPrimary.detailedState = DetailedState::NOTWORKING; // NOTWORKING + + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(infoPrimary), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()) + .Times(AtLeast(1)) + .WillOnce(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(1)); + EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).WillOnce(Return(WIFI_OPT_FAILED)); + + pStaAutoConnectService->OnScanInfosReadyHandler(scanInfos); +} + + +void StaAutoConnectServiceTest::OnScanResultsReadyHandlerFail7() +{ + std::vector scanInfos; + WifiLinkedInfo infoPrimary, infoSecondary; + GetInterScanInfoVector(scanInfos); + infoPrimary.supplicantState = SupplicantState::ASSOCIATING; + + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)) + .WillOnce(DoAll(SetArgReferee<0>(infoPrimary), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + pStaAutoConnectService->OnScanInfosReadyHandler(scanInfos); +} + +void StaAutoConnectServiceTest::EnableOrDisableBssidSuccess1() +{ + std::string bssid = "d8:c7:71:2f:14:d9"; + + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetRoamConfig(_)).Times(AtLeast(0)); + EXPECT_TRUE(pStaAutoConnectService->EnableOrDisableBssid(bssid, false, AP_CANNOT_HANDLE_NEW_STA)); +} + +void StaAutoConnectServiceTest::EnableOrDisableBssidSuccess2() +{ + std::string bssid = "d8:c7:71:2f:14:d9"; + EXPECT_TRUE(pStaAutoConnectService->EnableOrDisableBssid(bssid, false, AP_CANNOT_HANDLE_NEW_STA)); + EXPECT_TRUE(pStaAutoConnectService->EnableOrDisableBssid(bssid, true, AP_CANNOT_HANDLE_NEW_STA)); +} + +void StaAutoConnectServiceTest::EnableOrDisableBssidFail1() +{ + std::string bssid = ""; + EXPECT_FALSE(pStaAutoConnectService->EnableOrDisableBssid(bssid, true, AP_CANNOT_HANDLE_NEW_STA)); +} + +void StaAutoConnectServiceTest::EnableOrDisableBssidFail2() +{ + std::string bssid = ""; + EXPECT_FALSE(pStaAutoConnectService->EnableOrDisableBssid(bssid, false, AP_CANNOT_HANDLE_NEW_STA)); +} + +void StaAutoConnectServiceTest::EnableOrDisableBssidFail3() +{ + std::string bssid = "d8:c7:71:2f:14:d9"; + EXPECT_FALSE(pStaAutoConnectService->EnableOrDisableBssid(bssid, true, AP_CANNOT_HANDLE_NEW_STA)); +} + +void StaAutoConnectServiceTest::EnableOrDisableBssidFail4() +{ + std::string bssid = "d8:c7:71:2f:14:d9"; + const int AP_CANNOT_HANDLE_NEW_STA_ERR = 1; + EXPECT_FALSE(pStaAutoConnectService->EnableOrDisableBssid(bssid, false, AP_CANNOT_HANDLE_NEW_STA_ERR)); +} + +void StaAutoConnectServiceTest::AutoSelectDeviceSuccess1() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo info; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, info); + + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).WillOnce(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillRepeatedly(Return(-1)); // if it is false, it will do process. + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).WillOnce(Return(WIFI_OPT_SUCCESS)); + + EXPECT_TRUE(pStaAutoConnectService->AutoSelectDevice(deviceConfig, scanInfos, blockedBssids, info) == + WIFI_OPT_SUCCESS); +} + +void StaAutoConnectServiceTest::AutoSelectDeviceSuccess2() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo info; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, info); + info.detailedState = DetailedState::DISCONNECTED; // DISCONNECTED + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).WillOnce(Return(WIFI_OPT_SUCCESS)); + + EXPECT_TRUE(pStaAutoConnectService->AutoSelectDevice(deviceConfig, scanInfos, blockedBssids, info) == + WIFI_OPT_SUCCESS); +} + + +void StaAutoConnectServiceTest::AutoSelectDeviceSuccess3() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo info; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, info); + info.detailedState = DetailedState::NOTWORKING; // NOTWORKING + + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()) + .Times(AtLeast(1)) + .WillOnce(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).WillOnce(Return(WIFI_OPT_SUCCESS)); + + EXPECT_TRUE(pStaAutoConnectService->AutoSelectDevice(deviceConfig, scanInfos, blockedBssids, info) == + WIFI_OPT_SUCCESS); +} + +void StaAutoConnectServiceTest::AutoSelectDeviceFail1() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo info; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, info); + + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).WillOnce(Return(false)); + + EXPECT_TRUE(pStaAutoConnectService->AutoSelectDevice(deviceConfig, scanInfos, blockedBssids, info) == + WIFI_OPT_FAILED); +} + +void StaAutoConnectServiceTest::AutoSelectDeviceFail2() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo info; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, info); + + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).WillOnce(Return(true)); + /* CurrentDeviceGoodEnough:: There is enough devices, so need not devices at start. */ + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(deviceConfig), Return(0))); // if it is true, it will do not process. + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()).Times(AtLeast(0)).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkTimeVal()).Times(AtLeast(0)); + EXPECT_TRUE(pStaAutoConnectService->AutoSelectDevice(deviceConfig, scanInfos, blockedBssids, info) == + WIFI_OPT_FAILED); +} + + +void StaAutoConnectServiceTest::AutoSelectDeviceFail3() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo info; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, info); + + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).WillOnce(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillRepeatedly(Return(-1)); // if it is false, it will do process. + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).WillOnce(Return(WIFI_OPT_FAILED)); + + EXPECT_TRUE(pStaAutoConnectService->AutoSelectDevice(deviceConfig, scanInfos, blockedBssids, info) == + WIFI_OPT_FAILED); +} + +void StaAutoConnectServiceTest::AutoSelectDeviceFail4() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo info; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, info); + info.detailedState = DetailedState::DISCONNECTED; // DISCONNECTED + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).WillOnce(Return(WIFI_OPT_FAILED)); + + EXPECT_TRUE(pStaAutoConnectService->AutoSelectDevice(deviceConfig, scanInfos, blockedBssids, info) == + WIFI_OPT_FAILED); +} + +void StaAutoConnectServiceTest::AutoSelectDeviceFail5() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo info; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, info); + info.detailedState = DetailedState::NOTWORKING; // NOTWORKING + + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()) + .Times(AtLeast(1)) + .WillOnce(Return(false)); + + EXPECT_TRUE(pStaAutoConnectService->AutoSelectDevice(deviceConfig, scanInfos, blockedBssids, info) == + WIFI_OPT_FAILED); +} + +void StaAutoConnectServiceTest::AutoSelectDeviceFail6() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo info; + GetAllDeviceInfos(deviceConfig, scanInfos, blockedBssids, info); + info.detailedState = DetailedState::NOTWORKING; // NOTWORKING + + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()) + .Times(AtLeast(1)) + .WillOnce(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).WillOnce(Return(WIFI_OPT_FAILED)); + + EXPECT_TRUE(pStaAutoConnectService->AutoSelectDevice(deviceConfig, scanInfos, blockedBssids, info) == + WIFI_OPT_FAILED); +} + +void StaAutoConnectServiceTest::RegisterDeviceAppraisalSuccess() +{ + StaDeviceAppraisal *appraisal = nullptr; + int priority = 1; // 0~6 + EXPECT_TRUE(pStaAutoConnectService->RegisterDeviceAppraisal(appraisal, priority) == true); +} + +void StaAutoConnectServiceTest::RegisterDeviceAppraisalFail1() +{ + StaDeviceAppraisal *appraisal = nullptr; + int priority = -1; // 0~6 + EXPECT_TRUE(pStaAutoConnectService->RegisterDeviceAppraisal(appraisal, priority) == false); +} + + +void StaAutoConnectServiceTest::RegisterDeviceAppraisalFail2() +{ + StaDeviceAppraisal *appraisal = nullptr; + int priority = 7; // 0~6 + EXPECT_TRUE(pStaAutoConnectService->RegisterDeviceAppraisal(appraisal, priority) == false); +} + +void StaAutoConnectServiceTest::ClearOvertimeBlockedBssidSuccess1() +{ + pStaAutoConnectService->ClearOvertimeBlockedBssid(); +} + +void StaAutoConnectServiceTest::ClearOvertimeBlockedBssidSuccess2() +{ + std::string bssid = "2a:76:93:47:e2:8a"; + bool enable = false; + int reason = AP_CANNOT_HANDLE_NEW_STA; + pStaAutoConnectService->AddOrDelBlockedBssids(bssid, enable, reason); + pStaAutoConnectService->ClearOvertimeBlockedBssid(); +} + +void StaAutoConnectServiceTest::GetBlockedBssidsSuccess() +{ + std::vector blockedBssids; + std::string bssid = "2a:76:93:47:e2:8a"; + blockedBssids.push_back(bssid); + pStaAutoConnectService->GetBlockedBssids(blockedBssids); +} + +void StaAutoConnectServiceTest::AddOrDelBlockedBssidsSuccess() +{ + std::string bssid = "2a:76:93:47:e2:8a"; + bool enable = false; + int reason = AP_CANNOT_HANDLE_NEW_STA; + EXPECT_TRUE(pStaAutoConnectService->AddOrDelBlockedBssids(bssid, enable, reason) == true); +} + + +void StaAutoConnectServiceTest::AddOrDelBlockedBssidsFail() +{ + std::string bssid = "2a:76:93:47:e2:8a"; + bool enable = true; + int reason = AP_CANNOT_HANDLE_NEW_STA; + EXPECT_TRUE(pStaAutoConnectService->AddOrDelBlockedBssids(bssid, enable, reason) == false); +} + +void StaAutoConnectServiceTest::ObtainRoamCapFromFirmwareSuccess() +{ + WifiIdlRoamCapability capability; + capability.maxBlocklistSize = 2; + + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetStaCapabilities(_)) + .WillOnce(Return(WIFI_IDL_OPT_FAILED)); // if it is false, it will do process. + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetRoamingCapabilities(_)) + .WillOnce(DoAll(SetArgReferee<0>(capability), Return(WIFI_IDL_OPT_OK))); + EXPECT_TRUE(pStaAutoConnectService->ObtainRoamCapFromFirmware() == true); +} + +void StaAutoConnectServiceTest::ObtainRoamCapFromFirmwareFail1() +{ + unsigned int capabilities = 0; + + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetStaCapabilities(_)) + .WillOnce( + DoAll(SetArgReferee<0>(capabilities), Return(WIFI_IDL_OPT_OK))); // if it is true, it will do not process. + + EXPECT_TRUE(pStaAutoConnectService->ObtainRoamCapFromFirmware() == false); +} + + +void StaAutoConnectServiceTest::ObtainRoamCapFromFirmwareFail2() +{ + unsigned int capabilities = 0; + WifiIdlRoamCapability capability; + capability.maxBlocklistSize = 1; + + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetStaCapabilities(_)) + .WillOnce( + DoAll(SetArgReferee<0>(capabilities), Return(WIFI_IDL_OPT_FAILED))); // if it is true, it will do not process. + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetRoamingCapabilities(_)) + .WillOnce(DoAll(SetArgReferee<0>(capability), Return(WIFI_IDL_OPT_FAILED))); + + EXPECT_TRUE(pStaAutoConnectService->ObtainRoamCapFromFirmware() == false); +} + +void StaAutoConnectServiceTest::SetRoamBlockedBssidFirmwareSuccess() +{ + ObtainRoamCapFromFirmwareSuccess(); + std::vector blockedBssids; + std::string bssid = "2a:76:93:47:e2:8a"; + blockedBssids.push_back(bssid); + + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetRoamConfig(_)).WillOnce(Return(WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == true); +} + +void StaAutoConnectServiceTest::SetRoamBlockedBssidFirmwareFail1() +{ + std::vector blockedBssids; + std::string bssid = "2a:76:93:47:e2:8a"; + blockedBssids.push_back(bssid); + + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetRoamConfig(_)).WillOnce(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == false); +} + +void StaAutoConnectServiceTest::SetRoamBlockedBssidFirmwareFail2() +{ + ObtainRoamCapFromFirmwareSuccess(); + std::vector blockedBssids = {}; // NULL + EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == false); +} + +void StaAutoConnectServiceTest::SetRoamBlockedBssidFirmwareFail3() +{ + ObtainRoamCapFromFirmwareSuccess(); + std::vector blockedBssids; + std::string bssid1 = "2a:76:93:47:e2:8a"; + std::string bssid2 = "2a:76:93:47:e2:8a"; + std::string bssid3 = "2a:76:93:47:e2:8a"; + blockedBssids.push_back(bssid1); + blockedBssids.push_back(bssid2); + blockedBssids.push_back(bssid3); + + EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == false); +} + +void StaAutoConnectServiceTest::SetRoamBlockedBssidFirmwareFail4() +{ + ObtainRoamCapFromFirmwareSuccess(); + std::vector blockedBssids; + std::string bssid1 = "2a:76:93:47:e2:8a"; + blockedBssids.push_back(bssid1); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetRoamConfig(_)).WillOnce(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == false); +} + +void StaAutoConnectServiceTest::ConnectElectedDeviceSuccess1() +{ + WifiLinkedInfo info; + WifiDeviceConfig deviceConfig; + GetWifiLinkedInfo(info); + GetWifiDeviceConfig(deviceConfig); + info.connState = ConnState::CONNECTED; + info.bssid = "2a:76:93:47:e2:8b"; + deviceConfig.networkId = INVALID_NETWORK_ID; + + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).WillOnce(DoAll(SetArgReferee<0>(info), Return(0))); + pStaAutoConnectService->ConnectElectedDevice(deviceConfig); +} + +void StaAutoConnectServiceTest::ConnectElectedDeviceSuccess2() +{ + WifiLinkedInfo info; + WifiDeviceConfig deviceConfig; + GetWifiLinkedInfo(info); + GetWifiDeviceConfig(deviceConfig); + info.connState = ConnState::CONNECTED; + info.detailedState = DetailedState::DISCONNECTED; + + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).WillOnce(DoAll(SetArgReferee<0>(info), Return(0))); + pStaAutoConnectService->ConnectElectedDevice(deviceConfig); +} + +void StaAutoConnectServiceTest::ConnectElectedDeviceFail1() +{ + WifiLinkedInfo info; + WifiDeviceConfig deviceConfig; + GetWifiLinkedInfo(info); + GetWifiDeviceConfig(deviceConfig); + info.detailedState = DetailedState::INVALID; + + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).WillOnce(DoAll(SetArgReferee<0>(info), Return(0))); + pStaAutoConnectService->ConnectElectedDevice(deviceConfig); +} + +void StaAutoConnectServiceTest::GetAvailableScanInfosSuccess() +{ + std::vector availableScanInfos; + std::vector scanInfos; + std::vector blockedBssids; + WifiLinkedInfo info; + GetInterScanInfoVector(availableScanInfos); + GetInterScanInfoVector(scanInfos); + std::string bssid1 = "2a:76:93:47:e2:8a"; + blockedBssids.push_back(bssid1); + GetWifiLinkedInfo(info); + WifiDeviceConfig deviceConfig; + GetWifiDeviceConfig(deviceConfig); + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(deviceConfig.bssid, DEVICE_CONFIG_INDEX_BSSID, _)) + .Times(AtLeast(0)).WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); + + pStaAutoConnectService->GetAvailableScanInfos(availableScanInfos, scanInfos, blockedBssids, info); +} + +void StaAutoConnectServiceTest::AllowAutoSelectDeviceSuccess1() +{ + std::vector scanInfos; + WifiLinkedInfo info; + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).WillOnce(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillRepeatedly(Return(-1)); // if it is false, it will do process. + EXPECT_TRUE(pStaAutoConnectService->AllowAutoSelectDevice(scanInfos, info) == true); +} + +void StaAutoConnectServiceTest::AllowAutoSelectDeviceSuccess2() +{ + std::vector scanInfos; + WifiLinkedInfo info; + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + info.detailedState = DetailedState::DISCONNECTED; + EXPECT_TRUE(pStaAutoConnectService->AllowAutoSelectDevice(scanInfos, info) == true); +} + +void StaAutoConnectServiceTest::AllowAutoSelectDeviceSuccess3() +{ + std::vector scanInfos; + WifiLinkedInfo info; + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + info.detailedState = DetailedState::NOTWORKING; + + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).WillOnce(Return(true)); + EXPECT_TRUE(pStaAutoConnectService->AllowAutoSelectDevice(scanInfos, info) == true); +} + +void StaAutoConnectServiceTest::AllowAutoSelectDeviceFail1() +{ + std::vector scanInfos; + WifiLinkedInfo info; + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).WillOnce(Return(false)); + EXPECT_TRUE(pStaAutoConnectService->AllowAutoSelectDevice(scanInfos, info) == false); +} + +void StaAutoConnectServiceTest::AllowAutoSelectDeviceFail2() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + deviceConfig.networkId = 0; + + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).WillOnce(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(deviceConfig), Return(0))); // if it is true, it will do not process. + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()).Times(AtLeast(1)).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkTimeVal()).Times(AtLeast(0)); + EXPECT_TRUE(pStaAutoConnectService->AllowAutoSelectDevice(scanInfos, info) == false); +} + +void StaAutoConnectServiceTest::AllowAutoSelectDeviceFail3() +{ + std::vector scanInfos; + WifiLinkedInfo info; + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + info.detailedState = DetailedState::NOTWORKING; + + EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).WillOnce(Return(false)); + EXPECT_TRUE(pStaAutoConnectService->AllowAutoSelectDevice(scanInfos, info) == false); +} + +void StaAutoConnectServiceTest::AllowAutoSelectDeviceFail4() +{ + std::vector scanInfos; + WifiLinkedInfo info; + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + info.detailedState = DetailedState::INVALID; + + EXPECT_TRUE(pStaAutoConnectService->AllowAutoSelectDevice(scanInfos, info) == false); +} + +void StaAutoConnectServiceTest::CurrentDeviceGoodEnoughSuccess() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + deviceConfig.networkId = 0; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(deviceConfig), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()).Times(AtLeast(1)).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkTimeVal()).Times(AtLeast(1)); + EXPECT_TRUE(pStaAutoConnectService->CurrentDeviceGoodEnough(scanInfos, info) == true); +} + + +void StaAutoConnectServiceTest::CurrentDeviceGoodEnoughFail1() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(deviceConfig), Return(-1))); + EXPECT_TRUE(pStaAutoConnectService->CurrentDeviceGoodEnough(scanInfos, info) == false); +} + +void StaAutoConnectServiceTest::CurrentDeviceGoodEnoughFail2() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + deviceConfig.isEphemeral = true; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(deviceConfig), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()) + .Times(AtLeast(1)) + .WillOnce(Return(INVALID_NETWORK_ID)); + + EXPECT_TRUE(pStaAutoConnectService->CurrentDeviceGoodEnough(scanInfos, info) == false); +} + +void StaAutoConnectServiceTest::CurrentDeviceGoodEnoughFail3() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + deviceConfig.isEphemeral = false; + deviceConfig.keyMgmt = "NONE"; + deviceConfig.wepTxKeyIndex = -1; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(deviceConfig), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()) + .Times(AtLeast(1)) + .WillOnce(Return(INVALID_NETWORK_ID)); + + EXPECT_TRUE(pStaAutoConnectService->CurrentDeviceGoodEnough(scanInfos, info) == false); +} + + +void StaAutoConnectServiceTest::CurrentDeviceGoodEnoughFail4() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + info.rssi = SMALLER_THAN_RSSI_DELIMITING_VALUE; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(deviceConfig), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()) + .Times(AtLeast(1)) + .WillOnce(Return(INVALID_NETWORK_ID)); + + EXPECT_TRUE(pStaAutoConnectService->CurrentDeviceGoodEnough(scanInfos, info) == false); +} + +void StaAutoConnectServiceTest::CurrentDeviceGoodEnoughFail5() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + info.band = static_cast(BandType::BAND_2GHZ); + info.frequency = MIN_24_FREQUENCY + 1; + scanInfos[0].band = NETWORK_5G_BAND; + scanInfos[0].frequency = MIN_5_FREQUENCY + 1; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(deviceConfig), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()) + .Times(AtLeast(1)) + .WillOnce(Return(INVALID_NETWORK_ID)); + + EXPECT_TRUE(pStaAutoConnectService->CurrentDeviceGoodEnough(scanInfos, info) == false); +} + +void StaAutoConnectServiceTest::WhetherDevice5GAvailableSuccess() +{ + std::vector scanInfos; + GetInterScanInfoVector(scanInfos); + scanInfos[0].band = NETWORK_5G_BAND; + scanInfos[0].frequency = MIN_5_FREQUENCY + 1; + + EXPECT_TRUE(pStaAutoConnectService->WhetherDevice5GAvailable(scanInfos) == true); +} + +void StaAutoConnectServiceTest::WhetherDevice5GAvailableFail() +{ + std::vector scanInfos; + GetInterScanInfoVector(scanInfos); + + EXPECT_TRUE(pStaAutoConnectService->WhetherDevice5GAvailable(scanInfos) == false); +} + +void StaAutoConnectServiceTest::RoamingEncryptionModeCheckSuccess() +{ + WifiDeviceConfig deviceConfig; + InterScanInfo scanInfo; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetScanInfoConfig(scanInfo); + GetWifiLinkedInfo(info); + info.connState = ConnState::CONNECTED; + scanInfo.securityType = WifiSecurity::WEP; + deviceConfig.wepTxKeyIndex = 0; + deviceConfig.keyMgmt = "NONE"; + scanInfo.rssi = 8; + info.rssi = 1; + int indexType = DEVICE_CONFIG_INDEX_SSID; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(scanInfo.ssid, indexType, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); + + EXPECT_TRUE(pStaAutoConnectService->RoamingEncryptionModeCheck(deviceConfig, scanInfo, info) == true); +} + +void StaAutoConnectServiceTest::RoamingEncryptionModeCheckFail1() +{ + WifiDeviceConfig deviceConfig; + InterScanInfo scanInfo; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetScanInfoConfig(scanInfo); + GetWifiLinkedInfo(info); + int indexType = DEVICE_CONFIG_INDEX_SSID; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(scanInfo.ssid, indexType, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); + + EXPECT_TRUE(pStaAutoConnectService->RoamingEncryptionModeCheck(deviceConfig, scanInfo, info) == false); +} + +void StaAutoConnectServiceTest::RoamingEncryptionModeCheckFail2() +{ + WifiDeviceConfig deviceConfig; + InterScanInfo scanInfo; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetScanInfoConfig(scanInfo); + GetWifiLinkedInfo(info); + scanInfo.securityType = WifiSecurity::WEP; + deviceConfig.wepTxKeyIndex = -1; + int indexType = DEVICE_CONFIG_INDEX_SSID; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(scanInfo.ssid, indexType, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); + + EXPECT_TRUE(pStaAutoConnectService->RoamingEncryptionModeCheck(deviceConfig, scanInfo, info) == false); +} + +void StaAutoConnectServiceTest::RoamingEncryptionModeCheckFail3() +{ + WifiDeviceConfig deviceConfig; + InterScanInfo scanInfo; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetScanInfoConfig(scanInfo); + GetWifiLinkedInfo(info); + info.connState = ConnState::CONNECTED; + scanInfo.securityType = WifiSecurity::PSK; + deviceConfig.wepTxKeyIndex = 1; + deviceConfig.keyMgmt = "NONE"; + int indexType = DEVICE_CONFIG_INDEX_SSID; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(scanInfo.ssid, indexType, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); + + EXPECT_TRUE(pStaAutoConnectService->RoamingEncryptionModeCheck(deviceConfig, scanInfo, info) == false); +} + +void StaAutoConnectServiceTest::RoamingEncryptionModeCheckFail4() +{ + WifiDeviceConfig deviceConfig; + InterScanInfo scanInfo; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetScanInfoConfig(scanInfo); + GetWifiLinkedInfo(info); + info.connState = ConnState::CONNECTED; + scanInfo.securityType = WifiSecurity::WEP; + deviceConfig.wepTxKeyIndex = 1; + deviceConfig.keyMgmt = "WPA-PSK"; + int indexType = DEVICE_CONFIG_INDEX_SSID; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(scanInfo.ssid, indexType, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); + + EXPECT_TRUE(pStaAutoConnectService->RoamingEncryptionModeCheck(deviceConfig, scanInfo, info) == false); +} + +void StaAutoConnectServiceTest::RefreshConfigDeviceSuccess() +{ + pStaAutoConnectService->RefreshConfigDevice(); +} + +void StaAutoConnectServiceTest::RoamingSelectionSuccess1() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + deviceConfig.wepTxKeyIndex = 0; + deviceConfig.keyMgmt = "NONE"; + info.connState = ConnState::CONNECTED; + scanInfos[0].securityType = WifiSecurity::WEP; + scanInfos[0].rssi = 8; + scanInfos[0].ssid = "huawei"; + scanInfos[0].bssid = "2a:76:93:47:e2:8e"; + info.ssid = "huawei"; + info.bssid = "2a:76:93:47:e2:8b"; + info.rssi = 1; + int indexType = DEVICE_CONFIG_INDEX_SSID; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(scanInfos[0].ssid, indexType, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); + + EXPECT_TRUE(pStaAutoConnectService->RoamingSelection(deviceConfig, scanInfos, info) == true); +} + +void StaAutoConnectServiceTest::RoamingSelectionFail1() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + info.connState = ConnState::CONNECTED; + info.bssid = "2a:76:93:47:e2:8b"; + + int indexType = DEVICE_CONFIG_INDEX_SSID; + + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(scanInfos[0].ssid, indexType, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); + + EXPECT_TRUE(pStaAutoConnectService->RoamingSelection(deviceConfig, scanInfos, info) == false); +} + +void StaAutoConnectServiceTest::RoamingSelectionFail2() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + deviceConfig.wepTxKeyIndex = -1; + scanInfos[0].securityType = WifiSecurity::WEP; + info.connState = ConnState::CONNECTED; + info.bssid = "2a:76:93:47:e2:8b"; + int indexType = DEVICE_CONFIG_INDEX_SSID; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(scanInfos[0].ssid, indexType, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); + + EXPECT_TRUE(pStaAutoConnectService->RoamingSelection(deviceConfig, scanInfos, info) == false); +} + +void StaAutoConnectServiceTest::RoamingSelectionFail3() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + deviceConfig.wepTxKeyIndex = 1; + deviceConfig.keyMgmt = "NONE"; + scanInfos[0].securityType = WifiSecurity::PSK; + info.connState = ConnState::CONNECTED; + info.bssid = "2a:76:93:47:e2:8b"; + info.connState = ConnState::CONNECTED; + int indexType = DEVICE_CONFIG_INDEX_SSID; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(scanInfos[0].ssid, indexType, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); + + EXPECT_TRUE(pStaAutoConnectService->RoamingSelection(deviceConfig, scanInfos, info) == false); +} + +void StaAutoConnectServiceTest::RoamingSelectionFail4() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + deviceConfig.wepTxKeyIndex = 1; + deviceConfig.keyMgmt = "WPA-PSK"; + scanInfos[0].securityType = WifiSecurity::WEP; + info.connState = ConnState::CONNECTED; + info.bssid = "2a:76:93:47:e2:8b"; + info.connState = ConnState::CONNECTED; + int indexType = DEVICE_CONFIG_INDEX_SSID; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(scanInfos[0].ssid, indexType, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); + + EXPECT_TRUE(pStaAutoConnectService->RoamingSelection(deviceConfig, scanInfos, info) == false); +} + +void StaAutoConnectServiceTest::SyncBlockedSsidFirmwareSuccess() +{ + std::string bssid = "2a:76:93:47:e2:8a"; + bool enable = false; + int reason = AP_CANNOT_HANDLE_NEW_STA; + WifiIdlRoamCapability capability; + capability.maxBlocklistSize = 2; + + pStaAutoConnectService->AddOrDelBlockedBssids(bssid, enable, reason); + + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetStaCapabilities(_)) + .WillOnce(Return(WIFI_IDL_OPT_FAILED)); // if it is false, it will do process. + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetRoamingCapabilities(_)) + .WillOnce(DoAll(SetArgReferee<0>(capability), Return(WIFI_IDL_OPT_OK))); + pStaAutoConnectService->ObtainRoamCapFromFirmware(); + + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetRoamConfig(_)).WillOnce(Return(WIFI_IDL_OPT_OK)); + pStaAutoConnectService->SyncBlockedSsidFirmware(); +} + +void StaAutoConnectServiceTest::SyncBlockedSsidFirmwareFail() +{ + WifiIdlRoamCapability capability; + capability.maxBlocklistSize = 2; + + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetStaCapabilities(_)) + .WillOnce(Return(WIFI_IDL_OPT_FAILED)); // if it is false, it will do process. + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetRoamingCapabilities(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(capability), Return(WIFI_IDL_OPT_OK))); + pStaAutoConnectService->ObtainRoamCapFromFirmware(); + + pStaAutoConnectService->SyncBlockedSsidFirmware(); +} + +/* ************************ HWTEST_F ************************************ */ + +HWTEST_F(StaAutoConnectServiceTest, InitAutoConnectServiceSuccess, TestSize.Level1) +{ + InitAutoConnectServiceSuccess(); +} + +HWTEST_F(StaAutoConnectServiceTest, OnScanResultsReadyHandlerSuccess1, TestSize.Level1) +{ + OnScanResultsReadyHandlerSuccess1(); +} + +HWTEST_F(StaAutoConnectServiceTest, OnScanResultsReadyHandlerSuccess2, TestSize.Level1) +{ + OnScanResultsReadyHandlerSuccess2(); +} + +HWTEST_F(StaAutoConnectServiceTest, OnScanResultsReadyHandlerSuccess3, TestSize.Level1) +{ + OnScanResultsReadyHandlerSuccess3(); +} + +HWTEST_F(StaAutoConnectServiceTest, OnScanResultsReadyHandlerFail1, TestSize.Level1) +{ + OnScanResultsReadyHandlerFail1(); +} + +HWTEST_F(StaAutoConnectServiceTest, OnScanResultsReadyHandlerFail2, TestSize.Level1) +{ + OnScanResultsReadyHandlerFail2(); +} + +HWTEST_F(StaAutoConnectServiceTest, OnScanResultsReadyHandlerFail3, TestSize.Level1) +{ + OnScanResultsReadyHandlerFail3(); +} + +HWTEST_F(StaAutoConnectServiceTest, OnScanResultsReadyHandlerFail4, TestSize.Level1) +{ + OnScanResultsReadyHandlerFail4(); +} + + +HWTEST_F(StaAutoConnectServiceTest, OnScanResultsReadyHandlerFail5, TestSize.Level1) +{ + OnScanResultsReadyHandlerFail5(); +} + + +HWTEST_F(StaAutoConnectServiceTest, OnScanResultsReadyHandlerFail6, TestSize.Level1) +{ + OnScanResultsReadyHandlerFail6(); +} + +HWTEST_F(StaAutoConnectServiceTest, OnScanResultsReadyHandlerFail7, TestSize.Level1) +{ + OnScanResultsReadyHandlerFail7(); +} + +HWTEST_F(StaAutoConnectServiceTest, EnableOrDisableBssidSuccess1, TestSize.Level1) +{ + EnableOrDisableBssidSuccess1(); +} + +HWTEST_F(StaAutoConnectServiceTest, EnableOrDisableBssidSuccess2, TestSize.Level1) +{ + EnableOrDisableBssidSuccess2(); +} + +HWTEST_F(StaAutoConnectServiceTest, EnableOrDisableBssidFail1, TestSize.Level1) +{ + EnableOrDisableBssidFail1(); +} + +HWTEST_F(StaAutoConnectServiceTest, EnableOrDisableBssidFail2, TestSize.Level1) +{ + EnableOrDisableBssidFail2(); +} + +HWTEST_F(StaAutoConnectServiceTest, EnableOrDisableBssidFail3, TestSize.Level1) +{ + EnableOrDisableBssidFail3(); +} + +HWTEST_F(StaAutoConnectServiceTest, EnableOrDisableBssidFail4, TestSize.Level1) +{ + EnableOrDisableBssidFail4(); +} + +HWTEST_F(StaAutoConnectServiceTest, AutoSelectDeviceSuccess1, TestSize.Level1) +{ + AutoSelectDeviceSuccess1(); +} + +HWTEST_F(StaAutoConnectServiceTest, AutoSelectDeviceSuccess2, TestSize.Level1) +{ + AutoSelectDeviceSuccess2(); +} + +HWTEST_F(StaAutoConnectServiceTest, AutoSelectDeviceSuccess3, TestSize.Level1) +{ + AutoSelectDeviceSuccess3(); +} + +HWTEST_F(StaAutoConnectServiceTest, AutoSelectDeviceFail1, TestSize.Level1) +{ + AutoSelectDeviceFail1(); +} + +HWTEST_F(StaAutoConnectServiceTest, AutoSelectDeviceFail2, TestSize.Level1) +{ + AutoSelectDeviceFail2(); +} + +HWTEST_F(StaAutoConnectServiceTest, AutoSelectDeviceFail3, TestSize.Level1) +{ + AutoSelectDeviceFail3(); +} + +HWTEST_F(StaAutoConnectServiceTest, AutoSelectDeviceFail4, TestSize.Level1) +{ + AutoSelectDeviceFail4(); +} + +HWTEST_F(StaAutoConnectServiceTest, AutoSelectDeviceFail5, TestSize.Level1) +{ + AutoSelectDeviceFail5(); +} + +HWTEST_F(StaAutoConnectServiceTest, AutoSelectDeviceFail6, TestSize.Level1) +{ + AutoSelectDeviceFail6(); +} + +HWTEST_F(StaAutoConnectServiceTest, RegisterDeviceAppraisalSuccess, TestSize.Level1) +{ + RegisterDeviceAppraisalSuccess(); +} + +HWTEST_F(StaAutoConnectServiceTest, RegisterDeviceAppraisalFail1, TestSize.Level1) +{ + RegisterDeviceAppraisalFail1(); +} + +HWTEST_F(StaAutoConnectServiceTest, RegisterDeviceAppraisalFail2, TestSize.Level1) +{ + RegisterDeviceAppraisalFail2(); +} + +HWTEST_F(StaAutoConnectServiceTest, ClearOvertimeBlockedBssidSuccess1, TestSize.Level1) +{ + ClearOvertimeBlockedBssidSuccess1(); +} + +HWTEST_F(StaAutoConnectServiceTest, ClearOvertimeBlockedBssidSuccess2, TestSize.Level1) +{ + ClearOvertimeBlockedBssidSuccess2(); +} + +HWTEST_F(StaAutoConnectServiceTest, GetBlockedBssidsSuccess, TestSize.Level1) +{ + GetBlockedBssidsSuccess(); +} + +HWTEST_F(StaAutoConnectServiceTest, AddOrDelBlockedBssidsSuccess, TestSize.Level1) +{ + AddOrDelBlockedBssidsSuccess(); +} + +HWTEST_F(StaAutoConnectServiceTest, AddOrDelBlockedBssidsFail, TestSize.Level1) +{ + AddOrDelBlockedBssidsFail(); +} + +HWTEST_F(StaAutoConnectServiceTest, ObtainRoamCapFromFirmwareSuccess, TestSize.Level1) +{ + ObtainRoamCapFromFirmwareSuccess(); +} + +HWTEST_F(StaAutoConnectServiceTest, ObtainRoamCapFromFirmwareFail1, TestSize.Level1) +{ + ObtainRoamCapFromFirmwareFail1(); +} + +HWTEST_F(StaAutoConnectServiceTest, ObtainRoamCapFromFirmwareFail2, TestSize.Level1) +{ + ObtainRoamCapFromFirmwareFail2(); +} + +HWTEST_F(StaAutoConnectServiceTest, SetRoamBlockedBssidFirmwareSuccess, TestSize.Level1) +{ + SetRoamBlockedBssidFirmwareSuccess(); +} + +HWTEST_F(StaAutoConnectServiceTest, SetRoamBlockedBssidFirmwareFail1, TestSize.Level1) +{ + SetRoamBlockedBssidFirmwareFail1(); +} + +HWTEST_F(StaAutoConnectServiceTest, SetRoamBlockedBssidFirmwareFail2, TestSize.Level1) +{ + SetRoamBlockedBssidFirmwareFail2(); +} + +HWTEST_F(StaAutoConnectServiceTest, SetRoamBlockedBssidFirmwareFail3, TestSize.Level1) +{ + SetRoamBlockedBssidFirmwareFail3(); +} + +HWTEST_F(StaAutoConnectServiceTest, SetRoamBlockedBssidFirmwareFail4, TestSize.Level1) +{ + SetRoamBlockedBssidFirmwareFail4(); +} + +HWTEST_F(StaAutoConnectServiceTest, ConnectElectedDeviceSuccess1, TestSize.Level1) +{ + ConnectElectedDeviceSuccess1(); +} + +HWTEST_F(StaAutoConnectServiceTest, ConnectElectedDeviceSuccess2, TestSize.Level1) +{ + ConnectElectedDeviceSuccess2(); +} + +HWTEST_F(StaAutoConnectServiceTest, ConnectElectedDeviceFail1, TestSize.Level1) +{ + ConnectElectedDeviceFail1(); +} + +HWTEST_F(StaAutoConnectServiceTest, GetAvailableScanInfosSuccess, TestSize.Level1) +{ + GetAvailableScanInfosSuccess(); +} + +HWTEST_F(StaAutoConnectServiceTest, AllowAutoSelectDeviceSuccess1, TestSize.Level1) +{ + AllowAutoSelectDeviceSuccess1(); +} + +HWTEST_F(StaAutoConnectServiceTest, AllowAutoSelectDeviceSuccess2, TestSize.Level1) +{ + AllowAutoSelectDeviceSuccess2(); +} + +HWTEST_F(StaAutoConnectServiceTest, AllowAutoSelectDeviceSuccess3, TestSize.Level1) +{ + AllowAutoSelectDeviceSuccess3(); +} + +HWTEST_F(StaAutoConnectServiceTest, AllowAutoSelectDeviceFail1, TestSize.Level1) +{ + AllowAutoSelectDeviceFail1(); +} + +HWTEST_F(StaAutoConnectServiceTest, AllowAutoSelectDeviceFail2, TestSize.Level1) +{ + AllowAutoSelectDeviceFail2(); +} + +HWTEST_F(StaAutoConnectServiceTest, AllowAutoSelectDeviceFail3, TestSize.Level1) +{ + AllowAutoSelectDeviceFail3(); +} + +HWTEST_F(StaAutoConnectServiceTest, AllowAutoSelectDeviceFail4, TestSize.Level1) +{ + AllowAutoSelectDeviceFail4(); +} + +HWTEST_F(StaAutoConnectServiceTest, CurrentDeviceGoodEnoughSuccess, TestSize.Level1) +{ + CurrentDeviceGoodEnoughSuccess(); +} + +HWTEST_F(StaAutoConnectServiceTest, CurrentDeviceGoodEnoughFail1, TestSize.Level1) +{ + CurrentDeviceGoodEnoughFail1(); +} + +HWTEST_F(StaAutoConnectServiceTest, CurrentDeviceGoodEnoughFail2, TestSize.Level1) +{ + CurrentDeviceGoodEnoughFail2(); +} + +HWTEST_F(StaAutoConnectServiceTest, CurrentDeviceGoodEnoughFail3, TestSize.Level1) +{ + CurrentDeviceGoodEnoughFail3(); +} + + +HWTEST_F(StaAutoConnectServiceTest, CurrentDeviceGoodEnoughFail4, TestSize.Level1) +{ + CurrentDeviceGoodEnoughFail4(); +} + +HWTEST_F(StaAutoConnectServiceTest, CurrentDeviceGoodEnoughFail5, TestSize.Level1) +{ + CurrentDeviceGoodEnoughFail5(); +} + +HWTEST_F(StaAutoConnectServiceTest, WhetherDevice5GAvailableSuccess, TestSize.Level1) +{ + WhetherDevice5GAvailableSuccess(); +} + +HWTEST_F(StaAutoConnectServiceTest, WhetherDevice5GAvailableFail, TestSize.Level1) +{ + WhetherDevice5GAvailableFail(); +} + +HWTEST_F(StaAutoConnectServiceTest, RoamingEncryptionModeCheckSuccess, TestSize.Level1) +{ + RoamingEncryptionModeCheckSuccess(); +} + +HWTEST_F(StaAutoConnectServiceTest, RoamingEncryptionModeCheckFail1, TestSize.Level1) +{ + RoamingEncryptionModeCheckFail1(); +} + +HWTEST_F(StaAutoConnectServiceTest, RoamingEncryptionModeCheckFail2, TestSize.Level1) +{ + RoamingEncryptionModeCheckFail2(); +} + +HWTEST_F(StaAutoConnectServiceTest, RoamingEncryptionModeCheckFail3, TestSize.Level1) +{ + RoamingEncryptionModeCheckFail3(); +} + +HWTEST_F(StaAutoConnectServiceTest, RoamingEncryptionModeCheckFail4, TestSize.Level1) +{ + RoamingEncryptionModeCheckFail4(); +} + +HWTEST_F(StaAutoConnectServiceTest, RefreshConfigDeviceSuccess, TestSize.Level1) +{ + RefreshConfigDeviceSuccess(); +} + +HWTEST_F(StaAutoConnectServiceTest, RoamingSelectionSuccess1, TestSize.Level1) +{ + RoamingSelectionSuccess1(); +} + +HWTEST_F(StaAutoConnectServiceTest, RoamingSelectionFail1, TestSize.Level1) +{ + RoamingSelectionFail1(); +} + +HWTEST_F(StaAutoConnectServiceTest, RoamingSelectionFail2, TestSize.Level1) +{ + RoamingSelectionFail2(); +} + +HWTEST_F(StaAutoConnectServiceTest, RoamingSelectionFail3, TestSize.Level1) +{ + RoamingSelectionFail3(); +} + +HWTEST_F(StaAutoConnectServiceTest, RoamingSelectionFail4, TestSize.Level1) +{ + RoamingSelectionFail4(); +} + +HWTEST_F(StaAutoConnectServiceTest, SyncBlockedSsidFirmwareSuccess, TestSize.Level1) +{ + SyncBlockedSsidFirmwareSuccess(); +} + +HWTEST_F(StaAutoConnectServiceTest, SyncBlockedSsidFirmwareFail, TestSize.Level1) +{ + SyncBlockedSsidFirmwareFail(); +} +} // Wifi +} // OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface_test.cpp new file mode 100644 index 000000000..6edb82fa1 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface_test.cpp @@ -0,0 +1,427 @@ +/* + * 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 "sta_interface.h" +#include +#include +#include +#include +#include "mock_sta_service.h" +#include "mock_wifi_settings.h" +#include "mock_wifi_sta_hal_interface.h" + +using ::testing::_; +using ::testing::AtLeast; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::StrEq; +using ::testing::TypedEq; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +bool operator == (const WifiDeviceConfig &lhs, const WifiDeviceConfig &rhs) +{ + return lhs.networkId == rhs.networkId; +} + +class StaInterfaceTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + virtual void SetUp() override + { + pStaInterface.reset(new StaInterface); + pStaInterface->pStaService = new MockWifiStaService(); + pMockStaService = (MockWifiStaService *)pStaInterface->pStaService; + } + virtual void TearDown() override + { + pStaInterface.reset(); + } + + void SleepMs(const int sleepMs) + { + std::unique_lock lck(mMtxBlock); + mCvTest.wait_for(lck, std::chrono::milliseconds(sleepMs)); + } + +public: + std::unique_ptr pStaInterface; + MockWifiStaService *pMockStaService = nullptr; + std::mutex mMtxBlock; + std::condition_variable mCvTest; + + void EnableWifiSuccess() + { + EXPECT_CALL(*pMockStaService, InitStaService(_)).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_CALL(*pMockStaService, EnableWifi()).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->EnableWifi() == WIFI_OPT_SUCCESS); + } + + void DisableWifiSuceess() + { + EXPECT_CALL(*pMockStaService, DisableWifi()).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->DisableWifi() == WIFI_OPT_SUCCESS); + } + + void DisableWifiFail() + { + EXPECT_CALL(*pMockStaService, DisableWifi()).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->DisableWifi() == WIFI_OPT_FAILED); + } + + void ConnectToNetworkIdSuceess() + { + int networkId = 0; + EXPECT_CALL(*pMockStaService, ConnectToNetwork(networkId)).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->ConnectToNetwork(0) == WIFI_OPT_SUCCESS); + } + + void ConnectToNetworkIdFail1() + { + int networkId = 0; + EXPECT_CALL(*pMockStaService, ConnectToNetwork(networkId)).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->ConnectToNetwork(0) == WIFI_OPT_FAILED); + } + + void ConnectToConfigSuceess() + { + WifiDeviceConfig config; + EXPECT_CALL(*pMockStaService, ConnectToDevice(config)).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->ConnectToDevice(config) == WIFI_OPT_SUCCESS); + } + + void ConnectToConfigFail1() + { + WifiDeviceConfig config; + EXPECT_CALL(*pMockStaService, ConnectToDevice(config)).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->ConnectToDevice(config) == WIFI_OPT_FAILED); + } + + void ReAssociateSuceess() + { + WifiDeviceConfig config; + EXPECT_CALL(*pMockStaService, ReAssociate()).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->ReAssociate() == WIFI_OPT_SUCCESS); + } + + void ReAssociateFail1() + { + WifiDeviceConfig config; + EXPECT_CALL(*pMockStaService, ReAssociate()).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->ReAssociate() == WIFI_OPT_FAILED); + } + + void DisconnectSuceess() + { + WifiDeviceConfig config; + EXPECT_CALL(*pMockStaService, Disconnect()).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->Disconnect() == WIFI_OPT_SUCCESS); + } + + void DisconnectFail1() + { + WifiDeviceConfig config; + EXPECT_CALL(*pMockStaService, Disconnect()).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->Disconnect() == WIFI_OPT_FAILED); + } + + void AddDeviceConfigSuceess() + { + WifiDeviceConfig config; + EXPECT_CALL(*pMockStaService, AddDeviceConfig(_)).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->AddDeviceConfig(config) == WIFI_OPT_SUCCESS); + } + + void AddDeviceConfigFail1() + { + WifiDeviceConfig config; + EXPECT_CALL(*pMockStaService, AddDeviceConfig(_)).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->AddDeviceConfig(config) == WIFI_OPT_FAILED); + } + + void UpdateDeviceConfigSuceess() + { + WifiDeviceConfig config; + EXPECT_CALL(*pMockStaService, UpdateDeviceConfig(_)).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->UpdateDeviceConfig(config) == WIFI_OPT_SUCCESS); + } + + void UpdateDeviceConfigFail1() + { + WifiDeviceConfig config; + EXPECT_CALL(*pMockStaService, UpdateDeviceConfig(_)).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->UpdateDeviceConfig(config) == WIFI_OPT_FAILED); + } + + void RemoveDeviceConfigSuceess() + { + EXPECT_CALL(*pMockStaService, RemoveDevice(_)).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->RemoveDevice(0) == WIFI_OPT_SUCCESS); + } + + void RemoveDeviceConfigFail1() + { + EXPECT_CALL(*pMockStaService, RemoveDevice(_)).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->RemoveDevice(0) == WIFI_OPT_FAILED); + } + + void EnableDeviceConfigSuceess() + { + EXPECT_CALL(*pMockStaService, EnableDeviceConfig(_, _)).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->EnableDeviceConfig(0, true) == WIFI_OPT_SUCCESS); + } + + void EnableDeviceConfigFail1() + { + EXPECT_CALL(*pMockStaService, EnableDeviceConfig(_, _)).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->EnableDeviceConfig(0, true) == WIFI_OPT_FAILED); + } + + void DisableDeviceConfigSuceess() + { + EXPECT_CALL(*pMockStaService, DisableDeviceConfig(_)).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->DisableDeviceConfig(0) == WIFI_OPT_SUCCESS); + } + + void DisableDeviceConfigFail1() + { + EXPECT_CALL(*pMockStaService, DisableDeviceConfig(_)).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->DisableDeviceConfig(0) == WIFI_OPT_FAILED); + } + + void StartWpsSuceess() + { + WpsConfig config; + EXPECT_CALL(*pMockStaService, StartWps(_)).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->StartWps(config) == WIFI_OPT_SUCCESS); + } + + void StartWpsFail1() + { + WpsConfig config; + EXPECT_CALL(*pMockStaService, StartWps(_)).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->StartWps(config) == WIFI_OPT_FAILED); + } + + void CancelWpsSuceess() + { + EXPECT_CALL(*pMockStaService, CancelWps()).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->CancelWps() == WIFI_OPT_SUCCESS); + } + + void CancelWpsFail1() + { + EXPECT_CALL(*pMockStaService, CancelWps()).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->CancelWps() == WIFI_OPT_FAILED); + } + + void AutoConnectServiceSuceess() + { + std::vector scanInfos; + EXPECT_CALL(*pMockStaService, AutoConnectService(_)).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->ConnectivityManager(scanInfos) == WIFI_OPT_SUCCESS); + } + + void AutoConnectServiceFail() + { + std::vector scanInfos; + EXPECT_CALL(*pMockStaService, AutoConnectService(_)).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->ConnectivityManager(scanInfos) == WIFI_OPT_FAILED); + } + + void SetCountryCodeSuceess() + { + std::string countryCode; + EXPECT_CALL(*pMockStaService, SetCountryCode(_)).WillRepeatedly(Return(WIFI_OPT_SUCCESS)); + EXPECT_TRUE(pStaInterface->SetCountryCode(countryCode) == WIFI_OPT_SUCCESS); + } + + void SetCountryCodeFail() + { + std::string countryCode; + EXPECT_CALL(*pMockStaService, SetCountryCode(_)).WillRepeatedly(Return(WIFI_OPT_FAILED)); + EXPECT_TRUE(pStaInterface->SetCountryCode(countryCode) == WIFI_OPT_FAILED); + } +}; + +extern "C" IStaService *Create(void); +extern "C" void Destroy(IStaService *pservice); + +HWTEST_F(StaInterfaceTest, CreateSuccess, TestSize.Level1) +{ + Create(); +} + +HWTEST_F(StaInterfaceTest, DestroySuccess, TestSize.Level1) +{ + IStaService *pservice = nullptr; + Destroy(pservice); +} + +HWTEST_F(StaInterfaceTest, EnableWifiSuccess, TestSize.Level1) +{ + EnableWifiSuccess(); +} + +HWTEST_F(StaInterfaceTest, DisableWifiSuceess, TestSize.Level1) +{ + DisableWifiSuceess(); +} + +HWTEST_F(StaInterfaceTest, DisableWifiFail, TestSize.Level1) +{ + DisableWifiFail(); +} + +HWTEST_F(StaInterfaceTest, ConnectToNetworkIdSuceess, TestSize.Level1) +{ + ConnectToNetworkIdSuceess(); +} + +HWTEST_F(StaInterfaceTest, ConnectToNetworkIdFail1, TestSize.Level1) +{ + ConnectToNetworkIdFail1(); +} + +HWTEST_F(StaInterfaceTest, ConnectToConfigSuceess, TestSize.Level1) +{ + ConnectToConfigSuceess(); +} + +HWTEST_F(StaInterfaceTest, ConnectToConfigFail1, TestSize.Level1) +{ + ConnectToConfigFail1(); +} + +HWTEST_F(StaInterfaceTest, ReAssociateSuceess, TestSize.Level1) +{ + ReAssociateSuceess(); +} + +HWTEST_F(StaInterfaceTest, ReAssociateFail1, TestSize.Level1) +{ + ReAssociateFail1(); +} + +HWTEST_F(StaInterfaceTest, DisconnectSuceess, TestSize.Level1) +{ + DisconnectSuceess(); +} + +HWTEST_F(StaInterfaceTest, DisconnectFail1, TestSize.Level1) +{ + DisconnectFail1(); +} + +HWTEST_F(StaInterfaceTest, AddDeviceConfigSuceess, TestSize.Level1) +{ + AddDeviceConfigSuceess(); +} + +HWTEST_F(StaInterfaceTest, AddDeviceConfigFail1, TestSize.Level1) +{ + AddDeviceConfigFail1(); +} + +HWTEST_F(StaInterfaceTest, UpdateDeviceConfigSuceess, TestSize.Level1) +{ + UpdateDeviceConfigSuceess(); +} + +HWTEST_F(StaInterfaceTest, UpdateDeviceConfigFail1, TestSize.Level1) +{ + UpdateDeviceConfigFail1(); +} + +HWTEST_F(StaInterfaceTest, RemoveDeviceConfigSuceess, TestSize.Level1) +{ + RemoveDeviceConfigSuceess(); +} + +HWTEST_F(StaInterfaceTest, RemoveDeviceConfigFail1, TestSize.Level1) +{ + RemoveDeviceConfigFail1(); +} + +HWTEST_F(StaInterfaceTest, EnableDeviceConfigSuceess, TestSize.Level1) +{ + EnableDeviceConfigSuceess(); +} + +HWTEST_F(StaInterfaceTest, EnableDeviceConfigFail1, TestSize.Level1) +{ + EnableDeviceConfigFail1(); +} + +HWTEST_F(StaInterfaceTest, DisableDeviceConfigSuceess, TestSize.Level1) +{ + DisableDeviceConfigSuceess(); +} + +HWTEST_F(StaInterfaceTest, DisableDeviceConfigFail1, TestSize.Level1) +{ + DisableDeviceConfigFail1(); +} + +HWTEST_F(StaInterfaceTest, StartWpsSuceess, TestSize.Level1) +{ + StartWpsSuceess(); +} + +HWTEST_F(StaInterfaceTest, StartWpsFail1, TestSize.Level1) +{ + StartWpsFail1(); +} + +HWTEST_F(StaInterfaceTest, CancelWpsSuceess, TestSize.Level1) +{ + CancelWpsSuceess(); +} + +HWTEST_F(StaInterfaceTest, CancelWpsFail1, TestSize.Level1) +{ + CancelWpsFail1(); +} + +HWTEST_F(StaInterfaceTest, AutoConnectServiceSuceess, TestSize.Level1) +{ + AutoConnectServiceSuceess(); +} + +HWTEST_F(StaInterfaceTest, AutoConnectServiceFail, TestSize.Level1) +{ + AutoConnectServiceFail(); +} + +HWTEST_F(StaInterfaceTest, SetCountryCodeSuceess, TestSize.Level1) +{ + SetCountryCodeSuceess(); +} + +HWTEST_F(StaInterfaceTest, SetCountryCodeFail, TestSize.Level1) +{ + SetCountryCodeFail(); +} + +HWTEST_F(StaInterfaceTest, RegisterStaServiceCallbackSuceess, TestSize.Level1) +{ + StaServiceCallback callbacks; + pStaInterface->RegisterStaServiceCallback(callbacks); +} +} // namespace Wifi +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor_test.cpp new file mode 100644 index 000000000..e3e221dd4 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor_test.cpp @@ -0,0 +1,301 @@ +/* + * 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 "sta_monitor.h" +#include +#include "mock_sta_state_machine.h" +#include "mock_wifi_sta_hal_interface.h" +#include "wifi_idl_define.h" +#include + +using ::testing::_; +using ::testing::AtLeast; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::StrEq; +using ::testing::TypedEq; +using ::testing::ext::TestSize; + + +namespace OHOS { +namespace Wifi { +class StaMonitorTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + virtual void SetUp() + { + pStaMonitor = std::make_unique(); + pStaMonitor->pStaStateMachine = new MockStaStateMachine(); + InitStaMonitorSuccess(); + } + virtual void TearDown() + { + pStaMonitor.reset(); + } + +public: + std::unique_ptr pStaMonitor; + + void InitStaMonitorSuccess(); + void InitStaMonitorFail(); + void UnInitStaMonitorSuccess(); + void UnInitStaMonitorFail(); + void SetStateMachineSuccess(); + void OnConnectChangedCallBackSuccess1(); + void OnConnectChangedCallBackSuccess2(); + void OnConnectChangedCallBackFail1(); + void OnConnectChangedCallBackFail2(); + void OnConnectChangedCallBackFail3(); + void OnWpaStateChangedCallBackSuccess(); + void OnWpaStateChangedCallBackFail1(); + void OnWpaStateChangedCallBackFail2(); + void OnWpaSsidWrongKeyCallBackSuccess(); + void OnWpaSsidWrongKeyCallBackFail1(); + void OnWpaSsidWrongKeyCallBackFail2(); + void OnWpaSsidWrongKeyCallBackFail3(); + void OnWpsPbcOverlapCallBackSuccess(); + void OnWpsPbcOverlapCallBackFail1(); + void OnWpsPbcOverlapCallBackFail2(); + void OnWpsTimeOutCallBackSuccess(); + void OnWpsTimeOutCallBackFail1(); + void OnWpsTimeOutCallBackFail2(); +}; + +void StaMonitorTest::InitStaMonitorSuccess() +{ + EXPECT_CALL(WifiStaHalInterface::GetInstance(), RegisterStaEventCallback(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pStaMonitor->InitStaMonitor() == WIFI_OPT_SUCCESS); +} + +void StaMonitorTest::InitStaMonitorFail() +{ + EXPECT_CALL(WifiStaHalInterface::GetInstance(), RegisterStaEventCallback(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pStaMonitor->InitStaMonitor() == WIFI_OPT_FAILED); +} + +void StaMonitorTest::UnInitStaMonitorSuccess() +{ + EXPECT_CALL(WifiStaHalInterface::GetInstance(), RegisterStaEventCallback(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pStaMonitor->UnInitStaMonitor() == WIFI_OPT_SUCCESS); +} + +void StaMonitorTest::UnInitStaMonitorFail() +{ + EXPECT_CALL(WifiStaHalInterface::GetInstance(), RegisterStaEventCallback(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pStaMonitor->UnInitStaMonitor() == WIFI_OPT_FAILED); +} + +void StaMonitorTest::SetStateMachineSuccess() +{ + pStaMonitor->SetStateMachine(pStaMonitor->pStaStateMachine); +} + +void StaMonitorTest::OnConnectChangedCallBackSuccess1() +{ + int status = WPA_CB_CONNECTED; + int networkId = 1; + std::string bssid = "01:23:45:67:89:AB"; + pStaMonitor->OnConnectChangedCallBack(status, networkId, bssid); +} + +void StaMonitorTest::OnConnectChangedCallBackSuccess2() +{ + int status = WPA_CB_DISCONNECTED; + int networkId = 1; + std::string bssid = "01:23:45:67:89:AB"; + pStaMonitor->OnConnectChangedCallBack(status, networkId, bssid); +} + +void StaMonitorTest::OnConnectChangedCallBackFail1() +{ + int status = WPA_CB_CONNECTED; + int networkId = 0; + std::string bssid = "00:00:00:00:00:00"; + pStaMonitor->pStaStateMachine = nullptr; + pStaMonitor->OnConnectChangedCallBack(status, networkId, bssid); +} + +void StaMonitorTest::OnConnectChangedCallBackFail2() +{ + int status = WPA_CB_CONNECTED; + int networkId = 0; + std::string bssid = "00:00:00:00:00:00"; + pStaMonitor->OnConnectChangedCallBack(status, networkId, bssid); +} + +void StaMonitorTest::OnConnectChangedCallBackFail3() +{ + int status = -1; + int networkId = 0; + std::string bssid = "00:00:00:00:00:00"; + pStaMonitor->OnConnectChangedCallBack(status, networkId, bssid); +} + +void StaMonitorTest::OnWpaStateChangedCallBackSuccess() +{ + int status = 1; + pStaMonitor->OnWpaStateChangedCallBack(status); +} + +void StaMonitorTest::OnWpaStateChangedCallBackFail1() +{ + int status = 1; + pStaMonitor->pStaStateMachine = nullptr; + pStaMonitor->OnWpaStateChangedCallBack(status); +} + +void StaMonitorTest::OnWpaSsidWrongKeyCallBackSuccess() +{ + int status = 1; + pStaMonitor->OnWpaSsidWrongKeyCallBack(status); +} + +void StaMonitorTest::OnWpaSsidWrongKeyCallBackFail1() +{ + int status = 1; + pStaMonitor->pStaStateMachine = nullptr; + pStaMonitor->OnWpaSsidWrongKeyCallBack(status); +} + +void StaMonitorTest::OnWpaSsidWrongKeyCallBackFail2() +{ + int status = -1; + pStaMonitor->OnWpaSsidWrongKeyCallBack(status); +} + +void StaMonitorTest::OnWpsPbcOverlapCallBackSuccess() +{ + int status = 1; + pStaMonitor->OnWpsPbcOverlapCallBack(status); +} + +void StaMonitorTest::OnWpsPbcOverlapCallBackFail1() +{ + int status = 1; + pStaMonitor->pStaStateMachine = nullptr; + pStaMonitor->OnWpsPbcOverlapCallBack(status); +} + +void StaMonitorTest::OnWpsTimeOutCallBackSuccess() +{ + int status = 1; + pStaMonitor->OnWpsTimeOutCallBack(status); +} + +void StaMonitorTest::OnWpsTimeOutCallBackFail1() +{ + int status = 1; + pStaMonitor->pStaStateMachine = nullptr; + pStaMonitor->OnWpsTimeOutCallBack(status); +} + +HWTEST_F(StaMonitorTest, InitStaMonitorSuccess, TestSize.Level1) +{ + InitStaMonitorSuccess(); +} + +HWTEST_F(StaMonitorTest, InitStaMonitorFail, TestSize.Level1) +{ + InitStaMonitorFail(); +} + +HWTEST_F(StaMonitorTest, UnInitStaMonitorSuccess, TestSize.Level1) +{ + UnInitStaMonitorSuccess(); +} + +HWTEST_F(StaMonitorTest, UnInitStaMonitorFail, TestSize.Level1) +{ + UnInitStaMonitorFail(); +} + +HWTEST_F(StaMonitorTest, OnConnectChangedCallBackFail1, TestSize.Level1) +{ + OnConnectChangedCallBackFail1(); +} + +HWTEST_F(StaMonitorTest, OnConnectChangedCallBackFail2, TestSize.Level1) +{ + OnConnectChangedCallBackFail2(); +} + +HWTEST_F(StaMonitorTest, SetStateMachineSuccess, TestSize.Level1) +{ + SetStateMachineSuccess(); +} + + +HWTEST_F(StaMonitorTest, OnConnectChangedCallBackSuccess1, TestSize.Level1) +{ + OnConnectChangedCallBackSuccess1(); +} + +HWTEST_F(StaMonitorTest, OnConnectChangedCallBackSuccess2, TestSize.Level1) +{ + OnConnectChangedCallBackSuccess2(); +} + +HWTEST_F(StaMonitorTest, OnWpaStateChangedCallBackSuccess, TestSize.Level1) +{ + OnWpaStateChangedCallBackSuccess(); +} + +HWTEST_F(StaMonitorTest, OnWpaStateChangedCallBackFail1, TestSize.Level1) +{ + OnWpaStateChangedCallBackFail1(); +} + +HWTEST_F(StaMonitorTest, OnWpaSsidWrongKeyCallBackSuccess, TestSize.Level1) +{ + OnWpaSsidWrongKeyCallBackSuccess(); +} + +HWTEST_F(StaMonitorTest, OnWpaSsidWrongKeyCallBackFail1, TestSize.Level1) +{ + OnWpaSsidWrongKeyCallBackFail1(); +} + +HWTEST_F(StaMonitorTest, OnWpaSsidWrongKeyCallBackFail2, TestSize.Level1) +{ + OnWpaSsidWrongKeyCallBackFail2(); +} + +HWTEST_F(StaMonitorTest, OnWpsPbcOverlapCallBackSuccess, TestSize.Level1) +{ + OnWpsPbcOverlapCallBackSuccess(); +} + +HWTEST_F(StaMonitorTest, OnWpsPbcOverlapCallBackFail1, TestSize.Level1) +{ + OnWpsPbcOverlapCallBackFail1(); +} + +HWTEST_F(StaMonitorTest, OnWpsTimeOutCallBackSuccess, TestSize.Level1) +{ + OnWpsTimeOutCallBackSuccess(); +} + +HWTEST_F(StaMonitorTest, OnWpsTimeOutCallBackFail1, TestSize.Level1) +{ + OnWpsTimeOutCallBackFail1(); +} +} // WIFI +} // OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check_test.cpp new file mode 100644 index 000000000..1ee7a1ef8 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check_test.cpp @@ -0,0 +1,79 @@ +/* + * 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 "sta_network_check.h" + +#include +#include + +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class StaNetworkCheckTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + virtual void SetUp() + { + pStaNetworkCheck = std::make_unique(handle); + pStaNetworkCheck->InitNetCheckThread(); + } + virtual void TearDown() + { + pStaNetworkCheck->ExitNetCheckThread(); + pStaNetworkCheck.reset(); + } + +public: + void SignalNetCheckThreadSuccess(); + void StopNetCheckThreadSuccess(); + void HttpDetectionSuccess(); + +public: + std::unique_ptr pStaNetworkCheck; + NetStateHandler handle; +}; + +void StaNetworkCheckTest::SignalNetCheckThreadSuccess() +{ + pStaNetworkCheck->SignalNetCheckThread(); +} + +void StaNetworkCheckTest::StopNetCheckThreadSuccess() +{ + pStaNetworkCheck->StopNetCheckThread(); +} + +void StaNetworkCheckTest::HttpDetectionSuccess() +{ + pStaNetworkCheck->HttpDetection(); +} + +HWTEST_F(StaNetworkCheckTest, SignalNetCheckThreadSuccess, TestSize.Level1) +{ + SignalNetCheckThreadSuccess(); +} + +HWTEST_F(StaNetworkCheckTest, StopNetCheckThreadSuccess, TestSize.Level1) +{ + StopNetCheckThreadSuccess(); +} + +HWTEST_F(StaNetworkCheckTest, HttpDetectionSuccess, TestSize.Level1) +{ + HttpDetectionSuccess(); +} +} // Wifi +} // OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal_test.cpp new file mode 100644 index 000000000..8b99c6e29 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal_test.cpp @@ -0,0 +1,289 @@ +/* + * 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 "sta_saved_device_appraisal.h" +#include +#include +#include +#include "wifi_errcode.h" +#include "wifi_internal_msg.h" +#include "wifi_msg.h" + +#include "mock_wifi_settings.h" +#include "mock_device_appraisal.h" + +using ::testing::_; +using ::testing::AtLeast; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::StrEq; +using ::testing::TypedEq; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +constexpr int NETWORK_ID = 15; +constexpr int BAND = 2; +constexpr int RSSI = 8; + +class StaSavedDeviceAppraisalTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + virtual void SetUp() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsScoreSlope()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsInitScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsSameBssidScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsSameNetworkScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsFrequency5GHzScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsLastSelectionScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsSecurityScore()).Times(AtLeast(0)); + pStaSavedDeviceAppraisal = std::make_unique(false); + } + virtual void TearDown() + { + pStaSavedDeviceAppraisal.reset(); + } + +public: + void SaveNetworkEvaluatorSuccess1(); + void SaveNetworkEvaluatorSuccess2(); + void SaveNetworkEvaluatorFail1(); + void AppraiseDeviceQualitySuccess1(); + void AppraiseDeviceQualitySuccess2(); + void WhetherSkipDeviceSuccess1(); + void WhetherSkipDeviceSuccess2(); + void WhetherSkipDeviceFail1(); + +public: + std::unique_ptr pStaSavedDeviceAppraisal; + +private: + void GetScanInfoConfig(InterScanInfo &scanInfo) const; + void GetWifiDeviceConfig(WifiDeviceConfig &deviceConfig) const; + void GetInterScanInfoVector(std::vector &scanInfos) const; + void GetWifiLinkedInfo(WifiLinkedInfo &info); +}; + + +void StaSavedDeviceAppraisalTest::GetScanInfoConfig(InterScanInfo &scanInfo) const +{ + scanInfo.bssid = "2a:76:93:47:e2:8a"; + scanInfo.ssid = "HMWIFI_W2_EAP_G2_03"; + scanInfo.band = NETWORK_24G_BAND; + scanInfo.rssi = RSSI; + scanInfo.securityType = WifiSecurity::OPEN; +} + +void StaSavedDeviceAppraisalTest::GetWifiDeviceConfig(WifiDeviceConfig &deviceConfig) const +{ + deviceConfig.bssid = "2a:76:93:47:e2:8a"; + deviceConfig.band = BAND; + deviceConfig.networkId = NETWORK_ID; + deviceConfig.ssid = "HMWIFI_W2_EAP_G2_03"; + deviceConfig.keyMgmt = "123456"; +} + +void StaSavedDeviceAppraisalTest::GetInterScanInfoVector(std::vector &scanInfos) const +{ + InterScanInfo scanInfo; + GetScanInfoConfig(scanInfo); + scanInfos.push_back(scanInfo); +} + +void StaSavedDeviceAppraisalTest::GetWifiLinkedInfo(WifiLinkedInfo &info) +{ + info.detailedState = DetailedState::WORKING; // WORKING + info.bssid = "2a:76:93:47:e2:8a"; + info.ssid = "HMWIFI_W2_EAP_G2_03"; + info.networkId = NETWORK_ID; + info.connState = ConnState::CONNECTED; +} + +void StaSavedDeviceAppraisalTest::SaveNetworkEvaluatorSuccess1() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + + deviceConfig.status = static_cast(WifiDeviceConfigStatus::ENABLED); + deviceConfig.networkId = 0; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(scanInfos[0].bssid, DEVICE_CONFIG_INDEX_BSSID, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetSignalLevel(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()).Times(AtLeast(1)).WillOnce(Return(0)); + + EXPECT_TRUE(pStaSavedDeviceAppraisal->DeviceAppraisals(deviceConfig, scanInfos, info) == WIFI_OPT_SUCCESS); +} + +void StaSavedDeviceAppraisalTest::SaveNetworkEvaluatorSuccess2() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + + deviceConfig.isPasspoint = false; + deviceConfig.isEphemeral = false; + deviceConfig.status = static_cast(WifiDeviceConfigStatus::ENABLED); + deviceConfig.networkId = 0; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(scanInfos[0].bssid, DEVICE_CONFIG_INDEX_BSSID, _)) + .WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetSignalLevel(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()).Times(AtLeast(1)).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkTimeVal()).Times(AtLeast(1)); + + EXPECT_TRUE(pStaSavedDeviceAppraisal->DeviceAppraisals(deviceConfig, scanInfos, info) == WIFI_OPT_SUCCESS); +} + + +void StaSavedDeviceAppraisalTest::SaveNetworkEvaluatorFail1() +{ + WifiDeviceConfig deviceConfig; + std::vector scanInfos; + WifiLinkedInfo info; + GetWifiDeviceConfig(deviceConfig); + GetInterScanInfoVector(scanInfos); + GetWifiLinkedInfo(info); + + info.connState = ConnState::DISCONNECTED; + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(scanInfos[0].bssid, DEVICE_CONFIG_INDEX_BSSID, _)) + .Times(AtLeast(1)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetSignalLevel(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()).Times(AtLeast(0)).WillOnce(Return(0)); + + EXPECT_TRUE(pStaSavedDeviceAppraisal->DeviceAppraisals(deviceConfig, scanInfos, info) != WIFI_OPT_SUCCESS); +} + +void StaSavedDeviceAppraisalTest::AppraiseDeviceQualitySuccess1() +{ + int score = 1; + InterScanInfo scanInfo; + WifiDeviceConfig deviceConfig; + WifiLinkedInfo info; + GetScanInfoConfig(scanInfo); + GetWifiDeviceConfig(deviceConfig); + GetWifiLinkedInfo(info); + scanInfo.band = NETWORK_24G_BAND; + deviceConfig.networkId = 0; + + EXPECT_CALL(WifiSettings::GetInstance(), GetSignalLevel(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()).Times(AtLeast(1)).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkTimeVal()).Times(AtLeast(1)); + pStaSavedDeviceAppraisal->AppraiseDeviceQuality(score, scanInfo, deviceConfig, info); +} + +void StaSavedDeviceAppraisalTest::AppraiseDeviceQualitySuccess2() +{ + int score = 1; + InterScanInfo scanInfo; + WifiDeviceConfig deviceConfig; + WifiLinkedInfo info; + GetScanInfoConfig(scanInfo); + GetWifiDeviceConfig(deviceConfig); + GetWifiLinkedInfo(info); + scanInfo.band = NETWORK_5G_BAND; + deviceConfig.networkId = 0; + + EXPECT_CALL(WifiSettings::GetInstance(), GetSignalLevel(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()).Times(AtLeast(1)).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkTimeVal()).Times(AtLeast(1)); + pStaSavedDeviceAppraisal->AppraiseDeviceQuality(score, scanInfo, deviceConfig, info); +} + +void StaSavedDeviceAppraisalTest::WhetherSkipDeviceSuccess1() +{ + WifiDeviceConfig deviceConfig; + GetWifiDeviceConfig(deviceConfig); + deviceConfig.isPasspoint = false; + deviceConfig.isEphemeral = false; + deviceConfig.status = static_cast(WifiDeviceConfigStatus::ENABLED); + + EXPECT_TRUE(pStaSavedDeviceAppraisal->WhetherSkipDevice(deviceConfig) == true); +} + +void StaSavedDeviceAppraisalTest::WhetherSkipDeviceSuccess2() +{ + WifiDeviceConfig deviceConfig; + GetWifiDeviceConfig(deviceConfig); + + deviceConfig.isPasspoint = false; + deviceConfig.isEphemeral = false; + deviceConfig.status = static_cast(WifiDeviceConfigStatus::CURRENT); + EXPECT_TRUE(pStaSavedDeviceAppraisal->WhetherSkipDevice(deviceConfig) == true); +} + +void StaSavedDeviceAppraisalTest::WhetherSkipDeviceFail1() +{ + WifiDeviceConfig deviceConfig; + GetWifiDeviceConfig(deviceConfig); + deviceConfig.isPasspoint = true; + deviceConfig.isEphemeral = true; + deviceConfig.status = static_cast(WifiDeviceConfigStatus::ENABLED); + EXPECT_TRUE(pStaSavedDeviceAppraisal->WhetherSkipDevice(deviceConfig) == false); +} + +HWTEST_F(StaSavedDeviceAppraisalTest, SaveNetworkEvaluatorSuccess1, TestSize.Level1) +{ + SaveNetworkEvaluatorSuccess1(); +} + +HWTEST_F(StaSavedDeviceAppraisalTest, SaveNetworkEvaluatorSuccess2, TestSize.Level1) +{ + SaveNetworkEvaluatorSuccess2(); +} + +HWTEST_F(StaSavedDeviceAppraisalTest, SaveNetworkEvaluatorFail1, TestSize.Level1) +{ + SaveNetworkEvaluatorFail1(); +} + +HWTEST_F(StaSavedDeviceAppraisalTest, AppraiseDeviceQualitySuccess1, TestSize.Level1) +{ + AppraiseDeviceQualitySuccess1(); +} + +HWTEST_F(StaSavedDeviceAppraisalTest, AppraiseDeviceQualitySuccess2, TestSize.Level1) +{ + AppraiseDeviceQualitySuccess2(); +} + +HWTEST_F(StaSavedDeviceAppraisalTest, WhetherSkipDeviceSuccess1, TestSize.Level1) +{ + WhetherSkipDeviceSuccess1(); +} + +HWTEST_F(StaSavedDeviceAppraisalTest, WhetherSkipDeviceSuccess2, TestSize.Level1) +{ + WhetherSkipDeviceSuccess2(); +} + +HWTEST_F(StaSavedDeviceAppraisalTest, WhetherSkipDeviceFail1, TestSize.Level1) +{ + WhetherSkipDeviceFail1(); +} +} // Wifi +} // OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_test.cpp new file mode 100644 index 000000000..aaa3da5ba --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_test.cpp @@ -0,0 +1,678 @@ +/* + * 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 "sta_service.h" +#include +#include "mock_wifi_manager.h" +#include "mock_wifi_settings.h" +#include "mock_sta_state_machine.h" +#include "mock_wifi_sta_hal_interface.h" +#include "mock_wifi_supplicant_hal_interface.h" +#include "mock_dhcp_service.h" +#include "mock_sta_auto_connect_service.h" +#include "sta_define.h" +#include "wifi_msg.h" +#include "wifi_internal_msg.h" + +using ::testing::_; +using ::testing::AtLeast; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Ref; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::StrEq; +using ::testing::TypedEq; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +constexpr int NETWORK_ID = 15; +constexpr int BAND = 2; +constexpr int FREQUENCY = 2437; +constexpr int TIMESTAMP = -750366468; + +class StaServiceTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + virtual void SetUp() + { + pStaService = std::make_unique(); + pStaService->pStaStateMachine = new MockStaStateMachine(); + pStaService->pStaAutoConnectService = new MockStaAutoConnectService(pStaService->pStaStateMachine); + } + virtual void TearDown() + { + pStaService.reset(); + } + + void StaServiceInitStaServiceSuccess(); + void StaServiceEnableWifiSuccess(); + void StaServiceEnableWifiFail(); + void StaServiceDisableWifiSuccess(); + void StaServiceDisableWifiFail(); + void StaServiceConnectToWifiDeviceConfigSuccess(); + void StaServiceConnectToWifiDeviceConfigFail1(); + void StaServiceConnectToWifiDeviceConfigFail2(); + void StaServiceConnectToWifiDeviceConfigFail3(); + void StaServiceConnectToNetworkIdSuccess(); + void StaServiceConnectToNetworkIdFail1(); + void StaServiceReAssociateSuccess(); + void StaServiceAddDeviceConfigSuccess(); + void StaServiceAddDeviceConfigFail1(); + void StaServiceAddDeviceConfigFail2(); + void StaServiceAddDeviceConfigFail3(); + void StaServiceUpdateDeviceConfigSuccess(); + void StaServiceRemoveDeviceConfigSuccess(); + void StaServiceRemoveDeviceConfigFail1(); + void StaServiceEnableDeviceConfigSuccess(); + void StaServiceEnableDeviceConfigFail1(); + void StaServiceEnableDeviceConfigFail2(); + void StaServiceDisableDeviceConfigSuccess(); + void StaServiceDisableDeviceConfigFail1(); + void StaServiceDisconnectSuccess(); + void StaServiceStartWpsSuccess(); + void StaServiceCancelWpsSuccess(); + void StaServiceSetCountryCodeSuccess(); + void StaServiceSetCountryCodeFail(); + void StaServiceAutoConnectServiceSuccess(); + void StaServiceRegisterStaServiceCallbackSuccess(); + void StaServiceRegisterStaServiceCallbackFail(); +public: + std::unique_ptr pStaService; +}; + +void StaServiceTest::StaServiceInitStaServiceSuccess() +{ + WifiIdlRoamCapability capability; + capability.maxBlocklistSize = 1; + + EXPECT_CALL(WifiStaHalInterface::GetInstance(), RegisterStaEventCallback(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartWifi()).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), WpaAutoConnect(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetStaDeviceMacAddress(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetStaCapabilities(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsScoreSlope()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsInitScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsSameBssidScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsSameNetworkScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsFrequency5GHzScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsLastSelectionScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScoretacticsSecurityScore()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetSavedDeviceAppraisalPriority()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetExternDeviceAppraisalPriority()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ReloadDeviceConfig()).Times(AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), ClearDeviceConfig()).Times(AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()).Times(AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + + EXPECT_TRUE(pStaService->InitStaService(WifiManager::GetInstance().GetStaCallback()) == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceEnableWifiSuccess() +{ + EXPECT_TRUE(pStaService->EnableWifi() == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceEnableWifiFail() +{ +} + +void StaServiceTest::StaServiceDisableWifiSuccess() +{ + EXPECT_TRUE(pStaService->DisableWifi() == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceDisableWifiFail() +{ +} + +void StaServiceTest::StaServiceConnectToWifiDeviceConfigSuccess() +{ + WifiDeviceConfig config; + config.bssid = "01:23:45:67:89:AB"; + config.band = BAND; + config.networkId = NETWORK_ID; + config.ssid = "networkId"; + config.keyMgmt = "123456"; + + WifiLinkedInfo info; + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .Times(AtLeast(0)).WillOnce(DoAll(SetArgReferee<1>(config), Return(0))); + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(config.ssid, config.keyMgmt, _)) + .WillOnce(DoAll(SetArgReferee<2>(config), Return(0))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), AddDeviceConfig(_)).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), SyncDeviceConfig()).Times(AtLeast(1)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pStaService->ConnectToDevice(config) == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceConnectToWifiDeviceConfigFail1() +{ + WifiDeviceConfig config; + config.bssid = "01:23:45:67:89:AB"; + config.band = BAND; + config.networkId = NETWORK_ID; + config.keyMgmt = "123456"; + config.ssid = "networkId"; + + WifiLinkedInfo info; + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .Times(AtLeast(0)).WillOnce(DoAll(SetArgReferee<1>(config), Return(0))); + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(config.ssid, config.keyMgmt, _)) + .WillOnce(DoAll(SetArgReferee<2>(config), Return(-1))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetNextNetworkId(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), AddDeviceConfig(_)).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), SyncDeviceConfig()).Times(AtLeast(1)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pStaService->ConnectToDevice(config) == WIFI_OPT_FAILED); +} + +void StaServiceTest::StaServiceConnectToWifiDeviceConfigFail2() +{ + WifiDeviceConfig config; + config.bssid = "01:23:45:67:89:AB"; + config.band = BAND; + config.networkId = NETWORK_ID; + config.keyMgmt = "123456"; + config.ssid = "networkId"; + + WifiLinkedInfo info; + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .Times(AtLeast(0)).WillOnce(DoAll(SetArgReferee<1>(config), Return(0))); + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(config.ssid, config.keyMgmt, _)) + .WillOnce(DoAll(SetArgReferee<2>(config), Return(-1))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetNextNetworkId(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pStaService->ConnectToDevice(config) == WIFI_OPT_FAILED); +} + + +void StaServiceTest::StaServiceConnectToWifiDeviceConfigFail3() +{ + WifiDeviceConfig config; + config.bssid = "01:23:45:67:89:AB"; + config.band = BAND; + config.networkId = NETWORK_ID; + config.keyMgmt = "123456"; + config.ssid = "networkId"; + + WifiLinkedInfo info; + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .Times(AtLeast(0)).WillOnce(DoAll(SetArgReferee<1>(config), Return(0))); + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(config.ssid, config.keyMgmt, _)) + .WillOnce(DoAll(SetArgReferee<2>(config), Return(0))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pStaService->ConnectToDevice(config) == WIFI_OPT_FAILED); +} + +void StaServiceTest::StaServiceConnectToNetworkIdSuccess() +{ + int networkId = NETWORK_ID; + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)).WillRepeatedly(Return(0)); + EXPECT_TRUE(pStaService->ConnectToNetwork(networkId) == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceConnectToNetworkIdFail1() +{ + int networkId = NETWORK_ID; + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)).WillRepeatedly(Return(-1)); + EXPECT_TRUE(pStaService->ConnectToNetwork(networkId) == WIFI_OPT_FAILED); +} + +void StaServiceTest::StaServiceReAssociateSuccess() +{ + EXPECT_TRUE(pStaService->ReAssociate() == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceAddDeviceConfigSuccess() +{ + WifiDeviceConfig config; + config.bssid = "01:23:45:67:89:AB"; + config.band = 1; + config.networkId = NETWORK_ID; + config.ssid = "networkId"; + config.keyMgmt = "123456"; + + WifiLinkedInfo info; + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .Times(AtLeast(0)).WillOnce(DoAll(SetArgReferee<1>(config), Return(0))); + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(config.ssid, config.keyMgmt, _)) + .WillOnce(DoAll(SetArgReferee<2>(config), Return(0))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetNextNetworkId(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), AddDeviceConfig(_)).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), SyncDeviceConfig()).Times(AtLeast(1)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pStaService->AddDeviceConfig(config) != INVALID_NETWORK_ID); +} + +void StaServiceTest::StaServiceAddDeviceConfigFail1() +{ + WifiDeviceConfig config; + config.bssid = "01:23:45:67:89:AB"; + config.band = BAND; + config.networkId = NETWORK_ID; + config.ssid = "networkId"; + config.keyMgmt = "123456"; + + WifiLinkedInfo info; + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .Times(AtLeast(0)).WillOnce(DoAll(SetArgReferee<1>(config), Return(0))); + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(config.ssid, config.keyMgmt, _)) + .WillOnce(DoAll(SetArgReferee<2>(config), Return(-1))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetNextNetworkId(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), AddDeviceConfig(_)).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), SyncDeviceConfig()).Times(AtLeast(1)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pStaService->AddDeviceConfig(config) == INVALID_NETWORK_ID); +} + +void StaServiceTest::StaServiceAddDeviceConfigFail2() +{ + WifiDeviceConfig config; + config.bssid = "01:23:45:67:89:AB"; + config.band = BAND; + config.networkId = NETWORK_ID; + config.ssid = "networkId"; + config.keyMgmt = "123456"; + + WifiLinkedInfo info; + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .Times(AtLeast(0)).WillOnce(DoAll(SetArgReferee<1>(config), Return(0))); + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(config.ssid, config.keyMgmt, _)) + .WillOnce(DoAll(SetArgReferee<2>(config), Return(-1))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetNextNetworkId(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pStaService->AddDeviceConfig(config) == INVALID_NETWORK_ID); +} + + +void StaServiceTest::StaServiceAddDeviceConfigFail3() +{ + WifiDeviceConfig config; + config.bssid = "01:23:45:67:89:AB"; + config.band = BAND; + config.networkId = NETWORK_ID; + config.ssid = "networkId"; + config.keyMgmt = "123456"; + + WifiLinkedInfo info; + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .Times(AtLeast(0)).WillOnce(DoAll(SetArgReferee<1>(config), Return(0))); + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(config.ssid, config.keyMgmt, _)) + .WillOnce(DoAll(SetArgReferee<2>(config), Return(0))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pStaService->AddDeviceConfig(config) == INVALID_NETWORK_ID); +} + +void StaServiceTest::StaServiceUpdateDeviceConfigSuccess() +{ + WifiDeviceConfig config; + config.bssid = "01:23:45:67:89:A1"; + config.band = 2; + config.networkId = NETWORK_ID; + config.ssid = "networkId"; + config.keyMgmt = "12345678"; + + WifiLinkedInfo info; + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .Times(AtLeast(0)).WillOnce(DoAll(SetArgReferee<1>(config), Return(0))); + + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(config.ssid, config.keyMgmt, _)) + .WillOnce(DoAll(SetArgReferee<2>(config), Return(0))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetNextNetworkId(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), AddDeviceConfig(_)).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), SyncDeviceConfig()).Times(AtLeast(1)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pStaService->UpdateDeviceConfig(config) != INVALID_NETWORK_ID); +} + +void StaServiceTest::StaServiceRemoveDeviceConfigSuccess() +{ + int networkId = NETWORK_ID; + EXPECT_CALL(WifiStaHalInterface::GetInstance(), RemoveDevice(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)).Times(AtLeast(0)).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), RemoveDevice(_)).Times(AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), SyncDeviceConfig()).Times(AtLeast(1)); + EXPECT_TRUE(pStaService->RemoveDevice(networkId) == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceRemoveDeviceConfigFail1() +{ + int networkId = NETWORK_ID; + EXPECT_CALL(WifiStaHalInterface::GetInstance(), RemoveDevice(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pStaService->RemoveDevice(networkId) == WIFI_OPT_FAILED); +} + +void StaServiceTest::StaServiceEnableDeviceConfigSuccess() +{ + int networkId = NETWORK_ID; + bool attemptEnable = true; + EXPECT_CALL(WifiSettings::GetInstance(), + SetDeviceState(networkId, (int)WifiDeviceConfigStatus::ENABLED, attemptEnable)) + .WillRepeatedly(Return(0)); + EXPECT_TRUE(pStaService->EnableDeviceConfig(networkId, attemptEnable) == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceEnableDeviceConfigFail1() +{ + int networkId = NETWORK_ID; + bool attemptEnable = true; + EXPECT_CALL(WifiSettings::GetInstance(), + SetDeviceState(networkId, (int)WifiDeviceConfigStatus::ENABLED, attemptEnable)) + .WillRepeatedly(Return(-1)); + EXPECT_TRUE(pStaService->EnableDeviceConfig(networkId, attemptEnable) == WIFI_OPT_FAILED); +} + +void StaServiceTest::StaServiceEnableDeviceConfigFail2() +{ + int networkId = NETWORK_ID; + bool attemptEnable = true; + EXPECT_TRUE(pStaService->EnableDeviceConfig(networkId, attemptEnable) == WIFI_OPT_FAILED); +} + +void StaServiceTest::StaServiceDisableDeviceConfigSuccess() +{ + int networkId = NETWORK_ID; + bool attemptEnable = false; + EXPECT_CALL(WifiSettings::GetInstance(), + SetDeviceState(networkId, (int)WifiDeviceConfigStatus::DISABLED, attemptEnable)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pStaService->DisableDeviceConfig(networkId) == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceDisableDeviceConfigFail1() +{ + int networkId = NETWORK_ID; + bool attemptEnable = false; + EXPECT_CALL(WifiSettings::GetInstance(), + SetDeviceState(networkId, (int)WifiDeviceConfigStatus::DISABLED, attemptEnable)) + .WillRepeatedly(Return(-1)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pStaService->DisableDeviceConfig(networkId) == WIFI_OPT_FAILED); +} + +void StaServiceTest::StaServiceDisconnectSuccess() +{ + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).Times(AtLeast(1)); + EXPECT_TRUE(pStaService->Disconnect() == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceStartWpsSuccess() +{ + WpsConfig config; + config.setup = SetupMethod::PBC; + config.pin = "12345678"; + config.bssid = "01:23:45:67:89:AB"; + EXPECT_TRUE(pStaService->StartWps(config) == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceCancelWpsSuccess() +{ + EXPECT_TRUE(pStaService->CancelWps() == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceSetCountryCodeSuccess() +{ + std::string countryCode = "123456"; + EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), WpaSetCountryCode(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SetCountryCode(_)).Times(AtLeast(1)); + EXPECT_TRUE(pStaService->SetCountryCode(countryCode) == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceSetCountryCodeFail() +{ + std::string countryCode = "123456"; + EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), WpaSetCountryCode(_)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pStaService->SetCountryCode(countryCode) == WIFI_OPT_FAILED); +} + +void StaServiceTest::StaServiceAutoConnectServiceSuccess() +{ + std::vector scanInfos; + InterScanInfo scanInfo; + scanInfo.bssid = "2a:76:93:47:e2:8a"; + scanInfo.ssid = "HMWIFI_W2_EAP_G2_03"; + scanInfo.capabilities = "[RSN-EAP-CCMP][WPA2-EAP-CCMP][ESS]"; + scanInfo.frequency = FREQUENCY; + scanInfo.timestamp = TIMESTAMP; + scanInfos.push_back(scanInfo); + EXPECT_TRUE(pStaService->AutoConnectService(scanInfos) == WIFI_OPT_SUCCESS); +} + +void StaServiceTest::StaServiceRegisterStaServiceCallbackSuccess() +{ + WifiManager &instance = WifiManager::GetInstance(); + pStaService->RegisterStaServiceCallback(instance.GetStaCallback()); +} + +void StaServiceTest::StaServiceRegisterStaServiceCallbackFail() +{ + WifiManager &instance = WifiManager::GetInstance(); + pStaService->RegisterStaServiceCallback(instance.GetStaCallback()); +} + +HWTEST_F(StaServiceTest, StaServiceInitStaServiceSuccess, TestSize.Level1) +{ + StaServiceInitStaServiceSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceEnableWifiSuccess, TestSize.Level1) +{ + StaServiceEnableWifiSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceEnableWifiFail, TestSize.Level1) +{ + StaServiceEnableWifiFail(); +} + +HWTEST_F(StaServiceTest, StaServiceDisableWifiSuccess, TestSize.Level1) +{ + StaServiceDisableWifiSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceDisableWifiFail, TestSize.Level1) +{ + StaServiceDisableWifiFail(); +} + +HWTEST_F(StaServiceTest, StaServiceConnectToWifiDeviceConfigSuccess, TestSize.Level1) +{ + StaServiceConnectToWifiDeviceConfigSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceConnectToWifiDeviceConfigFail1, TestSize.Level1) +{ + StaServiceConnectToWifiDeviceConfigFail1(); +} + +HWTEST_F(StaServiceTest, StaServiceConnectToWifiDeviceConfigFail2, TestSize.Level1) +{ + StaServiceConnectToWifiDeviceConfigFail2(); +} + +HWTEST_F(StaServiceTest, StaServiceConnectToWifiDeviceConfigFail3, TestSize.Level1) +{ + StaServiceConnectToWifiDeviceConfigFail3(); +} + +HWTEST_F(StaServiceTest, StaServiceConnectToNetworkIdSuccess, TestSize.Level1) +{ + StaServiceConnectToNetworkIdSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceConnectToNetworkIdFail1, TestSize.Level1) +{ + StaServiceConnectToNetworkIdFail1(); +} + +HWTEST_F(StaServiceTest, StaServiceReAssociateSuccess, TestSize.Level1) +{ + StaServiceReAssociateSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceAddDeviceConfigSuccess, TestSize.Level1) +{ + StaServiceAddDeviceConfigSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceAddDeviceConfigFail1, TestSize.Level1) +{ + StaServiceAddDeviceConfigFail1(); +} + +HWTEST_F(StaServiceTest, StaServiceAddDeviceConfigFail2, TestSize.Level1) +{ + StaServiceAddDeviceConfigFail2(); +} + +HWTEST_F(StaServiceTest, StaServiceAddDeviceConfigFail3, TestSize.Level1) +{ + StaServiceAddDeviceConfigFail3(); +} + +HWTEST_F(StaServiceTest, StaServiceUpdateDeviceConfigSuccess, TestSize.Level1) +{ + StaServiceUpdateDeviceConfigSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceRemoveDeviceConfigSuccess, TestSize.Level1) +{ + StaServiceRemoveDeviceConfigSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceRemoveDeviceConfigFail1, TestSize.Level1) +{ + StaServiceRemoveDeviceConfigFail1(); +} + +HWTEST_F(StaServiceTest, StaServiceEnableDeviceConfigSuccess, TestSize.Level1) +{ + StaServiceEnableDeviceConfigSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceEnableDeviceConfigFail1, TestSize.Level1) +{ + StaServiceEnableDeviceConfigFail1(); +} + +HWTEST_F(StaServiceTest, StaServiceEnableDeviceConfigFail2, TestSize.Level1) +{ + StaServiceEnableDeviceConfigFail2(); +} + +HWTEST_F(StaServiceTest, StaServiceDisableDeviceConfigSuccess, TestSize.Level1) +{ + StaServiceDisableDeviceConfigSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceDisableDeviceConfigFail1, TestSize.Level1) +{ + StaServiceDisableDeviceConfigFail1(); +} + +HWTEST_F(StaServiceTest, StaServiceDisconnectSuccess, TestSize.Level1) +{ + StaServiceDisconnectSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceStartWpsSuccess, TestSize.Level1) +{ + StaServiceStartWpsSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceCancelWpsSuccess, TestSize.Level1) +{ + StaServiceCancelWpsSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceSetCountryCodeSuccess, TestSize.Level1) +{ + StaServiceSetCountryCodeSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceSetCountryCodeFail, TestSize.Level1) +{ + StaServiceSetCountryCodeFail(); +} + +HWTEST_F(StaServiceTest, StaServiceAutoConnectServiceSuccess, TestSize.Level1) +{ + StaServiceAutoConnectServiceSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceRegisterStaServiceCallbackSuccess, TestSize.Level1) +{ + StaServiceRegisterStaServiceCallbackSuccess(); +} + +HWTEST_F(StaServiceTest, StaServiceRegisterStaServiceCallbackFail, TestSize.Level1) +{ + StaServiceRegisterStaServiceCallbackFail(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine_test.cpp new file mode 100644 index 000000000..0d5575883 --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine_test.cpp @@ -0,0 +1,2043 @@ +/* + * 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 "sta_state_machine.h" +#include "sta_define.h" +#include "mock_wifi_settings.h" +#include "mock_wifi_supplicant_hal_interface.h" +#include "mock_wifi_sta_hal_interface.h" +#include "mock_wifi_manager.h" +#include "mock_dhcp_service.h" +#include "mock_wifi_chip_hal_interface.h" +#include "mock_sta_network_check.h" +#include "mock_if_config.h" +#include +#include "internal_message.h" + +using ::testing::_; +using ::testing::AtLeast; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::SetArgReferee; +using ::testing::StrEq; +using ::testing::TypedEq; +using ::testing::ext::TestSize; + +namespace OHOS { +namespace Wifi { +class StaStateMachineTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + virtual void SetUp() + { + pStaStateMachine.reset(new StaStateMachine()); + pStaStateMachine->InitStaStateMachine(); + + NetStateHandler handle; + pStaStateMachine->pNetcheck = new MockStaNetworkCheck(handle); + pStaStateMachine->RegisterStaServiceCallback(WifiManager::GetInstance().GetStaCallback()); + } + virtual void TearDown() + { + pStaStateMachine.reset(); + } + void SleepMs(const int sleepMs) + { + std::unique_lock lck(mMtxBlock); + mCvTest.wait_for(lck, std::chrono::milliseconds(sleepMs)); + } + std::unique_ptr pStaStateMachine; + std::mutex mMtxBlock; + std::condition_variable mCvTest; + + void InitWifiLinkedInfoSuccess() + { + pStaStateMachine->InitWifiLinkedInfo(); + } + + void InitLastWifiLinkedInfoSuccess() + { + pStaStateMachine->InitLastWifiLinkedInfo(); + } + + void BuildStateTreeSuccess() + { + pStaStateMachine->BuildStateTree(); + } + + void RegisterStaServiceCallbackSuccess() + { + StaServiceCallback callbacks; + pStaStateMachine->RegisterStaServiceCallback(callbacks); + } + + void DealConnectTimeOutCmd() + { + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), DisableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(1)); + InternalMessage msg; + pStaStateMachine->DealConnectTimeOutCmd(&msg); + } + + void RootStateGoInStateSuccess() + { + pStaStateMachine->pRootState->GoInState(); + } + + void RootStateGoOutStateSuccess() + { + pStaStateMachine->pRootState->GoOutState(); + } + + void RootStateExeMsgSuccess() + { + InternalMessage msg; + EXPECT_TRUE(pStaStateMachine->pRootState->ExecuteStateMsg(&msg)); + } + + void RootStateExeMsgFail() + { + EXPECT_FALSE(pStaStateMachine->pRootState->ExecuteStateMsg(nullptr)); + } + + void InitStateGoInStateSuccess() + { + pStaStateMachine->pInitState->GoInState(); + } + + void InitStateGoOutStateSuccess() + { + pStaStateMachine->pInitState->GoOutState(); + } + + void InitStateExeMsgSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartWifi()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), WpaAutoConnect(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaOpenRes(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ReloadDeviceConfig()).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), ClearDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SetMacAddress(_)).Times(testing::AtLeast(0)); + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_ENABLE_WIFI); + EXPECT_TRUE(pStaStateMachine->pInitState->ExecuteStateMsg(&msg)); + } + + void InitStateExeMsgFail1() + { + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_DISABLE_WIFI); + EXPECT_FALSE(pStaStateMachine->pInitState->ExecuteStateMsg(&msg)); + } + + void InitStateExeMsgFail2() + { + EXPECT_FALSE(pStaStateMachine->pInitState->ExecuteStateMsg(nullptr)); + } + + void ConvertDeviceCfgSuccess() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + WifiDeviceConfig config; + EXPECT_EQ(WIFI_OPT_SUCCESS, pStaStateMachine->ConvertDeviceCfg(config)); + } + + void ConvertDeviceCfgFail1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)) + .WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + WifiDeviceConfig config; + EXPECT_EQ(WIFI_OPT_FAILED, pStaStateMachine->ConvertDeviceCfg(config)); + } + + void ConvertDeviceCfgFail2() + { + } + + void StartWifiProcessSuccess() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartWifi()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), WpaAutoConnect(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaOpenRes(_)).Times(testing::AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)); + EXPECT_CALL(WifiSettings::GetInstance(), ReloadDeviceConfig()).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), ClearDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SetMacAddress(_)).Times(testing::AtLeast(0)); + std::vector results; + WifiDeviceConfig wifiDeviceConfig; + wifiDeviceConfig.networkId = 1; + results.push_back(wifiDeviceConfig); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(results), Return(0))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetNextNetworkId(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(1), Return(WIFI_IDL_OPT_FAILED))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(testing::AtLeast(0)); + pStaStateMachine->StartWifiProcess(); + } + + void StartWifiProcessFail1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartWifi()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), WpaAutoConnect(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaOpenRes(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ReloadDeviceConfig()).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), ClearDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SetMacAddress(_)).Times(testing::AtLeast(0)); + std::vector results; + WifiDeviceConfig wifiDeviceConfig; + wifiDeviceConfig.networkId = 1; + results.push_back(wifiDeviceConfig); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(results), Return(0))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), ClearDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(testing::AtLeast(0)); + pStaStateMachine->StartWifiProcess(); + } + + void StartWifiProcessFail2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartWifi()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), WpaAutoConnect(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaOpenRes(_)).Times(testing::AtLeast(1)); + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetMacAddress(_)).Times(testing::AtLeast(0)); + pStaStateMachine->StartWifiProcess(); + } + + void InitWpsSettingsSuccess() + { + pStaStateMachine->pWpaStartingState->InitWpsSettings(); + } + + void WpaStartingStateGoInStateSuccess() + { + pStaStateMachine->pWpaStartingState->GoInState(); + } + + void WpaStartingStateGoOutStateSuccess() + { + pStaStateMachine->pWpaStartingState->GoOutState(); + } + + void WpaStartingStateExeMsgSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(testing::AtLeast(0)); + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_SUP_CONNECTION_EVENT); + EXPECT_TRUE(pStaStateMachine->pWpaStartingState->ExecuteStateMsg(&msg)); + } + + void WpaStartingStateExeMsgFail1() + { + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_SUP_DISCONNECTION_EVENT); + EXPECT_FALSE(pStaStateMachine->pWpaStartingState->ExecuteStateMsg(&msg)); + } + + void WpaStartingStateExeMsgFail2() + { + EXPECT_FALSE(pStaStateMachine->pWpaStartingState->ExecuteStateMsg(nullptr)); + } + + void WpaStartedStateGoInStateSuccess1() + { + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(testing::AtLeast(1)); + pStaStateMachine->operationalMode = STA_CONNECT_MODE; + pStaStateMachine->pWpaStartedState->GoInState(); + } + + void WpaStartedStateGoInStateSuccess2() + { + pStaStateMachine->operationalMode = STA_DISABLED_MODE; + pStaStateMachine->pWpaStartedState->GoInState(); + } + + void WpaStartedStateGoOutStateSuccess() + { + pStaStateMachine->pWpaStartedState->GoOutState(); + } + + void WpaStartedStateExeMsgSuccess() + { + EXPECT_CALL(WifiManager::GetInstance(), DealStaCloseRes(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetMacAddress(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(IfConfig::GetInstance(), FlushIpAddr(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopWifi()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_DISABLE_WIFI); + EXPECT_TRUE(pStaStateMachine->pWpaStartedState->ExecuteStateMsg(&msg)); + } + + void WpaStartedStateExeMsgFail1() + { + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_ENABLE_WIFI); + EXPECT_FALSE(pStaStateMachine->pWpaStartedState->ExecuteStateMsg(&msg)); + } + + void WpaStartedStateExeMsgFail2() + { + EXPECT_FALSE(pStaStateMachine->pWpaStartedState->ExecuteStateMsg(nullptr)); + } + + void StopWifiProcessSuccess1() + { + pStaStateMachine->currentTpType = IPTYPE_IPV4; + EXPECT_CALL(WifiManager::GetInstance(), DealStaCloseRes(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetMacAddress(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopWifi()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pStaStateMachine->StopWifiProcess(); + } + + void StopWifiProcessSuccess2() + { + pStaStateMachine->currentTpType = IPTYPE_IPV6; + EXPECT_CALL(WifiManager::GetInstance(), DealStaCloseRes(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetMacAddress(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopWifi()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pStaStateMachine->StopWifiProcess(); + } + + void StopWifiProcessFail() + { + pStaStateMachine->currentTpType = IPTYPE_IPV6; + EXPECT_CALL(WifiManager::GetInstance(), DealStaCloseRes(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetMacAddress(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopWifi()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + pStaStateMachine->StopWifiProcess(); + } + + void WpaStoppingStateGoInStateSuccess() + { + pStaStateMachine->pWpaStoppingState->GoInState(); + } + + void WpaStoppingStateGoOutStateSuccess() + { + pStaStateMachine->pWpaStoppingState->GoOutState(); + } + + void WpaStoppingStateExeMsgSuccess() + { + InternalMessage msg; + pStaStateMachine->pWpaStoppingState->ExecuteStateMsg(&msg); + } + + void WpaStoppingStateExeMsgFail() + { + pStaStateMachine->pWpaStoppingState->ExecuteStateMsg(nullptr); + } + + void LinkStateGoInStateSuccess() + { + pStaStateMachine->pLinkedState->GoInState(); + } + + void LinkStateGoOutStateSuccess() + { + pStaStateMachine->pLinkedState->GoOutState(); + } + + void LinkStateExeMsgFail() + { + EXPECT_FALSE(pStaStateMachine->pLinkedState->ExecuteStateMsg(nullptr)); + } + + void InitStaSMHandleMapSuccess() + { + EXPECT_EQ(WIFI_OPT_SUCCESS, pStaStateMachine->InitStaSMHandleMap()); + } + + void DealConnectToUserSelectedNetworkSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), EnableNetwork(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetDeviceState(_, _, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), EnableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Connect(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScanInfoList(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(testing::AtLeast(0)); + InternalMessage msg; + msg.SetParam1(0); + msg.SetParam2(0); + pStaStateMachine->DealConnectToUserSelectedNetwork(&msg); + } + + void DealConnectToUserSelectedNetworkFail() + { + pStaStateMachine->DealConnectToUserSelectedNetwork(nullptr); + } + + void DealConnectTimeOutCmdSuccess() + { + InternalMessage msg; + pStaStateMachine->DealConnectToUserSelectedNetwork(nullptr); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), DisableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); + pStaStateMachine->DealConnectTimeOutCmd(&msg); + } + + void DealConnectTimeOutCmdFail() + { + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(testing::AtLeast(0)); + pStaStateMachine->DealConnectTimeOutCmd(nullptr); + } + + void DealConnectionEventSuccess1() + { + EXPECT_CALL(WifiSettings::GetInstance(), SetMacAddress(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(IfConfig::GetInstance(), FlushIpAddr(_, _)).Times(AtLeast(0)); + pStaStateMachine->wpsState = SetupMethod::INVALID; + pStaStateMachine->currentTpType = IPTYPE_IPV4; + pStaStateMachine->lastLinkedInfo.detailedState = DetailedState::CONNECTING; + InternalMessage msg; + pStaStateMachine->DealDisconnectEvent(&msg); + } + + void DealConnectionEventSuccess2() + { + EXPECT_CALL(WifiSettings::GetInstance(), SetMacAddress(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)); + EXPECT_CALL(IfConfig::GetInstance(), FlushIpAddr(_, _)).Times(AtLeast(0)); + pStaStateMachine->wpsState = SetupMethod::INVALID; + pStaStateMachine->currentTpType = IPTYPE_IPV6; + pStaStateMachine->lastLinkedInfo.detailedState = DetailedState::CONNECTED; + InternalMessage msg; + pStaStateMachine->DealDisconnectEvent(&msg); + } + + void DealWpaWrongPskEventSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); + InternalMessage msg; + pStaStateMachine->DealWpaWrongPskEvent(&msg); + } + + void DealWpaWrongPskEventFail() + { + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); + InternalMessage msg; + pStaStateMachine->DealWpaWrongPskEvent(nullptr); + } + + void DealReassociateCmdSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkTimeVal()); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Reassociate()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); + InternalMessage msg; + pStaStateMachine->DealReassociateCmd(&msg); + } + + void DealReassociateCmdFail1() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkTimeVal()); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Reassociate()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); + pStaStateMachine->DealReassociateCmd(nullptr); + } + + void DealReassociateCmdFail2() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkTimeVal()); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Reassociate()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + pStaStateMachine->DealReassociateCmd(nullptr); + } + + void DealStartWpsCmdSuccess() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetNetworkList(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)); + pStaStateMachine->wpsState = SetupMethod::DISPLAY; + InternalMessage msg; + msg.SetParam1(static_cast(SetupMethod::INVALID)); + pStaStateMachine->DealStartWpsCmd(&msg); + } + + void StartWpsModeSuccess1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartWpsPbcMode(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)); + InternalMessage msg; + msg.SetParam1(static_cast(SetupMethod::PBC)); + pStaStateMachine->StartWpsMode(&msg); + } + + void StartWpsModeSuccess2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartWpsPinMode(_, _)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)); + InternalMessage msg; + msg.SetParam1(static_cast(SetupMethod::DISPLAY)); + msg.AddStringMessageBody("hmwifi1"); + msg.AddStringMessageBody("hmwifi2"); + pStaStateMachine->StartWpsMode(&msg); + } + + void StartWpsModeSuccess3() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartWpsPinMode(_, _)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)); + InternalMessage msg; + msg.SetParam1(static_cast(SetupMethod::KEYPAD)); + msg.AddStringMessageBody("hmwifi1"); + msg.AddStringMessageBody("hmwifi2"); + pStaStateMachine->StartWpsMode(&msg); + } + + void StartWpsModeSuccess4() + { + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)); + InternalMessage msg; + msg.SetParam1(static_cast(SetupMethod::INVALID)); + msg.AddStringMessageBody("hmwifi1"); + msg.AddStringMessageBody("hmwifi2"); + pStaStateMachine->StartWpsMode(&msg); + } + + void StartWpsModeFail1() + { + pStaStateMachine->StartWpsMode(nullptr); + } + + void StartWpsModeFail2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartWpsPbcMode(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + InternalMessage msg; + msg.SetParam1(static_cast(SetupMethod::PBC)); + pStaStateMachine->StartWpsMode(nullptr); + } + + void StartWpsModeFail3() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartWpsPinMode(_, _)) + .WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + InternalMessage msg; + msg.SetParam1(static_cast(SetupMethod::DISPLAY)); + pStaStateMachine->StartWpsMode(nullptr); + } + + void StartWpsModeFail4() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StartWpsPinMode(_, _)) + .WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + InternalMessage msg; + msg.SetParam1(static_cast(SetupMethod::KEYPAD)); + pStaStateMachine->StartWpsMode(nullptr); + } + + void DealWpaBlockListClearEventSuccess() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), WpaBlocklistClear()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + pStaStateMachine->DealWpaBlockListClearEvent(&msg); + } + + void DealWpaBlockListClearEventFail() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), WpaBlocklistClear()) + .WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + InternalMessage msg; + pStaStateMachine->DealWpaBlockListClearEvent(&msg); + } + + void DealWpsConnectTimeOutEventSuccess() + { + pStaStateMachine->wpsState = SetupMethod::INVALID; + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopWps()).WillRepeatedly(Return((WIFI_IDL_OPT_FAILED))); + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)); + InternalMessage msg; + pStaStateMachine->DealWpsConnectTimeOutEvent(&msg); + } + + void DealWpsConnectTimeOutEventFail() + { + pStaStateMachine->wpsState = SetupMethod::INVALID; + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopWps()).WillRepeatedly(Return((WIFI_IDL_OPT_FAILED))); + pStaStateMachine->DealWpsConnectTimeOutEvent(nullptr); + } + + void DealCancelWpsCmdSuccess1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopWps()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).WillRepeatedly(Return(-1)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), EnableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)); + pStaStateMachine->wpsState = SetupMethod::PBC; + InternalMessage msg; + pStaStateMachine->DealCancelWpsCmd(&msg); + } + + void DealCancelWpsCmdSuccess2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopWps()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).WillRepeatedly(Return(-1)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), EnableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)); + pStaStateMachine->wpsState = SetupMethod::DISPLAY; + InternalMessage msg; + pStaStateMachine->DealCancelWpsCmd(&msg); + } + + void DealCancelWpsCmdSuccess3() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopWps()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).WillRepeatedly(Return(-1)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), EnableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)).Times(AtLeast(0)); + pStaStateMachine->wpsState = SetupMethod::KEYPAD; + InternalMessage msg; + pStaStateMachine->DealCancelWpsCmd(&msg); + } + + void DealCancelWpsCmdFail1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopWps()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)).Times(AtLeast(0)); + pStaStateMachine->wpsState = SetupMethod::PBC; + InternalMessage msg; + pStaStateMachine->DealCancelWpsCmd(&msg); + } + + void DealCancelWpsCmdFail2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopWps()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)).Times(AtLeast(0)); + pStaStateMachine->wpsState = SetupMethod::DISPLAY; + InternalMessage msg; + pStaStateMachine->DealCancelWpsCmd(&msg); + } + + void DealCancelWpsCmdFail3() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopWps()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)).Times(AtLeast(0)); + pStaStateMachine->wpsState = SetupMethod::KEYPAD; + InternalMessage msg; + pStaStateMachine->DealCancelWpsCmd(&msg); + } + + void DealStartRoamCmdSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), AddDeviceConfig(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SyncDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Reassociate()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + InternalMessage msg; + pStaStateMachine->DealStartRoamCmd(&msg); + } + + void DealStartRoamCmdFail1() + { + pStaStateMachine->DealStartRoamCmd(nullptr); + } + + void DealStartRoamCmdFail2() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)) + .WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiSettings::GetInstance(), AddDeviceConfig(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SyncDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Reassociate()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); + InternalMessage msg; + pStaStateMachine->DealStartRoamCmd(&msg); + } + + void DealStartRoamCmdFail3() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), AddDeviceConfig(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SyncDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Reassociate()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + InternalMessage msg; + pStaStateMachine->DealStartRoamCmd(&msg); + } + + void StartConnectToNetworkSuccess() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), EnableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Connect(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScanInfoList(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(testing::AtLeast(0)); + pStaStateMachine->StartConnectToNetwork(0); + } + + void StartConnectToNetworkFail1() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScanInfoList(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), EnableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(testing::AtLeast(0)); + pStaStateMachine->StartConnectToNetwork(0); + } + + void StartConnectToNetworkFail2() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScanInfoList(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), EnableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Connect(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(testing::AtLeast(0)); + pStaStateMachine->StartConnectToNetwork(0); + } + + void StartConnectToNetworkFali3() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), EnableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), GetScanInfoList(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Connect(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(testing::AtLeast(0)); + pStaStateMachine->StartConnectToNetwork(0); + } + + void MacAddressGenerateSuccess() + { + std::string strMac = "hmwifi"; + pStaStateMachine->MacAddressGenerate(strMac); + } + + void SetRandomMacSuccess1() + { + WifiDeviceConfig deviceConfig; + deviceConfig.wifiPrivacySetting = WifiPrivacyConfig::RANDOMMAC; + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillRepeatedly(DoAll(SetArgReferee<1>(deviceConfig), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetScanInfoList(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetStaDeviceMacAddress(_)) + .WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), GetMacAddress(_)).Times(AtLeast(0)).WillOnce(Return(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetConnectMacAddr(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pStaStateMachine->SetRandomMac(0); + } + + void SetRandomMacFail1() + { + WifiDeviceConfig deviceConfig; + deviceConfig.wifiPrivacySetting = WifiPrivacyConfig::RANDOMMAC; + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillRepeatedly(DoAll(SetArgReferee<1>(deviceConfig), Return(-1))); + EXPECT_CALL(WifiSettings::GetInstance(), GetMacAddress(_)).Times(AtLeast(0)).WillOnce(Return(0)); + pStaStateMachine->SetRandomMac(0); + } + + void SetRandomMacFail2() + { + WifiDeviceConfig deviceConfig; + deviceConfig.wifiPrivacySetting = WifiPrivacyConfig::RANDOMMAC; + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillRepeatedly(DoAll(SetArgReferee<1>(deviceConfig), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetScanInfoList(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetStaDeviceMacAddress(_)) + .WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiSettings::GetInstance(), GetMacAddress(_)).Times(AtLeast(0)).WillOnce(Return(0)); + pStaStateMachine->SetRandomMac(0); + } + + void StartRoamToNetworkSuccess() + { + pStaStateMachine->StartRoamToNetwork("a2:b1:f5:c7:d1"); + } + + void OnNetworkConnectionEventSuccess() + { + pStaStateMachine->OnNetworkConnectionEvent(0, "a2:b1:f5:c7:d1"); + } + + void SeparatingStateGoInStateSuccess() + { + pStaStateMachine->pSeparatingState->GoInState(); + } + + void SeparatingStateGoOutStateSuccess() + { + pStaStateMachine->pSeparatingState->GoOutState(); + } + + void SeparatingStateExeMsgSuccess() + { + InternalMessage msg; + pStaStateMachine->pSeparatingState->ExecuteStateMsg(&msg); + } + + void SeparatingStateExeMsgFail() + { + pStaStateMachine->pSeparatingState->ExecuteStateMsg(nullptr); + } + + void SeparatedStateGoInStateSuccess() + { + pStaStateMachine->pSeparatedState->GoInState(); + } + + void SeparatedStateGoOutStateSuccess() + { + pStaStateMachine->pSeparatedState->GoOutState(); + } + + void SeparatedStateExeMsgSuccess1() + { + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_NETWORK_DISCONNECTION_EVENT); + EXPECT_FALSE(pStaStateMachine->pSeparatedState->ExecuteStateMsg(&msg)); + } + + void SeparatedStateExeMsgSuccess2() + { + EXPECT_CALL(WifiManager::GetInstance(), DealStaOpenRes(_)); + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_ENABLE_WIFI); + EXPECT_TRUE(pStaStateMachine->pSeparatedState->ExecuteStateMsg(&msg)); + } + + void SeparatedStateExeMsgFail() + { + EXPECT_FALSE(pStaStateMachine->pSeparatedState->ExecuteStateMsg(nullptr)); + } + + void ApLinkedStateGoInStateSuccess() + { + pStaStateMachine->pApLinkedState->GoInState(); + } + + void ApLinkedStateGoOutStateSuccess() + { + pStaStateMachine->pApLinkedState->GoOutState(); + } + + void ApLinkedStateExeMsgSuccess1() + { + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(1)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Disconnect()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_DISCONNECT); + EXPECT_TRUE(pStaStateMachine->pApLinkedState->ExecuteStateMsg(&msg)); + } + + void ApLinkedStateExeMsgSuccess2() + { + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_NETWORK_CONNECTION_EVENT); + EXPECT_TRUE(pStaStateMachine->pApLinkedState->ExecuteStateMsg(&msg)); + } + + void ApLinkedStateExeMsgFail1() + { + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_NETWORK_DISCONNECTION_EVENT); + EXPECT_FALSE(pStaStateMachine->pApLinkedState->ExecuteStateMsg(&msg)); + } + + void ApLinkedStateExeMsgFai2() + { + EXPECT_FALSE(pStaStateMachine->pApLinkedState->ExecuteStateMsg(nullptr)); + } + + void DisConnectProcessSuccess() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Disconnect()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pStaStateMachine->DisConnectProcess(); + } + + void DisConnectProcessFail() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Disconnect()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + pStaStateMachine->DisConnectProcess(); + } + + void WpsStateGoInStateSuccess() + { + pStaStateMachine->pWpsState->GoInState(); + } + + void WpsStateGoOutStateSuccess() + { + pStaStateMachine->pWpsState->GoOutState(); + } + + void WpsStateExeMsgSuccess1() + { + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), AddDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SyncDeviceConfig()).Times(AtLeast(0)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetDeviceState(_, _, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_NETWORK_CONNECTION_EVENT); + EXPECT_TRUE(pStaStateMachine->pWpsState->ExecuteStateMsg(&msg)); + } + + void WpsStateExeMsgSuccess2() + { + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)); + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_STARTWPS); + msg.SetParam1(static_cast(SetupMethod::PBC)); + EXPECT_TRUE(pStaStateMachine->pWpsState->ExecuteStateMsg(&msg)); + } + + void WpsStateExeMsgSuccess3() + { + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)); + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_STARTWPS); + msg.SetParam1(static_cast(SetupMethod::DISPLAY)); + EXPECT_TRUE(pStaStateMachine->pWpsState->ExecuteStateMsg(&msg)); + } + + void WpsStateExeMsgSuccess4() + { + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)); + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_WPS_OVERLAP_EVENT); + msg.SetParam1(static_cast(SetupMethod::DISPLAY)); + EXPECT_TRUE(pStaStateMachine->pWpsState->ExecuteStateMsg(&msg)); + } + + void WpsStateExeMsgSuccess5() + { + EXPECT_CALL(WifiManager::GetInstance(), DealWpsChanged(_, _)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).WillRepeatedly(Return(-1)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopWps()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(testing::AtLeast(0)); + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_WPS_OVERLAP_EVENT); + msg.SetParam1(static_cast(SetupMethod::DISPLAY)); + EXPECT_TRUE(pStaStateMachine->pWpsState->ExecuteStateMsg(&msg)); + } + + void WpsStateExeMsgFail1() + { + EXPECT_FALSE(pStaStateMachine->pWpsState->ExecuteStateMsg(nullptr)); + } + + void WpsStateExeMsgFail2() + { + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_WPS_START_EVENT); + EXPECT_FALSE(pStaStateMachine->pWpsState->ExecuteStateMsg(nullptr)); + } + + void SyncAllDeviceConfigsSuccess() + { + std::vector result; + WifiDeviceConfig wifiDeviceConfig; + result.push_back(wifiDeviceConfig); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(result), Return(0))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetNextNetworkId(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetDeviceConfig(_, _)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()); + pStaStateMachine->SyncAllDeviceConfigs(); + } + + void SyncAllDeviceConfigsFail() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + pStaStateMachine->SyncAllDeviceConfigs(); + } + + void GetIpStateStateGoInStateSuccess1() + { + WifiDeviceConfig config; + config.wifiProxyconfig.configureMethod = ConfigureProxyMethod::MANUALCONFIGUE; + config.wifiIpConfig.assignMethod = AssignIpMethod::STATIC; + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillRepeatedly(DoAll(SetArgReferee<1>(config), Return(0))); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Disconnect()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + pStaStateMachine->pGetIpState->GoInState(); + } + + void GetIpStateStateGoInStateSuccess2() + { + pStaStateMachine->isRoam = true; + WifiDeviceConfig config; + config.wifiProxyconfig.configureMethod = ConfigureProxyMethod::MANUALCONFIGUE; + config.wifiIpConfig.assignMethod = AssignIpMethod::DHCP; + EXPECT_CALL(WifiSettings::GetInstance(), GetDhcpIpType()).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillRepeatedly(DoAll(SetArgReferee<1>(config), Return(0))); + pStaStateMachine->pGetIpState->GoInState(); + } + + void GetIpStateStateGoInStateSuccess3() + { + pStaStateMachine->isRoam = false; + WifiDeviceConfig config; + config.wifiProxyconfig.configureMethod = ConfigureProxyMethod::MANUALCONFIGUE; + config.wifiIpConfig.assignMethod = AssignIpMethod::DHCP; + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)) + .WillRepeatedly(DoAll(SetArgReferee<1>(config), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetDhcpIpType()).WillRepeatedly(Return(IPTYPE_IPV4)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Disconnect()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + pStaStateMachine->pGetIpState->GoInState(); + } + + void GetIpStateStateGoOutStateSuccess() + { + pStaStateMachine->pGetIpState->GoOutState(); + } + + void GetIpStateStateExeMsgSuccess() + { + InternalMessage msg; + pStaStateMachine->pGetIpState->ExecuteStateMsg(&msg); + } + + void GetIpStateStateExeMsgFail() + { + pStaStateMachine->pGetIpState->ExecuteStateMsg(nullptr); + } + + void ConfigStaticIpAddressSuccess1() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetIpInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); + pStaStateMachine->currentTpType = IPTYPE_IPV4; + pStaStateMachine->getIpSucNum = 1; + pStaStateMachine->isRoam = false; + StaticIpAddress staticIpAddress; + EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)).Times(AtLeast(0)); + ; + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(IfConfig::GetInstance(), SetIfAddr(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(AtLeast(0)); + EXPECT_TRUE(pStaStateMachine->ConfigStaticIpAddress(staticIpAddress)); + } + + void ConfigStaticIpAddressSuccess2() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetIpInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); + pStaStateMachine->currentTpType = IPTYPE_IPV6; + pStaStateMachine->getIpSucNum = 1; + pStaStateMachine->isRoam = false; + StaticIpAddress staticIpAddress; + EXPECT_CALL(IfConfig::GetInstance(), SetIfAddr(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(AtLeast(0)); + EXPECT_TRUE(pStaStateMachine->ConfigStaticIpAddress(staticIpAddress)); + } + + void ConfigStaticIpAddressSuccess3() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetIpInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); + pStaStateMachine->currentTpType = IPTYPE_MIX; + pStaStateMachine->getIpSucNum = 1; + pStaStateMachine->isRoam = false; + StaticIpAddress staticIpAddress; + EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(IfConfig::GetInstance(), SetIfAddr(_, _)).Times(AtLeast(0)); + EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(AtLeast(0)); + EXPECT_TRUE(pStaStateMachine->ConfigStaticIpAddress(staticIpAddress)); + } + + void ConfigStaticIpAddressFail() + { + pStaStateMachine->currentTpType = IPTYPE_BUTT; + StaticIpAddress staticIpAddress; + pStaStateMachine->getIpSucNum = 1; + pStaStateMachine->isRoam = false; + EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(IfConfig::GetInstance(), SetIfAddr(_, _)).Times(AtLeast(0)); + EXPECT_FALSE(pStaStateMachine->ConfigStaticIpAddress(staticIpAddress)); + } + + void HandleNetCheckResultSuccess1() + { + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)); + pStaStateMachine->linkedInfo.connState = ConnState::CONNECTED; + pStaStateMachine->HandleNetCheckResult(StaNetState::NETWORK_STATE_WORKING); + } + + void HandleNetCheckResultSuccess3() + { + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)); + pStaStateMachine->linkedInfo.connState = ConnState::CONNECTED; + pStaStateMachine->HandleNetCheckResult(StaNetState::NETWORK_STATE_UNKNOW); + } + + void HandleNetCheckResultFail() + { + pStaStateMachine->linkedInfo.connState = ConnState::DISCONNECTED; + pStaStateMachine->HandleNetCheckResult(StaNetState::NETWORK_STATE_UNKNOW); + } + + void LinkedStateGoInStateSuccess() + { + pStaStateMachine->pLinkedState->GoInState(); + } + + void LinkedStateGoOutStateSuccess() + { + pStaStateMachine->pLinkedState->GoOutState(); + } + + void LinkedStateExeMsgSuccess() + { + InternalMessage msg; + pStaStateMachine->pLinkedState->ExecuteStateMsg(&msg); + } + + void LinkedStateExeMsgFail() + { + pStaStateMachine->pLinkedState->ExecuteStateMsg(nullptr); + } + + void ApRoamingStateGoInStateSuccess() + { + pStaStateMachine->pApRoamingState->GoInState(); + } + + void ApRoamingStateGoOutStateSuccess() + { + pStaStateMachine->pApRoamingState->GoOutState(); + } + + void ApRoamingStateExeMsgSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(testing::AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)); + InternalMessage msg; + msg.SetMessageName(WIFI_SVR_CMD_STA_NETWORK_CONNECTION_EVENT); + EXPECT_TRUE(pStaStateMachine->pApRoamingState->ExecuteStateMsg(&msg)); + } + + void ApRoamingStateExeMsgFail() + { + EXPECT_FALSE(pStaStateMachine->pApRoamingState->ExecuteStateMsg(nullptr)); + } + + void ConnectToNetworkProcessSuccess() + { + pStaStateMachine->wpsState = SetupMethod::DISPLAY; + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)).WillRepeatedly(Return(-1)); + WifiIdlGetDeviceConfig config; + config.value = "hmwifi"; + EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetDeviceConfig(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(config), Return(WIFI_IDL_OPT_FAILED))); + EXPECT_CALL(WifiSettings::GetInstance(), AddWpsDeviceConfig(_)); + EXPECT_CALL(WifiSettings::GetInstance(), SyncDeviceConfig()); + EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); + InternalMessage msg; + pStaStateMachine->ConnectToNetworkProcess(&msg); + } + + void ConnectToNetworkProcessFail() + { + pStaStateMachine->ConnectToNetworkProcess(nullptr); + } + + void SetWifiLinkedInfoSuccess1() + { + pStaStateMachine->linkedInfo.networkId = INVALID_NETWORK_ID; + pStaStateMachine->lastLinkedInfo.networkId = 0; + pStaStateMachine->SetWifiLinkedInfo(INVALID_NETWORK_ID); + } + + void SetWifiLinkedInfoSuccess2() + { + EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_, _)).WillRepeatedly(Return(0)); + pStaStateMachine->linkedInfo.networkId = INVALID_NETWORK_ID; + pStaStateMachine->lastLinkedInfo.networkId = INVALID_NETWORK_ID; + pStaStateMachine->SetWifiLinkedInfo(0); + } + + void DhcpResultNotifyOnSuccessTest() + { + pStaStateMachine->linkedInfo.detailedState = DetailedState::CONNECTED; + pStaStateMachine->getIpSucNum = 1; + pStaStateMachine->isRoam = false; + IpInfo ipInfo; + ipInfo.ipAddress = IpTools::ConvertIpv4Address("192.168.0.2"); + ipInfo.gateway = IpTools::ConvertIpv4Address("192.168.0.1"); + EXPECT_CALL(WifiSettings::GetInstance(), GetIpInfo(_)) + .WillRepeatedly(DoAll(SetArgReferee<0>(ipInfo), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); + + std::string ifname = "wlan0"; + DhcpResult result; + result.strYourCli = "192.168.0.0"; + result.strRouter1 = "test"; + result.iptype = 0; + pStaStateMachine->pDhcpResultNotify->OnSuccess(0, ifname, result); + } + + void DhcpResultNotifyOnFailedTest1() + { + pStaStateMachine->linkedInfo.detailedState = DetailedState::CONNECTED; + pStaStateMachine->currentTpType = IPTYPE_IPV6; + pStaStateMachine->getIpSucNum = 0; + pStaStateMachine->getIpFailNum = 1; + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Disconnect()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + std::string ifname = "wlan0"; + std::string reason = "test"; + pStaStateMachine->pDhcpResultNotify->OnFailed(0, ifname, reason); + } + + void DhcpResultNotifyOnFailedTest2() + { + pStaStateMachine->linkedInfo.detailedState = DetailedState::CONNECTED; + pStaStateMachine->isRoam = false; + EXPECT_CALL(WifiStaHalInterface::GetInstance(), Disconnect()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + std::string ifname = "wlan1"; + std::string reason = "test"; + pStaStateMachine->pDhcpResultNotify->OnFailed(0, ifname, reason); + } + + void DhcpResultNotifyOnFailedTest3() + { + pStaStateMachine->linkedInfo.detailedState = DetailedState::CONNECTED; + pStaStateMachine->isRoam = true; + std::string ifname = "wlan1"; + std::string reason = "test"; + pStaStateMachine->pDhcpResultNotify->OnFailed(0, ifname, reason); + } + + void DhcpResultNotifyOnSerExitNotify() + { + std::string ifname = "wlan0"; + pStaStateMachine->pDhcpResultNotify->OnSerExitNotify(ifname); + } + + void SaveLinkstateSuccess() + { + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)); + pStaStateMachine->SaveLinkstate(ConnState::CONNECTED, DetailedState::CONNECTED); + } + + void DisableNetworkSuccess() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), DisableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + pStaStateMachine->DisableNetwork(0); + } + + void DisableNetworkFail1() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), DisableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + pStaStateMachine->DisableNetwork(0); + } + + void DisableNetworkFail2() + { + EXPECT_CALL(WifiStaHalInterface::GetInstance(), DisableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SaveDeviceConfig()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); + pStaStateMachine->DisableNetwork(0); + } +}; + +HWTEST_F(StaStateMachineTest, InitWifiLinkedInfoSuccess, TestSize.Level1) +{ + InitWifiLinkedInfoSuccess(); +} + +HWTEST_F(StaStateMachineTest, InitLastWifiLinkedInfoSuccess, TestSize.Level1) +{ + InitLastWifiLinkedInfoSuccess(); +} + +HWTEST_F(StaStateMachineTest, BuildStateTreeSuccess, TestSize.Level1) +{ + BuildStateTreeSuccess(); +} + +HWTEST_F(StaStateMachineTest, RegisterStaServiceCallbackSuccess, TestSize.Level1) +{ + RegisterStaServiceCallbackSuccess(); +} + +HWTEST_F(StaStateMachineTest, DealConnectTimeOutCmd, TestSize.Level1) +{ + DealConnectTimeOutCmd(); +} + +HWTEST_F(StaStateMachineTest, RootStateGoInStateSuccess, TestSize.Level1) +{ + RootStateGoInStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, RootStateGoOutStateSuccess, TestSize.Level1) +{ + RootStateGoOutStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, RootStateExeMsgSuccess, TestSize.Level1) +{ + RootStateExeMsgSuccess(); +} + +HWTEST_F(StaStateMachineTest, RootStateExeMsgFail, TestSize.Level1) +{ + RootStateExeMsgFail(); +} + +HWTEST_F(StaStateMachineTest, InitStateGoInStateSuccess, TestSize.Level1) +{ + InitStateGoInStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, InitStateGoOutStateSuccess, TestSize.Level1) +{ + InitStateGoOutStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, InitStateExeMsgSuccess, TestSize.Level1) +{ + InitStateExeMsgSuccess(); +} + +HWTEST_F(StaStateMachineTest, InitStateExeMsgFail1, TestSize.Level1) +{ + InitStateExeMsgFail1(); +} + +HWTEST_F(StaStateMachineTest, InitStateExeMsgFail2, TestSize.Level1) +{ + InitStateExeMsgFail2(); +} + +HWTEST_F(StaStateMachineTest, ConvertDeviceCfgSuccess, TestSize.Level1) +{ + ConvertDeviceCfgSuccess(); +} + +HWTEST_F(StaStateMachineTest, ConvertDeviceCfgFail1, TestSize.Level1) +{ + ConvertDeviceCfgFail1(); +} + +HWTEST_F(StaStateMachineTest, ConvertDeviceCfgFail2, TestSize.Level1) +{ + ConvertDeviceCfgFail2(); +} + +HWTEST_F(StaStateMachineTest, StartWifiProcessSuccess, TestSize.Level1) +{ + StartWifiProcessSuccess(); +} + +HWTEST_F(StaStateMachineTest, StartWifiProcessFail1, TestSize.Level1) +{ + StartWifiProcessFail1(); +} + +HWTEST_F(StaStateMachineTest, StartWifiProcessFail2, TestSize.Level1) +{ + StartWifiProcessFail2(); +} + +HWTEST_F(StaStateMachineTest, InitWpsSettingsSuccess, TestSize.Level1) +{ + InitWpsSettingsSuccess(); +} + +HWTEST_F(StaStateMachineTest, WpaStartingStateGoInStateSuccess, TestSize.Level1) +{ + WpaStartingStateGoInStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, WpaStartingStateGoOutStateSuccess, TestSize.Level1) +{ + WpaStartingStateGoOutStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, WpaStartingStateExeMsgSuccess, TestSize.Level1) +{ + WpaStartingStateExeMsgSuccess(); +} + +HWTEST_F(StaStateMachineTest, WpaStartingStateExeMsgFail1, TestSize.Level1) +{ + WpaStartingStateExeMsgFail1(); +} + +HWTEST_F(StaStateMachineTest, WpaStartingStateExeMsgFail2, TestSize.Level1) +{ + WpaStartingStateExeMsgFail2(); +} + +HWTEST_F(StaStateMachineTest, WpaStartedStateGoInStateSuccess1, TestSize.Level1) +{ + WpaStartedStateGoInStateSuccess1(); +} + +HWTEST_F(StaStateMachineTest, WpaStartedStateGoInStateSuccess2, TestSize.Level1) +{ + WpaStartedStateGoInStateSuccess2(); +} + +HWTEST_F(StaStateMachineTest, WpaStartedStateGoOutStateSuccess, TestSize.Level1) +{ + WpaStartedStateGoOutStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, WpaStartedStateExeMsgSuccess, TestSize.Level1) +{ + WpaStartedStateExeMsgSuccess(); +} + +HWTEST_F(StaStateMachineTest, WpaStartedStateExeMsgFail1, TestSize.Level1) +{ + WpaStartedStateExeMsgFail1(); +} + +HWTEST_F(StaStateMachineTest, WpaStartedStateExeMsgFail2, TestSize.Level1) +{ + WpaStartedStateExeMsgFail2(); +} + +HWTEST_F(StaStateMachineTest, StopWifiProcessSuccess1, TestSize.Level1) +{ + StopWifiProcessSuccess1(); +} + +HWTEST_F(StaStateMachineTest, StopWifiProcessSuccess2, TestSize.Level1) +{ + StopWifiProcessSuccess2(); +} + +HWTEST_F(StaStateMachineTest, StopWifiProcessFail, TestSize.Level1) +{ + StopWifiProcessFail(); +} + +HWTEST_F(StaStateMachineTest, WpaStoppingStateGoInStateSuccess, TestSize.Level1) +{ + WpaStoppingStateGoInStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, WpaStoppingStateGoOutStateSuccess, TestSize.Level1) +{ + WpaStoppingStateGoOutStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, WpaStoppingStateExeMsgSuccess, TestSize.Level1) +{ + WpaStoppingStateExeMsgSuccess(); +} + +HWTEST_F(StaStateMachineTest, WpaStoppingStateExeMsgFail, TestSize.Level1) +{ + WpaStoppingStateExeMsgFail(); +} + +HWTEST_F(StaStateMachineTest, LinkStateGoInStateSuccess, TestSize.Level1) +{ + LinkStateGoInStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, LinkStateGoOutStateSuccess, TestSize.Level1) +{ + LinkStateGoOutStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, LinkStateExeMsgFail, TestSize.Level1) +{ + LinkStateExeMsgFail(); +} + +HWTEST_F(StaStateMachineTest, InitStaSMHandleMapSuccess, TestSize.Level1) +{ + InitStaSMHandleMapSuccess(); +} + +HWTEST_F(StaStateMachineTest, DealConnectToUserSelectedNetworkSuccess, TestSize.Level1) +{ + DealConnectToUserSelectedNetworkSuccess(); +} + +HWTEST_F(StaStateMachineTest, DealConnectToUserSelectedNetworkFail, TestSize.Level1) +{ + DealConnectToUserSelectedNetworkFail(); +} + +HWTEST_F(StaStateMachineTest, DealConnectTimeOutCmdSuccess, TestSize.Level1) +{ + DealConnectTimeOutCmdSuccess(); +} + +HWTEST_F(StaStateMachineTest, DealConnectTimeOutCmdFail, TestSize.Level1) +{ + DealConnectTimeOutCmdFail(); +} + +HWTEST_F(StaStateMachineTest, DealConnectionEventSuccess1, TestSize.Level1) +{ + DealConnectionEventSuccess1(); +} + +HWTEST_F(StaStateMachineTest, DealConnectionEventSuccess2, TestSize.Level1) +{ + DealConnectionEventSuccess2(); +} + +HWTEST_F(StaStateMachineTest, DealWpaWrongPskEventSuccess, TestSize.Level1) +{ + DealWpaWrongPskEventSuccess(); +} + +HWTEST_F(StaStateMachineTest, DealWpaWrongPskEventFail, TestSize.Level1) +{ + DealWpaWrongPskEventFail(); +} + +HWTEST_F(StaStateMachineTest, DealReassociateCmdSuccess, TestSize.Level1) +{ + DealReassociateCmdSuccess(); +} + +HWTEST_F(StaStateMachineTest, DealReassociateCmdFail1, TestSize.Level1) +{ + DealReassociateCmdFail1(); +} + +HWTEST_F(StaStateMachineTest, DealReassociateCmdFail2, TestSize.Level1) +{ + DealReassociateCmdFail2(); +} + +HWTEST_F(StaStateMachineTest, DealStartWpsCmdSuccess, TestSize.Level1) +{ + DealStartWpsCmdSuccess(); +} + +HWTEST_F(StaStateMachineTest, StartWpsModeSuccess1, TestSize.Level1) +{ + StartWpsModeSuccess1(); +} + +HWTEST_F(StaStateMachineTest, StartWpsModeSuccess2, TestSize.Level1) +{ + StartWpsModeSuccess2(); +} + +HWTEST_F(StaStateMachineTest, StartWpsModeSuccess3, TestSize.Level1) +{ + StartWpsModeSuccess3(); +} + +HWTEST_F(StaStateMachineTest, StartWpsModeSuccess4, TestSize.Level1) +{ + StartWpsModeSuccess4(); +} + +HWTEST_F(StaStateMachineTest, StartWpsModeFail1, TestSize.Level1) +{ + StartWpsModeFail1(); +} + +HWTEST_F(StaStateMachineTest, StartWpsModeFail2, TestSize.Level1) +{ + StartWpsModeFail2(); +} + +HWTEST_F(StaStateMachineTest, StartWpsModeFail3, TestSize.Level1) +{ + StartWpsModeFail3(); +} + +HWTEST_F(StaStateMachineTest, StartWpsModeFail4, TestSize.Level1) +{ + StartWpsModeFail4(); +} + +HWTEST_F(StaStateMachineTest, DealWpaBlockListClearEventSuccess, TestSize.Level1) +{ + DealWpaBlockListClearEventSuccess(); +} + +HWTEST_F(StaStateMachineTest, DealWpaBlockListClearEventFail, TestSize.Level1) +{ + DealWpaBlockListClearEventFail(); +} + +HWTEST_F(StaStateMachineTest, DealWpsConnectTimeOutEventSuccess, TestSize.Level1) +{ + DealWpsConnectTimeOutEventSuccess(); +} + +HWTEST_F(StaStateMachineTest, DealWpsConnectTimeOutEventFail, TestSize.Level1) +{ + DealWpsConnectTimeOutEventFail(); +} + +HWTEST_F(StaStateMachineTest, DealCancelWpsCmdSuccess1, TestSize.Level1) +{ + DealCancelWpsCmdSuccess1(); +} + +HWTEST_F(StaStateMachineTest, DealCancelWpsCmdSuccess2, TestSize.Level1) +{ + DealCancelWpsCmdSuccess2(); +} + +HWTEST_F(StaStateMachineTest, DealCancelWpsCmdSuccess3, TestSize.Level1) +{ + DealCancelWpsCmdSuccess3(); +} + +HWTEST_F(StaStateMachineTest, DealCancelWpsCmdFail1, TestSize.Level1) +{ + DealCancelWpsCmdFail1(); +} + +HWTEST_F(StaStateMachineTest, DealCancelWpsCmdFail2, TestSize.Level1) +{ + DealCancelWpsCmdFail2(); +} + +HWTEST_F(StaStateMachineTest, DealCancelWpsCmdFail3, TestSize.Level1) +{ + DealCancelWpsCmdFail3(); +} + +HWTEST_F(StaStateMachineTest, DealStartRoamCmdSuccess, TestSize.Level1) +{ + DealStartRoamCmdSuccess(); +} + +HWTEST_F(StaStateMachineTest, DealStartRoamCmdFail1, TestSize.Level1) +{ + DealStartRoamCmdFail1(); +} + +HWTEST_F(StaStateMachineTest, DealStartRoamCmdFail2, TestSize.Level1) +{ + DealStartRoamCmdFail2(); +} + +HWTEST_F(StaStateMachineTest, DealStartRoamCmdFail3, TestSize.Level1) +{ + DealStartRoamCmdFail3(); +} + +HWTEST_F(StaStateMachineTest, StartConnectToNetworkSuccess, TestSize.Level1) +{ + StartConnectToNetworkSuccess(); +} + +HWTEST_F(StaStateMachineTest, StartConnectToNetworkFail1, TestSize.Level1) +{ + StartConnectToNetworkFail1(); +} + +HWTEST_F(StaStateMachineTest, StartConnectToNetworkFail2, TestSize.Level1) +{ + StartConnectToNetworkFail2(); +} + +HWTEST_F(StaStateMachineTest, StartConnectToNetworkFali3, TestSize.Level1) +{ + StartConnectToNetworkFali3(); +} + +HWTEST_F(StaStateMachineTest, MacAddressGenerateSuccess, TestSize.Level1) +{ + MacAddressGenerateSuccess(); +} + +HWTEST_F(StaStateMachineTest, SetRandomMacSuccess1, TestSize.Level1) +{ + SetRandomMacSuccess1(); +} + +HWTEST_F(StaStateMachineTest, SetRandomMacFail1, TestSize.Level1) +{ + SetRandomMacFail1(); +} + +HWTEST_F(StaStateMachineTest, SetRandomMacFail2, TestSize.Level1) +{ + SetRandomMacFail2(); +} + +HWTEST_F(StaStateMachineTest, StartRoamToNetworkSuccess, TestSize.Level1) +{ + StartRoamToNetworkSuccess(); +} + +HWTEST_F(StaStateMachineTest, OnNetworkConnectionEventSuccess, TestSize.Level1) +{ + OnNetworkConnectionEventSuccess(); +} + +HWTEST_F(StaStateMachineTest, SeparatingStateGoInStateSuccess, TestSize.Level1) +{ + SeparatingStateGoInStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, SeparatingStateGoOutStateSuccess, TestSize.Level1) +{ + SeparatingStateGoOutStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, SeparatingStateExeMsgSuccess, TestSize.Level1) +{ + SeparatingStateExeMsgSuccess(); +} + +HWTEST_F(StaStateMachineTest, SeparatingStateExeMsgFail, TestSize.Level1) +{ + SeparatingStateExeMsgFail(); +} + +HWTEST_F(StaStateMachineTest, SeparatedStateGoInStateSuccess, TestSize.Level1) +{ + SeparatedStateGoInStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, SeparatedStateGoOutStateSuccess, TestSize.Level1) +{ + SeparatedStateGoOutStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, SeparatedStateExeMsgSuccess1, TestSize.Level1) +{ + SeparatedStateExeMsgSuccess1(); +} + +HWTEST_F(StaStateMachineTest, SeparatedStateExeMsgSuccess2, TestSize.Level1) +{ + SeparatedStateExeMsgSuccess2(); +} + +HWTEST_F(StaStateMachineTest, SeparatedStateExeMsgFail, TestSize.Level1) +{ + SeparatedStateExeMsgFail(); +} + +HWTEST_F(StaStateMachineTest, ApLinkedStateGoInStateSuccess, TestSize.Level1) +{ + ApLinkedStateGoInStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, ApLinkedStateGoOutStateSuccess, TestSize.Level1) +{ + ApLinkedStateGoOutStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, ApLinkedStateExeMsgSuccess1, TestSize.Level1) +{ + ApLinkedStateExeMsgSuccess1(); +} + +HWTEST_F(StaStateMachineTest, ApLinkedStateExeMsgSuccess2, TestSize.Level1) +{ + ApLinkedStateExeMsgSuccess2(); +} + +HWTEST_F(StaStateMachineTest, ApLinkedStateExeMsgFail1, TestSize.Level1) +{ + ApLinkedStateExeMsgFail1(); +} + +HWTEST_F(StaStateMachineTest, ApLinkedStateExeMsgFai2, TestSize.Level1) +{ + ApLinkedStateExeMsgFai2(); +} + +HWTEST_F(StaStateMachineTest, DisConnectProcessSuccess, TestSize.Level1) +{ + DisConnectProcessSuccess(); +} + +HWTEST_F(StaStateMachineTest, DisConnectProcessFail, TestSize.Level1) +{ + DisConnectProcessFail(); +} + +HWTEST_F(StaStateMachineTest, WpsStateGoInStateSuccess, TestSize.Level1) +{ + WpsStateGoInStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, WpsStateGoOutStateSuccess, TestSize.Level1) +{ + WpsStateGoOutStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, WpsStateExeMsgSuccess1, TestSize.Level1) +{ + WpsStateExeMsgSuccess1(); +} + +HWTEST_F(StaStateMachineTest, WpsStateExeMsgSuccess2, TestSize.Level1) +{ + WpsStateExeMsgSuccess2(); +} + +HWTEST_F(StaStateMachineTest, WpsStateExeMsgSuccess3, TestSize.Level1) +{ + WpsStateExeMsgSuccess3(); +} + +HWTEST_F(StaStateMachineTest, WpsStateExeMsgSuccess4, TestSize.Level1) +{ + WpsStateExeMsgSuccess4(); +} + +HWTEST_F(StaStateMachineTest, WpsStateExeMsgSuccess5, TestSize.Level1) +{ + WpsStateExeMsgSuccess5(); +} + +HWTEST_F(StaStateMachineTest, WpsStateExeMsgFail1, TestSize.Level1) +{ + WpsStateExeMsgFail1(); +} + +HWTEST_F(StaStateMachineTest, WpsStateExeMsgFail2, TestSize.Level1) +{ + WpsStateExeMsgFail2(); +} + +HWTEST_F(StaStateMachineTest, SyncAllDeviceConfigsSuccess, TestSize.Level1) +{ + SyncAllDeviceConfigsSuccess(); +} + +HWTEST_F(StaStateMachineTest, SyncAllDeviceConfigsFail, TestSize.Level1) +{ + SyncAllDeviceConfigsFail(); +} + +HWTEST_F(StaStateMachineTest, GetIpStateStateGoInStateSuccess1, TestSize.Level1) +{ + GetIpStateStateGoInStateSuccess1(); +} + +HWTEST_F(StaStateMachineTest, GetIpStateStateGoInStateSuccess2, TestSize.Level1) +{ + GetIpStateStateGoInStateSuccess2(); +} + +HWTEST_F(StaStateMachineTest, GetIpStateStateGoInStateSuccess3, TestSize.Level1) +{ + GetIpStateStateGoInStateSuccess3(); +} + +HWTEST_F(StaStateMachineTest, GetIpStateStateGoOutStateSuccess, TestSize.Level1) +{ + GetIpStateStateGoOutStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, GetIpStateStateExeMsgSuccess, TestSize.Level1) +{ + GetIpStateStateExeMsgSuccess(); +} + +HWTEST_F(StaStateMachineTest, GetIpStateStateExeMsgFail, TestSize.Level1) +{ + GetIpStateStateExeMsgFail(); +} + +HWTEST_F(StaStateMachineTest, ConfigStaticIpAddressSuccess1, TestSize.Level1) +{ + ConfigStaticIpAddressSuccess1(); +} + +HWTEST_F(StaStateMachineTest, ConfigStaticIpAddressSuccess2, TestSize.Level1) +{ + ConfigStaticIpAddressSuccess2(); +} + +HWTEST_F(StaStateMachineTest, ConfigStaticIpAddressSuccess3, TestSize.Level1) +{ + ConfigStaticIpAddressSuccess3(); +} + +HWTEST_F(StaStateMachineTest, ConfigStaticIpAddressFail, TestSize.Level1) +{ + ConfigStaticIpAddressFail(); +} + +HWTEST_F(StaStateMachineTest, HandleNetCheckResultSuccess1, TestSize.Level1) +{ + HandleNetCheckResultSuccess1(); +} + +HWTEST_F(StaStateMachineTest, HandleNetCheckResultSuccess3, TestSize.Level1) +{ + HandleNetCheckResultSuccess3(); +} + +HWTEST_F(StaStateMachineTest, HandleNetCheckResultFail, TestSize.Level1) +{ + HandleNetCheckResultFail(); +} + +HWTEST_F(StaStateMachineTest, LinkedStateGoInStateSuccess, TestSize.Level1) +{ + LinkedStateGoInStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, LinkedStateGoOutStateSuccess, TestSize.Level1) +{ + LinkedStateGoOutStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, LinkedStateExeMsgSuccess, TestSize.Level1) +{ + LinkedStateExeMsgSuccess(); +} + +HWTEST_F(StaStateMachineTest, LinkedStateExeMsgFail, TestSize.Level1) +{ + LinkedStateExeMsgFail(); +} + +HWTEST_F(StaStateMachineTest, ApRoamingStateGoInStateSuccess, TestSize.Level1) +{ + ApRoamingStateGoInStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, ApRoamingStateGoOutStateSuccess, TestSize.Level1) +{ + ApRoamingStateGoOutStateSuccess(); +} + +HWTEST_F(StaStateMachineTest, ApRoamingStateExeMsgSuccess, TestSize.Level1) +{ + ApRoamingStateExeMsgSuccess(); +} + +HWTEST_F(StaStateMachineTest, ApRoamingStateExeMsgFail, TestSize.Level1) +{ + ApRoamingStateExeMsgFail(); +} + +HWTEST_F(StaStateMachineTest, ConnectToNetworkProcessSuccess, TestSize.Level1) +{ + ConnectToNetworkProcessSuccess(); +} + +HWTEST_F(StaStateMachineTest, ConnectToNetworkProcessFail, TestSize.Level1) +{ + ConnectToNetworkProcessFail(); +} + +HWTEST_F(StaStateMachineTest, SetWifiLinkedInfoSuccess1, TestSize.Level1) +{ + SetWifiLinkedInfoSuccess1(); +} + +HWTEST_F(StaStateMachineTest, SetWifiLinkedInfoSuccess2, TestSize.Level1) +{ + SetWifiLinkedInfoSuccess2(); +} + +HWTEST_F(StaStateMachineTest, DhcpResultNotifyOnSuccessTest, TestSize.Level1) +{ + DhcpResultNotifyOnSuccessTest(); +} + +HWTEST_F(StaStateMachineTest, DhcpResultNotifyOnFailedTest1, TestSize.Level1) +{ + DhcpResultNotifyOnFailedTest1(); +} + +HWTEST_F(StaStateMachineTest, DhcpResultNotifyOnFailedTest2, TestSize.Level1) +{ + DhcpResultNotifyOnFailedTest2(); +} + +HWTEST_F(StaStateMachineTest, DhcpResultNotifyOnFailedTest3, TestSize.Level1) +{ + DhcpResultNotifyOnFailedTest3(); +} + +HWTEST_F(StaStateMachineTest, DhcpResultNotifyOnSerExitNotify, TestSize.Level1) +{ + DhcpResultNotifyOnSerExitNotify(); +} + +HWTEST_F(StaStateMachineTest, SaveLinkstateSuccess, TestSize.Level1) +{ + SaveLinkstateSuccess(); +} + +HWTEST_F(StaStateMachineTest, DisableNetworkSuccess, TestSize.Level1) +{ + DisableNetworkSuccess(); +} + +HWTEST_F(StaStateMachineTest, DisableNetworkFail1, TestSize.Level1) +{ + DisableNetworkFail1(); +} + +HWTEST_F(StaStateMachineTest, DisableNetworkFail2, TestSize.Level1) +{ + DisableNetworkFail2(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/wifi_sta_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/wifi_sta_test.cpp new file mode 100644 index 000000000..067af39ab --- /dev/null +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/wifi_sta_test.cpp @@ -0,0 +1,24 @@ +/* + * 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 "global_test.h" + +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + testing::Environment *env = new GlobalTest(); + testing::AddGlobalTestEnvironment(env); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/BUILD.gn b/tests/wifi_standard/wifi_hal/unittest/BUILD.gn new file mode 100644 index 000000000..20d7d37d2 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/BUILD.gn @@ -0,0 +1,118 @@ +# 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. + +import("//build/test.gni") +SUBSYSTEM_DIR = "//foundation/communication/wifi" +module_output_path = "wifi_standard/wifi_hal_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/tests/wifi_standard/wifi_hal/unittest", + ] +} + +ohos_unittest("wifi_hal_unittest") { + module_out_path = module_output_path + sources = [ + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_adapter.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_ap_interface.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_base_interface.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_callback.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_chip_interface.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module_manage.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_sta_interface.c", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_vendor_interface.c", + "mock_wpa_ctrl.cpp", + "wifi_hal_ap_interface_test.cpp", + "wifi_hal_base_interface_test.cpp", + "wifi_hal_chip_interface_test.cpp", + "wifi_hal_crpc_server_add_test.cpp", + "wifi_hal_crpc_server_test.cpp", + "wifi_hal_hostapd_test.cpp", + "wifi_hal_p2p_interface_test.cpp", + "wifi_hal_sta_interface_test.cpp", + "wifi_hal_test.cpp", + "wifi_hal_wpa_p2p_test.cpp", + "wifi_hal_wpa_sta_test.cpp", + ] + + include_dirs = [ + "//utils/native/base/include", + "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/common", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//third_party/wpa_supplicant/wpa_supplicant-2.9_standard/src/", + "//third_party/bounds_checking_function/include/", + ] + + deps = [ + "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_server", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//utils/native/base:utils", + ] + + ldflags = [ + "-fPIC", + "--coverage", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + configs = [ ":module_private_config" ] + + part_name = "wifi_standard" + subsystem_name = "communication" + testonly = true +} + +group("unittest") { + testonly = true + deps = [ ":wifi_hal_unittest" ] +} + +ohos_shared_library("WifiHalVendorTest") { + sources = [ "wifi_hal_vendor_interface_test.c" ] + include_dirs = [ + "//utils/native/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal", + "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/common", + ] + deps = [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//utils/native/base:utils", + ] + part_name = "wifi_standard" + subsystem_name = "communication" +} diff --git a/tests/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.cpp b/tests/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.cpp new file mode 100644 index 000000000..ad999b291 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.cpp @@ -0,0 +1,287 @@ +/* + * 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 +#include +#include "mock_wpa_ctrl.h" +#include "wifi_hal_common_func.h" + +static std::vector gPipeFd; +static int gUsePipeFdNum = 0; +const int OncePipeFdNum = 2; +const int MaxExactCmdLength = 32; + +static std::map gSupportedCmd; + +void MockSetWpaExpectCmdResponse(const std::string &cmd, const std::string &response) +{ + gSupportedCmd[cmd] = response; +} + +void MockEraseSupportedCmd(const std::string &cmd) +{ + gSupportedCmd.erase(cmd); +} + +void MockInitGlobalCmd(void) +{ + gSupportedCmd["INTERFACE_ADD"] = "OK"; + gSupportedCmd["INTERFACE_REMOVE"] = "OK"; +} + +void MockInitStaSupportedCmd(void) +{ + gSupportedCmd["STATUS"] = "OK"; + gSupportedCmd["ADD_NETWORK"] = "OK"; + gSupportedCmd["RECONNECT"] = "OK"; + gSupportedCmd["REASSOCIATE"] = "OK"; + gSupportedCmd["DISCONNECT"] = "OK"; + gSupportedCmd["SAVE_CONFIG"] = "OK"; + gSupportedCmd["SET_NETWORK"] = "OK"; + gSupportedCmd["ENABLE_NETWORK"] = "OK"; + gSupportedCmd["SELECT_NETWORK"] = "OK"; + gSupportedCmd["DISABLE_NETWORK"] = "OK"; + gSupportedCmd["REMOVE_NETWORK"] = "OK"; + gSupportedCmd["GET_NETWORK"] = "OK"; + gSupportedCmd["WPS_PBC"] = "OK"; + gSupportedCmd["WPS_PIN"] = "OK"; + gSupportedCmd["WPS_CANCEL"] = "OK"; + gSupportedCmd["SET"] = "OK"; + gSupportedCmd["GET"] = "OK"; + gSupportedCmd["STA_AUTOCONNECT"] = "OK"; + gSupportedCmd["RECONFIGURE"] = "OK"; + gSupportedCmd["LIST_NETWORKS"] = "OK"; + gSupportedCmd["SIGNAL_POLL"] = "OK"; + return; +} + +void MockInitApSupportedCmd(void) +{ + gSupportedCmd["ENABLE"] = "OK"; + gSupportedCmd["SET"] = "OK"; + gSupportedCmd["STATUS"] = "OK"; + gSupportedCmd["DISABLE"] = "OK"; + gSupportedCmd["DENY_ACL"] = "OK"; + gSupportedCmd["STA-FIRST"] = "OK"; + gSupportedCmd["STA-NEXT"] = "OK"; + gSupportedCmd["RELOAD"] = "OK"; + gSupportedCmd["DEAUTHENTICATE"] = "OK"; + gSupportedCmd["DISASSOCIATE"] = "OK"; + return; +} + +void MockInitP2pSupportedCmd(void) +{ + gSupportedCmd["P2P_STOP_FIND"] = "OK"; + gSupportedCmd["P2P_FIND"] = "OK"; + gSupportedCmd["SET"] = "OK"; + gSupportedCmd["STATUS"] = "OK"; + gSupportedCmd["P2P_FLUSH"] = "OK"; + gSupportedCmd["P2P_SERVICE_FLUSH"] = "OK"; + gSupportedCmd["P2P_PROV_DISC"] = "OK"; + gSupportedCmd["P2P_GROUP_ADD"] = "OK"; + gSupportedCmd["SAVE_CONFIG"] = "OK"; + gSupportedCmd["LIST_NETWORKS"] = "OK"; + gSupportedCmd["P2P_PEER"] = "OK\n"; + gSupportedCmd["P2P_SERV_DISC_RESP"] = "OK"; + gSupportedCmd["P2P_SERV_DISC_EXTERNAL"] = "OK"; + gSupportedCmd["DRIVER"] = "OK"; + gSupportedCmd["P2P_SERV_DISC_CANCEL_REQ"] = "OK"; + gSupportedCmd["P2P_SERV_DISC_REQ"] = "OK"; + gSupportedCmd["P2P_SERVICE_ADD"] = "OK"; + gSupportedCmd["P2P_SERVICE_DEL"] = "OK"; + gSupportedCmd["P2P_INVITE"] = "OK"; + gSupportedCmd["P2P_CANCEL"] = "OK"; + gSupportedCmd["P2P_SET"] = "OK"; + gSupportedCmd["P2P_EXT_LISTEN"] = "OK"; + gSupportedCmd["WFD_SUBELEM_SET"] = "OK"; + gSupportedCmd["REMOVE_NETWORK"] = "OK"; + gSupportedCmd["P2P_GROUP_REMOVE"] = "OK"; + gSupportedCmd["WPS_PBC"] = "OK"; + gSupportedCmd["WPS_PIN"] = "OK"; + gSupportedCmd["P2P_CONNECT"] = "OK"; + return; +} + +void MockWpaCallback(struct wpa_ctrl *send, const char *message) +{ + if (send == NULL || message == NULL) { + return; + } + write(send->s, message, strlen(message)); + return; +} + +static void SetNonBlock(int fd) +{ + int flags = fcntl(fd, F_GETFL, 0); + if (flags < 0) { + return; + } + flags |= O_NONBLOCK; + fcntl(fd, F_SETFL, flags); + return; +} + +struct wpa_ctrl *wpa_ctrl_open(const char *ctrl_path) +{ + (void)ctrl_path; + struct wpa_ctrl *ctrl = (struct wpa_ctrl *)calloc(1, sizeof(struct wpa_ctrl)); + if (ctrl == NULL) { + return NULL; + } + if (gUsePipeFdNum % OncePipeFdNum == 0) { + int pipeFd[OncePipeFdNum] = {0}; + pipe(pipeFd); + SetNonBlock(pipeFd[0]); + gPipeFd.push_back(pipeFd[0]); + gPipeFd.push_back(pipeFd[1]); + } + if (gUsePipeFdNum % OncePipeFdNum == 0) { + ctrl->s = gPipeFd[gUsePipeFdNum + 1]; + } else { + ctrl->s = gPipeFd[gUsePipeFdNum - 1]; + } + ++gUsePipeFdNum; + return ctrl; +} + +struct wpa_ctrl * wpa_ctrl_open2(const char *ctrl_path, const char *cli_path) +{ + (void)cli_path; + return wpa_ctrl_open(ctrl_path); +} + +void wpa_ctrl_close(struct wpa_ctrl *ctrl) +{ + if (ctrl == NULL) { + return; + } + close(ctrl->s); + for (auto iter = gPipeFd.begin(); iter != gPipeFd.end(); ++iter) { + if (*iter == ctrl->s) { + gPipeFd.erase(iter); + break; + } + } + --gUsePipeFdNum; + free(ctrl); + return; +} + +static void GetExactCmd(const char *cmd, char *out, int out_len) +{ + if (cmd == NULL || out == NULL) { + return; + } + int i = 0; + int j = 0; + if (strncmp(cmd, "IFNAME=", strlen("IFNAME=")) == 0) { + const char *p = strchr(cmd, ' '); + if (p == NULL) { + return; + } + j = p - cmd + 1; + } + while (i < out_len - 1 && cmd[i + j] != '\0' && cmd[i + j] != ' ') { + out[i] = cmd[i + j]; + ++i; + } + out[i] = '\0'; + return; +} + +static int CheckInputCmdArgs(const char *cmd) +{ + (void)cmd; + return 0; +} + +int wpa_ctrl_request(struct wpa_ctrl *ctrl, const char *cmd, size_t cmd_len, char *reply, size_t *reply_len, + void (*msg_cb)(char *msg, size_t len)) +{ + if (ctrl == NULL || cmd == NULL || reply == NULL || reply_len == NULL) { + return -1; + } + (void)cmd_len; + (void)msg_cb; + char exactCmd[MaxExactCmdLength] = {0}; + GetExactCmd(cmd, exactCmd, MaxExactCmdLength); + std::map::iterator iter = gSupportedCmd.find(std::string(exactCmd)); + if (iter == gSupportedCmd.end()) { + StrSafeCopy(reply, *reply_len, "UNKNOWN COMMAND\n"); + *reply_len = strlen(reply); + return -1; + } + if (CheckInputCmdArgs(cmd) < 0) { + StrSafeCopy(reply, *reply_len, "FAIL\n"); + } else { + StrSafeCopy(reply, *reply_len, iter->second.c_str()); + } + *reply_len = strlen(reply); + return 0; +} + +int wpa_ctrl_attach(struct wpa_ctrl *ctrl) +{ + (void)ctrl; + return 0; +} + +int wpa_ctrl_detach(struct wpa_ctrl *ctrl) +{ + (void)ctrl; + return 0; +} + +int wpa_ctrl_recv(struct wpa_ctrl *ctrl, char *reply, size_t *reply_len) +{ + size_t pos = 0; + while (pos < *reply_len) { + int ret = read(ctrl->s, reply + pos, 1); + if (ret <= 0) { + break; + } + if (reply[pos] == '\n') { + break; + } + ++pos; + } + *reply_len = pos; + reply[pos] = '\0'; + return 0; +} + +int wpa_ctrl_pending(struct wpa_ctrl *ctrl) +{ + (void)ctrl; + return 0; +} + +int wpa_ctrl_get_fd(struct wpa_ctrl *ctrl) +{ + if (ctrl != NULL) { + return ctrl->s; + } + return -1; +} + +size_t printf_decode(u8 *buf, size_t maxlen, const char *str) +{ + return 0; +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.h b/tests/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.h new file mode 100644 index 000000000..e44f8e1b1 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.h @@ -0,0 +1,47 @@ +/* + * 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 WIFI_MOCK_WPA_CTRL_H +#define WIFI_MOCK_WPA_CTRL_H +#include "common/wpa_ctrl.h" +#ifdef __cplusplus +extern "C" { +#endif +#include "utils/common.h" +#ifdef __cplusplus +} +#endif +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct wpa_ctrl { + int s; +}; + +void MockSetWpaExpectCmdResponse(const std::string &cmd, const std::string &response); +void MockEraseSupportedCmd(const std::string &cmd); +void MockInitGlobalCmd(void); +void MockInitStaSupportedCmd(void); +void MockInitApSupportedCmd(void); +void MockInitP2pSupportedCmd(void); +void MockWpaCallback(struct wpa_ctrl *send, const char *message); +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_adapter_test.h b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_adapter_test.h new file mode 100644 index 000000000..4ee1b5a67 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_adapter_test.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_WIFI_HAL_ADAPTER_TEST_H +#define OHOS_WIFI_HAL_ADAPTER_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiHalAdapterTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.cpp b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.cpp new file mode 100644 index 000000000..eea026af1 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.cpp @@ -0,0 +1,121 @@ +/* + * 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 "wifi_hal_ap_interface_test.h" +#include "securec.h" +#include "wifi_log.h" +#include "wifi_hal_ap_interface.h" +#include "wifi_hal_common_func.h" +#include "mock_wpa_ctrl.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +void WifiHalApInterfaceTest::SetUpTestCase() +{ + MockInitApSupportedCmd(); +} + +HWTEST_F(WifiHalApInterfaceTest, StartSoftApTest, TestSize.Level1) +{ + EXPECT_TRUE(StartSoftAp() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalApInterfaceTest, GetStaInfosTest, TestSize.Level1) +{ + char infos[4096] = {0}; + int size = 4096; + EXPECT_TRUE(GetStaInfos(NULL, NULL) == WIFI_HAL_FAILED); + EXPECT_TRUE(GetStaInfos(infos, NULL) == WIFI_HAL_FAILED); + EXPECT_TRUE(GetStaInfos(NULL, &size) == WIFI_HAL_FAILED); + EXPECT_TRUE(GetStaInfos(infos, &size) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalApInterfaceTest, SetCountryCodeTest, TestSize.Level1) +{ + EXPECT_TRUE(SetCountryCode(NULL) == WIFI_HAL_INVALID_PARAM); + EXPECT_TRUE(SetCountryCode("") == WIFI_HAL_INVALID_PARAM); + EXPECT_TRUE(SetCountryCode("C") == WIFI_HAL_INVALID_PARAM); + EXPECT_TRUE(SetCountryCode("CN") == WIFI_HAL_SUCCESS); + EXPECT_TRUE(SetCountryCode("CHINA") == WIFI_HAL_INVALID_PARAM); +} + +HWTEST_F(WifiHalApInterfaceTest, SetHostapdConfigTest, TestSize.Level1) +{ + EXPECT_TRUE(SetHostapdConfig(NULL) == WIFI_HAL_FAILED); + HostapdConfig config; + ASSERT_TRUE(memset_s(&config, sizeof(config), 0, sizeof(config)) == EOK); + config.band = AP_2GHZ_BAND; + config.channel = 6; + config.maxConn = 20; + config.securityType = WPA_PSK; + StrSafeCopy(config.ssid, sizeof(config.ssid), "test_ssid"); + config.ssidLen = strlen(config.ssid); + StrSafeCopy(config.preSharedKey, sizeof(config.preSharedKey), "adc123456"); + config.preSharedKeyLen = strlen(config.preSharedKey); + EXPECT_TRUE(SetHostapdConfig(&config) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalApInterfaceTest, SetMacFilterTest, TestSize.Level1) +{ + EXPECT_TRUE(SetMacFilter(NULL, 0) == WIFI_HAL_FAILED); + unsigned char tmpMac[] = "00:00:00:00:00"; + EXPECT_TRUE(SetMacFilter(tmpMac, strlen((const char *)tmpMac)) == WIFI_HAL_FAILED); + unsigned char tmpMac2[] = "00.00.00.00.00.00"; + EXPECT_TRUE(SetMacFilter(tmpMac2, strlen((const char *)tmpMac2)) == WIFI_HAL_INPUT_MAC_INVALID); + unsigned char mac[] = "00:00:00:00:00:00"; + EXPECT_TRUE(SetMacFilter(mac, strlen((const char *)mac)) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalApInterfaceTest, DelMacFilterTest, TestSize.Level1) +{ + EXPECT_TRUE(DelMacFilter(NULL, 0) == WIFI_HAL_FAILED); + unsigned char tmpMac[] = "00:00:00:00:00"; + EXPECT_TRUE(DelMacFilter(tmpMac, strlen((const char *)tmpMac)) == WIFI_HAL_FAILED); + unsigned char tmpMac2[] = "00.00.00.00.00.00"; + EXPECT_TRUE(DelMacFilter(tmpMac2, strlen((const char *)tmpMac2)) == WIFI_HAL_INPUT_MAC_INVALID); + unsigned char mac[] = "00:00:00:00:00:00"; + EXPECT_TRUE(DelMacFilter(mac, strlen((const char *)mac)) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalApInterfaceTest, DisassociateStaTest, TestSize.Level1) +{ + EXPECT_TRUE(DisassociateSta(NULL, 0) == WIFI_HAL_FAILED); + unsigned char tmpMac[] = "00:00:00:00:00"; + EXPECT_TRUE(DisassociateSta(tmpMac, strlen((const char *)tmpMac)) == WIFI_HAL_FAILED); + unsigned char tmpMac2[] = "00.00.00.00.00.00"; + EXPECT_TRUE(DisassociateSta(tmpMac2, strlen((const char *)tmpMac2)) == WIFI_HAL_INPUT_MAC_INVALID); + unsigned char mac[] = "00:00:00:00:00:00"; + EXPECT_TRUE(DisassociateSta(mac, strlen((const char *)mac)) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalApInterfaceTest, GetValidFrequenciesForBandTest, TestSize.Level1) +{ + int32_t band = AP_2GHZ_BAND; + int frequencies[20] = {0}; + int size = 20; + EXPECT_TRUE(GetValidFrequenciesForBand(band, NULL, NULL) == WIFI_HAL_FAILED); + EXPECT_TRUE(GetValidFrequenciesForBand(band, frequencies, NULL) == WIFI_HAL_FAILED); + EXPECT_TRUE(GetValidFrequenciesForBand(band, NULL, &size) == WIFI_HAL_FAILED); + WifiErrorNo err = GetValidFrequenciesForBand(band, frequencies, &size); + EXPECT_TRUE(err == WIFI_HAL_SUCCESS || err == WIFI_HAL_NOT_SUPPORT); +} + +HWTEST_F(WifiHalApInterfaceTest, StopSoftApTest, TestSize.Level1) +{ + EXPECT_TRUE(StopSoftAp() == WIFI_HAL_SUCCESS); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.h b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.h new file mode 100644 index 000000000..c83e27c6a --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.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_WIFI_HAL_AP_INTERFACE_TEST_H +#define OHOS_WIFI_HAL_AP_INTERFACE_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiHalApInterfaceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.cpp b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.cpp new file mode 100644 index 000000000..cb8b3dc56 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.cpp @@ -0,0 +1,37 @@ +/* + * 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 "wifi_hal_base_interface_test.h" +#include "wifi_hal_base_interface.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiHalBaseInterfaceTest, GetNameTest, TestSize.Level1) +{ + EXPECT_TRUE(GetName(NULL, 0) == WIFI_HAL_SUCCESS); + char ifname[] = "wlan0"; + int size = strlen(ifname); + EXPECT_TRUE(GetName(ifname, size) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalBaseInterfaceTest, GetTypeTest, TestSize.Level1) +{ + EXPECT_TRUE(GetType(NULL) == WIFI_HAL_SUCCESS); + int32_t type = 0; + EXPECT_TRUE(GetType(&type) == WIFI_HAL_SUCCESS); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.h b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.h new file mode 100644 index 000000000..93abd0e75 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.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_WIFI_HAL_BASE_INTERFACE_TEST_H +#define OHOS_WIFI_HAL_BASE_INTERFACE_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiHalBaseInterfaceTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.cpp b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.cpp new file mode 100644 index 000000000..62bea0db4 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.cpp @@ -0,0 +1,106 @@ +/* + * 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 "wifi_hal_chip_interface_test.h" +#include "securec.h" +#include "wifi_hal_chip_interface.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +HWTEST_F(WifiHalChipInterfaceTest, GetWifiChipTest, TestSize.Level1) +{ + uint8_t id = 0; + WifiChip chip; + EXPECT_TRUE(GetWifiChip(id, NULL) == WIFI_HAL_SUCCESS); + EXPECT_TRUE(GetWifiChip(id, &chip) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalChipInterfaceTest, GetWifiChipIdsTest, TestSize.Level1) +{ + EXPECT_TRUE(GetWifiChipIds(NULL, NULL) == WIFI_HAL_SUCCESS); + uint8_t ids[32] = {0}; + int size = 32; + EXPECT_TRUE(GetWifiChipIds(ids, &size) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalChipInterfaceTest, GetChipIdTest, TestSize.Level1) +{ + EXPECT_TRUE(GetChipId(NULL) == WIFI_HAL_SUCCESS); + int32_t id = 0; + EXPECT_TRUE(GetChipId(&id) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalChipInterfaceTest, CreateRemoveIfaceTest, TestSize.Level1) +{ + EXPECT_TRUE(CreateIface(0, NULL) == WIFI_HAL_FAILED); + WifiIface iface; + ASSERT_TRUE(memset_s(&iface, sizeof(iface), 0, sizeof(iface)) == EOK); + EXPECT_TRUE(CreateIface(0, &iface) == WIFI_HAL_SUCCESS); + EXPECT_TRUE(iface.type == 0); + // test RemoveIface + EXPECT_TRUE(RemoveIface(NULL) == WIFI_HAL_FAILED); +} + +HWTEST_F(WifiHalChipInterfaceTest, GetIfaceNamesTest, TestSize.Level1) +{ + EXPECT_TRUE(GetIfaceNames(0, NULL, 0) == WIFI_HAL_SUCCESS); + char ifaces[128] = {0}; + int size = 128; + EXPECT_TRUE(GetIfaceNames(0, ifaces, size) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalChipInterfaceTest, GetCapabilitiesTest, TestSize.Level1) +{ + EXPECT_TRUE(GetCapabilities(NULL) == WIFI_HAL_SUCCESS); + uint32_t capability = 0; + EXPECT_TRUE(GetCapabilities(&capability) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalChipInterfaceTest, GetSupportedComboModesTest, TestSize.Level1) +{ + EXPECT_TRUE(GetSupportedComboModes(NULL, NULL) == WIFI_HAL_FAILED); + int32_t modes[32] = {0}; + int size = 32; + WifiErrorNo ret = GetSupportedComboModes(modes, &size); + EXPECT_TRUE(ret == WIFI_HAL_SUCCESS || ret == WIFI_HAL_NOT_SUPPORT); +} + +HWTEST_F(WifiHalChipInterfaceTest, ConfigComboModesTest, TestSize.Level1) +{ + EXPECT_TRUE(ConfigComboModes(0) == WIFI_HAL_NOT_SUPPORT); +} + +HWTEST_F(WifiHalChipInterfaceTest, GetComboModesTest, TestSize.Level1) +{ + EXPECT_TRUE(GetComboModes(NULL) == WIFI_HAL_FAILED); + int mode = 0; + EXPECT_TRUE(GetComboModes(&mode) == WIFI_HAL_NOT_SUPPORT); +} + +HWTEST_F(WifiHalChipInterfaceTest, RequestFirmwareDebugDumpTest, TestSize.Level1) +{ + EXPECT_TRUE(RequestFirmwareDebugDump(NULL, NULL) == WIFI_HAL_FAILED); + unsigned char bytes[32] = {0}; + int size = 32; + EXPECT_TRUE(RequestFirmwareDebugDump(bytes, &size) == WIFI_HAL_NOT_SUPPORT); +} + +HWTEST_F(WifiHalChipInterfaceTest, SetPowerModeTest, TestSize.Level1) +{ + EXPECT_TRUE(SetPowerMode(0) == WIFI_HAL_SUCCESS); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.h b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.h new file mode 100644 index 000000000..3ab38b701 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.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_WIFI_HAL_CHIP_INTERFACE_TEST_H +#define OHOS_WIFI_HAL_CHIP_INTERFACE_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiHalChipInterfaceTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.cpp b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.cpp new file mode 100644 index 000000000..2d2f949cf --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.cpp @@ -0,0 +1,627 @@ +/* + * 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 "wifi_hal_crpc_server_add_test.h" +#include "wifi_log.h" +#include "wifi_hal_crpc_server.h" +#include "wifi_hal_crpc_p2p.h" +#include "mock_wpa_ctrl.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +static std::string g_rpcSockPath = "./unix_sock_test.sock"; +RpcServer *WifiHalCRpcServerAddTest::mServer = nullptr; +Context *WifiHalCRpcServerAddTest::mContext = nullptr; + +void WifiHalCRpcServerAddTest::SetUpTestCase() +{ + if (access(g_rpcSockPath.c_str(), 0) == 0) { + unlink(g_rpcSockPath.c_str()); + } + mServer = CreateRpcServer(g_rpcSockPath.c_str()); + mContext = CreateContext(CONTEXT_BUFFER_MIN_SIZE); + if (mServer == nullptr || mContext == nullptr) { + printf("Init rpc server failed or create context failed!"); + exit(-1); + } + InitCallbackMsg(); + SetRpcServerInited(mServer); + MockInitGlobalCmd(); + MockInitP2pSupportedCmd(); +} + +void WifiHalCRpcServerAddTest::TearDownTestCase() +{ + if (mServer != nullptr) { + ReleaseRpcServer(mServer); + mServer = nullptr; + } + SetRpcServerInited(NULL); + ReleaseCallbackMsg(); + if (mContext != nullptr) { + ReleaseContext(mContext); + mContext = nullptr; + } +} + +void WifiHalCRpcServerAddTest::SetUp() +{ + if (mContext != nullptr) { + mContext->wBegin = mContext->wEnd = 0; + } +} + +void WifiHalCRpcServerAddTest::TearDown() +{ + if (mContext != nullptr) { + mContext->wBegin = mContext->wEnd = 0; + } +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pStartTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pStart(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcP2pStart(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pStopTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pStop(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcP2pStop(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetRandomMacTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetRandomMac(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetRandomMac|1"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetRandomMac|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetRandomMac(mServer, mContext) < 0); + char buff1[] = "N|P2pSetRandomMac|1|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetRandomMac|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetRandomMac(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetDeviceNameTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetDeviceName(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetDeviceName|p2p_device_name"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetDeviceName|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetDeviceName(mServer, mContext) < 0); + char buff1[] = "N|P2pSetDeviceName|p2p_device_name|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetDeviceName|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetDeviceName(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetSsidPostfixNameTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetSsidPostfixName(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetSsidPostfixName|p2p_postfix_name"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetSsidPostfixName|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetSsidPostfixName(mServer, mContext) < 0); + char buff1[] = "N|P2pSetSsidPostfixName|p2p_postfix_name|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetSsidPostfixName|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetSsidPostfixName(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetWpsDeviceTypeTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetWpsDeviceType(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetWpsDeviceType|p2p_device_type"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetWpsDeviceType|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetWpsDeviceType(mServer, mContext) < 0); + char buff1[] = "N|P2pSetWpsDeviceType|p2p_device_type|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetWpsDeviceType|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetWpsDeviceType(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetWpsConfigMethodsTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetWpsConfigMethods(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetWpsConfigMethods|p2p_config_methods"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetWpsConfigMethods|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetWpsConfigMethods(mServer, mContext) < 0); + char buff1[] = "N|P2pSetWpsConfigMethods|p2p_config_methods|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetWpsConfigMethods|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetWpsConfigMethods(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pGetDeviceAddressTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pGetDeviceAddress(nullptr, nullptr) < 0); + char buff[] = "N|P2pGetDeviceAddress|17"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pGetDeviceAddress|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pGetDeviceAddress(mServer, mContext) < 0); + char buff1[] = "N|P2pGetDeviceAddress|17|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pGetDeviceAddress|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pGetDeviceAddress(mServer, mContext) == 0); + char buff2[] = "N|P2pGetDeviceAddress|-1|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|P2pGetDeviceAddress|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcP2pGetDeviceAddress(mServer, mContext) < 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pFlushTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pFlush(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcP2pFlush(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pFlushServiceTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pFlushService(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcP2pFlushService(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSaveConfigTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSaveConfig(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcP2pSaveConfig(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetupWpsPbcTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetupWpsPbc(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetupWpsPbc|p2p-dev-wlan0|00:00:00:00:00:00"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetupWpsPbc|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetupWpsPbc(mServer, mContext) < 0); + char buff1[] = "N|P2pSetupWpsPbc|p2p-dev-wlan0|00:00:00:00:00:00|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetupWpsPbc|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetupWpsPbc(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetupWpsPinTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetupWpsPin(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetupWpsPin|p2p-dev-wlan0|00:00:00:00:00:00|123456789|8|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetupWpsPin|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetupWpsPin(mServer, mContext) < 0); + char buff1[] = "N|P2pSetupWpsPin|p2p-dev-wlan0|00:00:00:00:00:00|12345678|8|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetupWpsPin|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetupWpsPin(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pRemoveNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pRemoveNetwork(nullptr, nullptr) < 0); + char buff[] = "N|P2pRemoveNetwork|1"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pRemoveNetwork|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pRemoveNetwork(mServer, mContext) < 0); + char buff1[] = "N|P2pRemoveNetwork|1|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pRemoveNetwork|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pRemoveNetwork(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pListNetworksTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pListNetworks(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcP2pListNetworks(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetGroupMaxIdleTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetGroupMaxIdle(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetGroupMaxIdle|p2p-dev-wlan0|1"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetGroupMaxIdle|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetGroupMaxIdle(mServer, mContext) < 0); + char buff1[] = "N|P2pSetGroupMaxIdle|p2p-dev-wlan0|1|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetGroupMaxIdle|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetGroupMaxIdle(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetPowerSaveTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetPowerSave(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetPowerSave|p2p-dev-wlan0|1"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetPowerSave|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetPowerSave(mServer, mContext) < 0); + char buff1[] = "N|P2pSetPowerSave|p2p-dev-wlan0|1|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetPowerSave|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetPowerSave(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetWfdEnableTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetWfdEnable(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetWfdEnable|1"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetWfdEnable|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetWfdEnable(mServer, mContext) < 0); + char buff1[] = "N|P2pSetWfdEnable|1|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetWfdEnable|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetWfdEnable(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetWfdDeviceConfigTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetWfdDeviceConfig(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetWfdDeviceConfig|p2p_device_config"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetWfdDeviceConfig|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetWfdDeviceConfig(mServer, mContext) < 0); + char buff1[] = "N|P2pSetWfdDeviceConfig|p2p_device_config|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetWfdDeviceConfig|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetWfdDeviceConfig(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pStartFindTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pStartFind(nullptr, nullptr) < 0); + char buff[] = "N|P2pStartFind|120"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pStartFind|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pStartFind(mServer, mContext) < 0); + char buff1[] = "N|P2pStartFind|120|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pStartFind|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pStartFind(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pStopFindTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pStopFind(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcP2pStopFind(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetExtListenTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetExtListen(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetExtListen|0|0|0"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetExtListen|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetExtListen(mServer, mContext) < 0); + char buff1[] = "N|P2pSetExtListen|0|0|0|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetExtListen|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetExtListen(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetListenChannelTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetListenChannel(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetListenChannel|0|0"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetListenChannel|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetListenChannel(mServer, mContext) < 0); + char buff1[] = "N|P2pSetListenChannel|0|0|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetListenChannel|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetListenChannel(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pConnectTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pConnect(nullptr, nullptr) < 0); + char buff[] = "N|P2pConnect|0|0|0|0|00:00:00:00:00:00|12345678"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pConnect|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pConnect(mServer, mContext) < 0); + char buff1[] = "N|P2pConnect|0|0|0|0|00:00:00:00:00:00|12345678|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pConnect|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pConnect(mServer, mContext) == 0); + char buff2[] = "N|P2pConnect|0|1|0|0|00:00:00:00:00:00|pin|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|P2pConnect|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcP2pConnect(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pCancelConnectTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pCancelConnect(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcP2pCancelConnect(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pProvisionDiscoveryTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pProvisionDiscovery(nullptr, nullptr) < 0); + char buff[] = "N|P2pProvisionDiscovery|00:00:00:00:00:00|1"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pProvisionDiscovery|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pProvisionDiscovery(mServer, mContext) < 0); + char buff1[] = "N|P2pProvisionDiscovery|00:00:00:00:00:00|1|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pProvisionDiscovery|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pProvisionDiscovery(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pAddGroupTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pAddGroup(nullptr, nullptr) < 0); + char buff[] = "N|P2pAddGroup|0|1|0"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pAddGroup|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pAddGroup(mServer, mContext) < 0); + char buff1[] = "N|P2pAddGroup|0|1|0|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pAddGroup|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pAddGroup(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pRemoveGroupTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pRemoveGroup(nullptr, nullptr) < 0); + char buff[] = "N|P2pRemoveGroup|p2p-dev-wlan0"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pRemoveGroup|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pRemoveGroup(mServer, mContext) < 0); + char buff1[] = "N|P2pRemoveGroup|p2p-dev-wlan0|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pRemoveGroup|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pRemoveGroup(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pInviteTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pInvite(nullptr, nullptr) < 0); + char buff[] = "N|P2pInvite|0|||p2p-dev-wlan0"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pInvite|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pInvite(mServer, mContext) < 0); + char buff1[] = "N|P2pInvite|0|||p2p-dev-wlan0|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pInvite|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pInvite(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pReinvokeTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pReinvoke(nullptr, nullptr) < 0); + char buff[] = "N|P2pReinvoke|0|00:00:00:00:00:00"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pReinvoke|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pReinvoke(mServer, mContext) < 0); + char buff1[] = "N|P2pReinvoke|0|00:00:00:00:00:00|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pReinvoke|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pReinvoke(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pGetGroupCapabilityTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pGetGroupCapability(nullptr, nullptr) < 0); + char buff[] = "N|P2pGetGroupCapability|00:00:00:00:00:00"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pGetGroupCapability|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pGetGroupCapability(mServer, mContext) < 0); + char buff1[] = "N|P2pGetGroupCapability|00:00:00:00:00:00|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pGetGroupCapability|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pGetGroupCapability(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pAddServiceTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pAddService(nullptr, nullptr) < 0); + char buff[] = "N|P2pAddService|x|0|service_name"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pAddService|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pAddService(mServer, mContext) < 0); + char buff1[] = "N|P2pAddService|0|0|service_name"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pAddService|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pAddService(mServer, mContext) < 0); + char buff2[] = "N|P2pAddService|0|0|service_name|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|P2pAddService|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcP2pAddService(mServer, mContext) == 0); + char buff3[] = "N|P2pAddService|1|query_message|resp_message"; + mContext->oneProcess = buff3; + mContext->nPos = strlen("N|P2pAddService|"); + mContext->nSize = strlen(buff3); + EXPECT_TRUE(RpcP2pAddService(mServer, mContext) < 0); + char buff4[] = "N|P2pAddService|1|query_message|resp_message|"; + mContext->oneProcess = buff4; + mContext->nPos = strlen("N|P2pAddService|"); + mContext->nSize = strlen(buff4); + EXPECT_TRUE(RpcP2pAddService(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pRemoveServiceTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pRemoveService(nullptr, nullptr) < 0); + char buff[] = "N|P2pRemoveService|x|0|service_name"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pRemoveService|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pRemoveService(mServer, mContext) < 0); + char buff1[] = "N|P2pRemoveService|0|0|service_name"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pRemoveService|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pRemoveService(mServer, mContext) < 0); + char buff2[] = "N|P2pRemoveService|0|0|service_name|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|P2pRemoveService|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcP2pRemoveService(mServer, mContext) == 0); + char buff3[] = "N|P2pRemoveService|1|query_message"; + mContext->oneProcess = buff3; + mContext->nPos = strlen("N|P2pRemoveService|"); + mContext->nSize = strlen(buff3); + EXPECT_TRUE(RpcP2pRemoveService(mServer, mContext) < 0); + char buff4[] = "N|P2pRemoveService|1|query_message|"; + mContext->oneProcess = buff4; + mContext->nPos = strlen("N|P2pRemoveService|"); + mContext->nSize = strlen(buff4); + EXPECT_TRUE(RpcP2pRemoveService(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pReqServiceDiscoveryTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pReqServiceDiscovery(nullptr, nullptr) < 0); + char buff[] = "N|P2pReqServiceDiscovery|00:00:00:00:00:00|discover message"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pReqServiceDiscovery|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pReqServiceDiscovery(mServer, mContext) < 0); + char buff1[] = "N|P2pReqServiceDiscovery|00:00:00:00:00:00|discover message|32|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pReqServiceDiscovery|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pReqServiceDiscovery(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pCancelServiceDiscoveryTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pCancelServiceDiscovery(nullptr, nullptr) < 0); + char buff[] = "N|P2pCancelServiceDiscovery|discover message"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pCancelServiceDiscovery|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pCancelServiceDiscovery(mServer, mContext) < 0); + char buff1[] = "N|P2pCancelServiceDiscovery|discover message|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pCancelServiceDiscovery|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pCancelServiceDiscovery(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetMiracastTypeTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetMiracastType(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetMiracastType|x|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetMiracastType|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetMiracastType(mServer, mContext) < 0); + char buff1[] = "N|P2pSetMiracastType|1|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetMiracastType|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetMiracastType(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pRespServerDiscoveryTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pRespServerDiscovery(nullptr, nullptr) < 0); + char buff[] = "N|P2pRespServerDiscovery|0|0|00:00:00:00:00:00|tlvs message"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pRespServerDiscovery|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pRespServerDiscovery(mServer, mContext) < 0); + char buff1[] = "N|P2pRespServerDiscovery|0|0|00:00:00:00:00:00|tlvs message|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pRespServerDiscovery|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pRespServerDiscovery(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetServDiscExternalTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetServDiscExternal(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetServDiscExternal|x|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetServDiscExternal|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetServDiscExternal(mServer, mContext) < 0); + char buff1[] = "N|P2pSetServDiscExternal|1|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetServDiscExternal|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetServDiscExternal(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetPersistentReconnectTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcP2pSetPersistentReconnect(nullptr, nullptr) < 0); + char buff[] = "N|P2pSetPersistentReconnect|x|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|P2pSetPersistentReconnect|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcP2pSetPersistentReconnect(mServer, mContext) < 0); + char buff1[] = "N|P2pSetPersistentReconnect|1|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|P2pSetPersistentReconnect|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcP2pSetPersistentReconnect(mServer, mContext) == 0); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.h b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.h new file mode 100644 index 000000000..7b77cc144 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.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_WIFI_HAL_CRPC_SERVER_ADD_TEST_H +#define OHOS_WIFI_HAL_CRPC_SERVER_ADD_TEST_H + +#include +#include "server.h" + +namespace OHOS { +namespace Wifi { +class WifiHalCRpcServerAddTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp(); + virtual void TearDown(); + +public: + static RpcServer *mServer; + static Context *mContext; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.cpp b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.cpp new file mode 100644 index 000000000..b95c984e0 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.cpp @@ -0,0 +1,1298 @@ +/* + * 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 "wifi_hal_crpc_server_test.h" +#include "wifi_log.h" +#include "wifi_hal_crpc_server.h" +#include "wifi_hal_crpc_base.h" +#include "wifi_hal_crpc_chip.h" +#include "wifi_hal_crpc_supplicant.h" +#include "wifi_hal_crpc_sta.h" +#include "wifi_hal_crpc_ap.h" +#include "wifi_hal_crpc_common.h" +#include "wifi_hal_crpc_p2p.h" +#include "wifi_hal_ap_interface.h" +#include "wifi_hal_sta_interface.h" +#include "mock_wpa_ctrl.h" +#include "wifi_hal_common_func.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +static std::string g_rpcSockPath = "./unix_sock_test.sock"; +RpcServer *WifiHalCRpcServerTest::mServer = nullptr; +Context *WifiHalCRpcServerTest::mContext = nullptr; + +static int StrcmpMathRight(const char *left, const char *right) +{ + return strncmp(left, right, strlen(right)); +} + +void WifiHalCRpcServerTest::SetUpTestCase() +{ + if (access(g_rpcSockPath.c_str(), 0) == 0) { + unlink(g_rpcSockPath.c_str()); + } + mServer = CreateRpcServer(g_rpcSockPath.c_str()); + mContext = CreateContext(CONTEXT_BUFFER_MIN_SIZE); + if (mServer == nullptr || mContext == nullptr) { + printf("Init rpc server failed or create context failed!"); + exit(-1); + } + SetRpcServerInited(mServer); + MockInitGlobalCmd(); + MockInitStaSupportedCmd(); + MockInitApSupportedCmd(); +} + +void WifiHalCRpcServerTest::TearDownTestCase() +{ + if (mServer != nullptr) { + ReleaseRpcServer(mServer); + mServer = nullptr; + } + SetRpcServerInited(NULL); + if (mContext != nullptr) { + ReleaseContext(mContext); + mContext = nullptr; + } +} + +void WifiHalCRpcServerTest::SetUp() +{ + InitRpcFunc(); + if (mContext != nullptr) { + mContext->wBegin = mContext->wEnd = 0; + } +} + +void WifiHalCRpcServerTest::TearDown() +{ + ReleaseRpcFunc(); + if (mContext != nullptr) { + mContext->wBegin = mContext->wEnd = 0; + } +} + +HWTEST_F(WifiHalCRpcServerTest, GetRpcFuncTest, TestSize.Level1) +{ + EXPECT_TRUE(GetRpcFunc("GetName") != nullptr); + EXPECT_TRUE(GetRpcFunc("GetNameTest") == nullptr); +} + +HWTEST_F(WifiHalCRpcServerTest, OnTransactTest, TestSize.Level1) +{ + char buff[] = "N|IncorrectTypeInputMessage"; + mContext->oneProcess = buff; + mContext->nPos = 2; + mContext->nSize = strlen(buff); + EXPECT_TRUE(OnTransact(mServer, mContext) < 0); + char buff2[] = "N|UnsupportedCmd|"; + mContext->oneProcess = buff2; + mContext->nPos = 2; + mContext->nSize = strlen(buff2); + EXPECT_TRUE(OnTransact(mServer, mContext) == 0); + EXPECT_TRUE(strstr(mContext->szWrite, "unsupport function") != nullptr); + char buff3[] = "N|SetCountryCode|"; + mContext->oneProcess = buff3; + mContext->nPos = 2; + mContext->nSize = strlen(buff3); + EXPECT_TRUE(OnTransact(mServer, mContext) == 0); + EXPECT_TRUE(strstr(mContext->szWrite, "server deal failed!") != nullptr); +} + +HWTEST_F(WifiHalCRpcServerTest, PushPopCallbackMsgTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *msg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + ASSERT_TRUE(msg != nullptr); + msg->msg.scanStatus = 100; + int event = WIFI_FAILURE_EVENT - 1; + EXPECT_TRUE(PushBackCallbackMsg(event, msg) < 0); + event = WIFI_HAL_MAX_EVENT; + EXPECT_TRUE(PushBackCallbackMsg(event, msg) < 0); + event = WIFI_FAILURE_EVENT; + EXPECT_TRUE(PushBackCallbackMsg(event, msg) == 0); + WifiHalEventCallbackMsg *msg1 = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + ASSERT_TRUE(msg1 != nullptr); + msg1->msg.scanStatus = 101; + EXPECT_TRUE(PushBackCallbackMsg(event, msg1) == 0); + WifiHalEventCallbackMsg *msg2 = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + ASSERT_TRUE(msg2 != nullptr); + msg2->msg.scanStatus = 102; + EXPECT_TRUE(PushBackCallbackMsg(event, msg2) == 0); + EXPECT_TRUE(PopBackCallbackMsg(WIFI_HAL_MAX_EVENT) < 0); + EXPECT_TRUE(PopBackCallbackMsg(event) == 0); + EXPECT_TRUE(FrontCallbackMsg(WIFI_HAL_MAX_EVENT) == nullptr); + WifiHalEventCallbackMsg *p = FrontCallbackMsg(event); + EXPECT_TRUE(p->msg.scanStatus == 100); + EXPECT_TRUE(PopFrontCallbackMsg(WIFI_HAL_MAX_EVENT) < 0); + EXPECT_TRUE(PopFrontCallbackMsg(event) == 0); + p = FrontCallbackMsg(event); + EXPECT_TRUE(p->msg.scanStatus == 101); + EXPECT_TRUE(PopFrontCallbackMsg(event) == 0); + p = FrontCallbackMsg(event); + EXPECT_TRUE(p == nullptr); + free(msg2); +} + +HWTEST_F(WifiHalCRpcServerTest, OnCallbackTransactTest, TestSize.Level1) +{ + EXPECT_TRUE(OnCallbackTransact(nullptr, 0, nullptr) < 0); + EXPECT_TRUE(OnCallbackTransact(mServer, WIFI_FAILURE_EVENT, mContext) == 0); + EXPECT_TRUE(EndCallbackTransact(nullptr, 0) < 0); + EXPECT_TRUE(EndCallbackTransact(mServer, WIFI_FAILURE_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealCommonCbkTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + cbmsg->msg.scanStatus = 100; + EXPECT_TRUE(PushBackCallbackMsg(WIFI_SCAN_INFO_NOTIFY_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, WIFI_SCAN_INFO_NOTIFY_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|107|100|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, WIFI_SCAN_INFO_NOTIFY_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealIfaceCbkTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + cbmsg->msg.ifMsg.type = 100; + StrSafeCopy(cbmsg->msg.ifMsg.ifname, sizeof(cbmsg->msg.ifMsg.ifname), "wlan0"); + EXPECT_TRUE(PushBackCallbackMsg(WIFI_ADD_IFACE_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, WIFI_ADD_IFACE_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|103|100|wlan0|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, WIFI_ADD_IFACE_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealConnectionChangedCbkTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + cbmsg->msg.connMsg.status = 100; + cbmsg->msg.connMsg.networkId = 1; + StrSafeCopy(cbmsg->msg.connMsg.bssid, sizeof(cbmsg->msg.connMsg.bssid), "00:00:00:00:00:00"); + EXPECT_TRUE(PushBackCallbackMsg(WIFI_CONNECT_CHANGED_NOTIFY_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, WIFI_CONNECT_CHANGED_NOTIFY_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|108|100|1|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, WIFI_CONNECT_CHANGED_NOTIFY_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealP2pDeviceFoundCbkTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + StrSafeCopy(cbmsg->msg.deviceInfo.srcAddress, sizeof(cbmsg->msg.deviceInfo.srcAddress), "00:00:00:00:00:00"); + EXPECT_TRUE(PushBackCallbackMsg(P2P_DEVICE_FOUND_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, P2P_DEVICE_FOUND_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|117|0|0|0|0|00:00:00:00:00:00|||||$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, P2P_DEVICE_FOUND_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealP2pNegoriationCbkLostTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + StrSafeCopy(cbmsg->msg.connMsg.bssid, sizeof(cbmsg->msg.connMsg.bssid), "00:00:00:00:00:00"); + EXPECT_TRUE(PushBackCallbackMsg(P2P_DEVICE_LOST_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, P2P_DEVICE_LOST_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|118|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, P2P_DEVICE_LOST_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealP2pNegoriationCbkTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + StrSafeCopy(cbmsg->msg.connMsg.bssid, sizeof(cbmsg->msg.connMsg.bssid), "00:00:00:00:00:00"); + EXPECT_TRUE(PushBackCallbackMsg(P2P_GO_NEGOTIATION_REQUEST_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, P2P_GO_NEGOTIATION_REQUEST_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|119|0|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, P2P_GO_NEGOTIATION_REQUEST_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealP2pInviationCbkReceiveTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + StrSafeCopy(cbmsg->msg.invitaInfo.srcAddress, sizeof(cbmsg->msg.invitaInfo.srcAddress), "00:00:00:00:00:00"); + StrSafeCopy(cbmsg->msg.invitaInfo.bssid, sizeof(cbmsg->msg.invitaInfo.bssid), "00:00:00:00:00:00"); + EXPECT_TRUE(PushBackCallbackMsg(P2P_INVITATION_RECEIVED_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, P2P_INVITATION_RECEIVED_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|122|0|0|0|00:00:00:00:00:00||00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, P2P_INVITATION_RECEIVED_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealP2pInviationCbkResultTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + StrSafeCopy(cbmsg->msg.invitaInfo.bssid, sizeof(cbmsg->msg.invitaInfo.bssid), "00:00:00:00:00:00"); + EXPECT_TRUE(PushBackCallbackMsg(P2P_INVITATION_RESULT_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, P2P_INVITATION_RESULT_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|123|0|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, P2P_INVITATION_RESULT_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealP2pInviationCbkFailureTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + StrSafeCopy(cbmsg->msg.invitaInfo.bssid, sizeof(cbmsg->msg.invitaInfo.bssid), "00:00:00:00:00:00"); + EXPECT_TRUE(PushBackCallbackMsg(P2P_GROUP_FORMATION_FAILURE_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, P2P_GROUP_FORMATION_FAILURE_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|125|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, P2P_GROUP_FORMATION_FAILURE_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealP2pGroupInfoCbkStartTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + StrSafeCopy(cbmsg->msg.groupInfo.groupIfName, sizeof(cbmsg->msg.groupInfo.groupIfName), "p2p-dev-wlan0"); + StrSafeCopy(cbmsg->msg.groupInfo.ssid, sizeof(cbmsg->msg.groupInfo.ssid), "test_p2p"); + StrSafeCopy( + cbmsg->msg.groupInfo.goDeviceAddress, sizeof(cbmsg->msg.groupInfo.goDeviceAddress), "00:00:00:00:00:00"); + EXPECT_TRUE(PushBackCallbackMsg(P2P_GROUP_STARTED_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, P2P_GROUP_STARTED_EVENT, mContext) == 0); + EXPECT_TRUE( + StrcmpMathRight(mContext->szWrite, "C|126|0|0|0|p2p-dev-wlan0|test_p2p|||00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, P2P_GROUP_STARTED_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealP2pGroupInfoCbkRemoveTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + StrSafeCopy(cbmsg->msg.groupInfo.groupIfName, sizeof(cbmsg->msg.groupInfo.groupIfName), "p2p-dev-wlan0"); + EXPECT_TRUE(PushBackCallbackMsg(P2P_GROUP_REMOVED_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, P2P_GROUP_REMOVED_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|127|0|p2p-dev-wlan0|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, P2P_GROUP_REMOVED_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealP2pDeviceInfoCbkPbcTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + StrSafeCopy(cbmsg->msg.deviceInfo.srcAddress, sizeof(cbmsg->msg.deviceInfo.srcAddress), "00:00:00:00:00:00"); + EXPECT_TRUE(PushBackCallbackMsg(P2P_PROV_DISC_PBC_REQ_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, P2P_PROV_DISC_PBC_REQ_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|128|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, P2P_PROV_DISC_PBC_REQ_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealP2pDeviceInfoCbkPinTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + StrSafeCopy(cbmsg->msg.deviceInfo.srcAddress, sizeof(cbmsg->msg.deviceInfo.srcAddress), "00:00:00:00:00:00"); + StrSafeCopy(cbmsg->msg.deviceInfo.deviceName, sizeof(cbmsg->msg.deviceInfo.deviceName), "test_p2p"); + EXPECT_TRUE(PushBackCallbackMsg(P2P_PROV_DISC_SHOW_PIN_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, P2P_PROV_DISC_SHOW_PIN_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|131|00:00:00:00:00:00|test_p2p|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, P2P_PROV_DISC_SHOW_PIN_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealP2pDeviceInfoCbkConnectionTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + StrSafeCopy( + cbmsg->msg.deviceInfo.p2pDeviceAddress, sizeof(cbmsg->msg.deviceInfo.p2pDeviceAddress), "00:00:00:00:00:00"); + EXPECT_TRUE(PushBackCallbackMsg(AP_STA_DISCONNECTED_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, AP_STA_DISCONNECTED_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|135|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, AP_STA_DISCONNECTED_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealP2pServerInfoCbkTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + StrSafeCopy(cbmsg->msg.serverInfo.srcAddress, sizeof(cbmsg->msg.serverInfo.srcAddress), "00:00:00:00:00:00"); + EXPECT_TRUE(PushBackCallbackMsg(P2P_SERV_DISC_RESP_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, P2P_SERV_DISC_RESP_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|133|0|00:00:00:00:00:00|0|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, P2P_SERV_DISC_RESP_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, DealP2pServerDiscReqCbkTest, TestSize.Level1) +{ + WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + StrSafeCopy(cbmsg->msg.serDiscReqInfo.mac, sizeof(cbmsg->msg.serDiscReqInfo.mac), "00:00:00:00:00:00"); + EXPECT_TRUE(PushBackCallbackMsg(P2P_SERV_DISC_REQ_EVENT, cbmsg) == 0); + EXPECT_TRUE(OnCallbackTransact(mServer, P2P_SERV_DISC_REQ_EVENT, mContext) == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|137|0|0|0|00:00:00:00:00:00|0|$$$$$$") == 0); + EXPECT_TRUE(EndCallbackTransact(mServer, P2P_SERV_DISC_REQ_EVENT) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetNameTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetName(nullptr, nullptr) < 0); + char buff[] = "N|GetName|x|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|GetName|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcGetName(mServer, mContext) < 0); + char buff2[] = "N|GetName|128|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|GetName|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcGetName(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetTypeTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetType(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcGetType(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcRegisterEventCallbackTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcRegisterEventCallback(nullptr, nullptr) < 0); + char buff[] = "N|RegisterEventCallback|asdgfd|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|RegisterEventCallback|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcRegisterEventCallback(mServer, mContext) < 0); + char buff2[] = "N|RegisterEventCallback|2|101|asdf|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|RegisterEventCallback|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcRegisterEventCallback(mServer, mContext) < 0); + char buff3[] = "N|RegisterEventCallback|2|101|108|"; + mContext->oneProcess = buff3; + mContext->nPos = strlen("N|RegisterEventCallback|"); + mContext->nSize = strlen(buff3); + EXPECT_TRUE(RpcRegisterEventCallback(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcUnRegisterEventCallbackTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcUnRegisterEventCallback(nullptr, nullptr) < 0); + char buff[] = "N|UnRegisterEventCallback|asdgfd|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|UnRegisterEventCallback|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcUnRegisterEventCallback(mServer, mContext) < 0); + char buff2[] = "N|UnRegisterEventCallback|2|101|asdf|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|UnRegisterEventCallback|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcUnRegisterEventCallback(mServer, mContext) < 0); + char buff3[] = "N|UnRegisterEventCallback|2|101|108|"; + mContext->oneProcess = buff3; + mContext->nPos = strlen("N|UnRegisterEventCallback|"); + mContext->nSize = strlen(buff3); + EXPECT_TRUE(RpcUnRegisterEventCallback(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcNotifyClearTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcNotifyClear(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcNotifyClear(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetWifiChipTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetWifiChip(nullptr, nullptr) < 0); + char buff[] = "N|GetWifiChip|adsgfsd|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|GetWifiChip|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcGetWifiChip(mServer, mContext) < 0); + char buff1[] = "N|GetWifiChip|8|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|GetWifiChip|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcGetWifiChip(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetWifiChipIdsTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetWifiChipIds(nullptr, nullptr) < 0); + char buff[] = "N|GetWifiChipIds|x|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|GetWifiChipIds|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcGetWifiChipIds(mServer, mContext) < 0); + char buff1[] = "N|GetWifiChipIds|8|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|GetWifiChipIds|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcGetWifiChipIds(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetChipIdTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetChipId(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcGetChipId(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcCreateIfaceTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcCreateIface(nullptr, nullptr) < 0); + char buff[] = "N|CreateIface|fdshajkdsghk|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|CreateIface|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcCreateIface(mServer, mContext) < 0); + char buff1[] = "N|CreateIface|8|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|CreateIface|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcCreateIface(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetIfaceTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetIface(nullptr, nullptr) < 0); + char buff[] = "N|GetIface|wlan0"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|GetIface|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcGetIface(mServer, mContext) < 0); + char buff1[] = "N|GetIface|wlan0|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|GetIface|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcGetIface(mServer, mContext) == 0); + char buff2[] = "N|GetIface|01234567890123456789012345678901|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|GetIface|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcGetIface(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetIfaceNamesTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetIfaceNames(nullptr, nullptr) < 0); + char buff[] = "N|GetIfaceNames|asdgf|asdgf|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|GetIfaceNames|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcGetIfaceNames(mServer, mContext) < 0); + char buff1[] = "N|GetIfaceNames|12|asdgf|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|GetIfaceNames|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcGetIfaceNames(mServer, mContext) < 0); + char buff2[] = "N|GetIfaceNames|12|128|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|GetIfaceNames|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcGetIfaceNames(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcRemoveIfaceTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcRemoveIface(nullptr, nullptr) < 0); + char buff[] = "N|RemoveIface|wlan0"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|RemoveIface|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcRemoveIface(mServer, mContext) < 0); + char buff1[] = "N|RemoveIface|wlan0|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|RemoveIface|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcRemoveIface(mServer, mContext) == 0); + char buff2[] = "N|RemoveIface|01234567890123456789012345678901|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|RemoveIface|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcRemoveIface(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetCapabilitiesTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetCapabilities(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcGetCapabilities(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetSupportedComboModesTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetSupportedComboModes(nullptr, nullptr) < 0); + char buff[] = "N|GetSupportedComboModes|asdgds|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|GetSupportedComboModes|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcGetSupportedComboModes(mServer, mContext) < 0); + char buff1[] = "N|GetSupportedComboModes|134|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|GetSupportedComboModes|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcGetSupportedComboModes(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcConfigComboModesTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcConfigComboModes(nullptr, nullptr) < 0); + char buff[] = "N|ConfigComboModes|asdgds|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|ConfigComboModes|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcConfigComboModes(mServer, mContext) < 0); + char buff1[] = "N|ConfigComboModes|134|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|ConfigComboModes|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcConfigComboModes(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetComboModesTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetComboModes(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcGetComboModes(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcRequestFirmwareDebugDumpTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcRequestFirmwareDebugDump(nullptr, nullptr) < 0); + char buff[] = "N|RequestFirmwareDebugDump|asdgds|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|RequestFirmwareDebugDump|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcRequestFirmwareDebugDump(mServer, mContext) < 0); + char buff1[] = "N|RequestFirmwareDebugDump|134|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|RequestFirmwareDebugDump|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcRequestFirmwareDebugDump(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcSetPowerModeTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcSetPowerMode(nullptr, nullptr) < 0); + char buff[] = "N|SetPowerMode|asdgds|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|SetPowerMode|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcSetPowerMode(mServer, mContext) < 0); + char buff1[] = "N|SetPowerMode|1|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|SetPowerMode|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcSetPowerMode(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcStartTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcStart(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcStart(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcStartSupplicantTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcStartSupplicant(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcStartSupplicant(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcStopSupplicantTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcStopSupplicant(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcStopSupplicant(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcStopTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcStop(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcStop(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcConnectSupplicantTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcConnectSupplicant(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcConnectSupplicant(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcDisconnectSupplicantTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcDisconnectSupplicant(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcDisconnectSupplicant(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcRequestToSupplicantTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcRequestToSupplicant(nullptr, nullptr) < 0); + char buff[] = "N|RequestToSupplicant|asdf|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|RequestToSupplicant|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcRequestToSupplicant(mServer, mContext) < 0); + char buff1[] = "N|RequestToSupplicant|4|8c677c8d5a|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|RequestToSupplicant|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcRequestToSupplicant(mServer, mContext) < 0); + char buff2[] = "N|RequestToSupplicant|4|8c677c8a|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|RequestToSupplicant|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcRequestToSupplicant(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcSetPowerSaveTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcSetPowerSave(nullptr, nullptr) < 0); + char buff[] = "N|SetPowerSave|fds|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|SetPowerSave|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcSetPowerSave(mServer, mContext) < 0); + char buff1[] = "N|SetPowerSave|1|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|SetPowerSave|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcSetPowerSave(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcWpaSetCountryCodeTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcWpaSetCountryCode(nullptr, nullptr) < 0); + char buff[] = "N|WpaSetCountryCode|CHINA|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|WpaSetCountryCode|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcWpaSetCountryCode(mServer, mContext) < 0); + char buff1[] = "N|WpaSetCountryCode|CN|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|WpaSetCountryCode|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcWpaSetCountryCode(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcWpaGetCountryCodeTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcWpaGetCountryCode(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcWpaGetCountryCode(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcStartScanTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcStartScan(nullptr, nullptr) < 0); + char buff[] = "N|StartScan|x|10|scan_ssid1|10|scan_ssid2|2|2427|2442|2|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|StartScan|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcStartScan(mServer, mContext) < 0); + char buff1[] = "N|StartScan|2|10|scan_ssid1|10|scan_ssid2"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|StartScan|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcStartScan(mServer, mContext) < 0); + char buff2[] = "N|StartScan|2|10|scan_ssid1|10|scan_ssid2|x|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|StartScan|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcStartScan(mServer, mContext) < 0); + char buff3[] = "N|StartScan|2|10|scan_ssid1|10|scan_ssid2|2|2427|x|x|"; + mContext->oneProcess = buff3; + mContext->nPos = strlen("N|StartScan|"); + mContext->nSize = strlen(buff3); + EXPECT_TRUE(RpcStartScan(mServer, mContext) < 0); + char buff4[] = "N|StartScan|2|10|scan_ssid1|10|scan_ssid2|2|2427|2442|x|"; + mContext->oneProcess = buff4; + mContext->nPos = strlen("N|StartScan|"); + mContext->nSize = strlen(buff4); + EXPECT_TRUE(RpcStartScan(mServer, mContext) < 0); + char buff5[] = "N|StartScan|2|10|scan_ssid1|10|scan_ssid2|2|2427|2442|2|"; + mContext->oneProcess = buff5; + mContext->nPos = strlen("N|StartScan|"); + mContext->nSize = strlen(buff5); + EXPECT_TRUE(RpcStartScan(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetScanInfosTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetScanInfos(nullptr, nullptr) < 0); + char buff[] = "N|GetScanInfos|x|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|GetScanInfos|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcGetScanInfos(mServer, mContext) < 0); + char buff1[] = "N|GetScanInfos|12|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|GetScanInfos|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcGetScanInfos(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetNetworkListTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetNetworkList(nullptr, nullptr) < 0); + char buff[] = "N|GetNetworkList|x|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|GetNetworkList|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcGetNetworkList(mServer, mContext) < 0); + char buff1[] = "N|GetNetworkList|12|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|GetNetworkList|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcGetNetworkList(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcStartPnoScanTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcStartPnoScan(nullptr, nullptr) < 0); + char buff[] = "N|StartPnoScan|1|x|1|2|3|asd|4|asdf|1|5|asdfg|2|5040|5080|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) < 0); + char buff1[] = "N|StartPnoScan|1|2|1|2|10|scan_ssid1|10|scan_ssid2"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) < 0); + char buff2[] = "N|StartPnoScan|1|2|1|2|10|scan_ssid1|10|scan_ssid2|x|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) < 0); + char buff3[] = "N|StartPnoScan|1|2|1|2|10|scan_ssid1|10|scan_ssid2|2|10|save_ssid1|10|save_ssid2"; + mContext->oneProcess = buff3; + mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nSize = strlen(buff3); + EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) < 0); + char buff4[] = "N|StartPnoScan|1|2|1|2|10|scan_ssid1|10|scan_ssid2|2|10|save_ssid1|10|save_ssid2|x|"; + mContext->oneProcess = buff4; + mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nSize = strlen(buff4); + EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) < 0); + char buff5[] = "N|StartPnoScan|1|2|1|2|10|scan_ssid1|10|scan_ssid2|2|10|save_ssid1|10|save_ssid2|2|5040|x|"; + mContext->oneProcess = buff5; + mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nSize = strlen(buff5); + EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) < 0); + char buff6[] = "N|StartPnoScan|1|2|1|2|10|scan_ssid1|10|scan_ssid2|2|10|save_ssid1|10|save_ssid2|2|5040|5080|"; + mContext->oneProcess = buff6; + mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nSize = strlen(buff6); + EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcStopPnoScanTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcStopPnoScan(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcStopPnoScan(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcConnectTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcConnect(nullptr, nullptr) < 0); + char buff[] = "N|Connect|x|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|Connect|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcConnect(mServer, mContext) < 0); + char buff1[] = "N|Connect|1|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|Connect|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcConnect(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcWpaAutoConnectTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcWpaAutoConnect(nullptr, nullptr) < 0); + char buff[] = "N|WpaAutoConnect|0ad|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|WpaAutoConnect|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcWpaAutoConnect(mServer, mContext) < 0); + char buff1[] = "N|WpaAutoConnect|1|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|WpaAutoConnect|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcWpaAutoConnect(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcReconnectTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcReconnect(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcReconnect(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcReassociateTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcReassociate(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcReassociate(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcDisconnectTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcDisconnect(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcDisconnect(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetStaCapabilitiesTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetStaCapabilities(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcGetStaCapabilities(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetDeviceMacAddressTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetDeviceMacAddress(nullptr, nullptr) < 0); + char buff[] = "N|GetDeviceMacAddress|x|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|GetDeviceMacAddress|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcGetDeviceMacAddress(mServer, mContext) < 0); + char buff1[] = "N|GetDeviceMacAddress|17|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|GetDeviceMacAddress|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcGetDeviceMacAddress(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetFrequenciesTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetFrequencies(nullptr, nullptr) < 0); + char buff[] = "N|GetFrequencies|1|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|GetFrequencies|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcGetFrequencies(mServer, mContext) < 0); + char buff1[] = "N|GetFrequencies|1|128|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|GetFrequencies|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcGetFrequencies(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcSetAssocMacAddrTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcSetAssocMacAddr(nullptr, nullptr) < 0); + char buff[] = "N|SetAssocMacAddr|x|7d9c039dfeba46|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|SetAssocMacAddr|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcSetAssocMacAddr(mServer, mContext) < 0); + char buff1[] = "N|SetAssocMacAddr|6|7d9c039dfeba46|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|SetAssocMacAddr|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcSetAssocMacAddr(mServer, mContext) < 0); + char buff2[] = "N|SetAssocMacAddr|7|7d9c039dfeba46|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|SetAssocMacAddr|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcSetAssocMacAddr(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcSetScanningMacAddressTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcSetScanningMacAddress(nullptr, nullptr) < 0); + char buff[] = "N|SetScanningMacAddress|x|7d9c039dfeba46|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|SetScanningMacAddress|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcSetScanningMacAddress(mServer, mContext) < 0); + char buff1[] = "N|SetScanningMacAddress|6|7d9c039dfeba46|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|SetScanningMacAddress|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcSetScanningMacAddress(mServer, mContext) < 0); + char buff2[] = "N|SetScanningMacAddress|7|7d9c039dfeba46|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|SetScanningMacAddress|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcSetScanningMacAddress(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcDeauthLastRoamingBssidTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcDeauthLastRoamingBssid(nullptr, nullptr) < 0); + char buff[] = "N|DeauthLastRoamingBssid|x|7d9c039dfeba46|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|DeauthLastRoamingBssid|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcDeauthLastRoamingBssid(mServer, mContext) < 0); + char buff1[] = "N|DeauthLastRoamingBssid|6|7d9c039dfeba46|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|DeauthLastRoamingBssid|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcDeauthLastRoamingBssid(mServer, mContext) < 0); + char buff2[] = "N|DeauthLastRoamingBssid|7|7d9c039dfeba46|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|DeauthLastRoamingBssid|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcDeauthLastRoamingBssid(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetSupportFeatureTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetSupportFeature(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcGetSupportFeature(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcRunCmdTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcRunCmd(nullptr, nullptr) < 0); + char buff[] = "N|RunCmd|wlan0"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|RunCmd|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcRunCmd(mServer, mContext) < 0); + char buff1[] = "N|RunCmd|wlan0|x|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|RunCmd|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcRunCmd(mServer, mContext) < 0); + char buff2[] = "N|RunCmd|wlan0|1|x|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|RunCmd|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcRunCmd(mServer, mContext) < 0); + char buff3[] = "N|RunCmd|wlan0|1|6|7d9c039dfeba46|"; + mContext->oneProcess = buff3; + mContext->nPos = strlen("N|RunCmd|"); + mContext->nSize = strlen(buff3); + EXPECT_TRUE(RpcRunCmd(mServer, mContext) < 0); + char buff4[] = "N|RunCmd|wlan0|1|7|7d9c039dfeba46|"; + mContext->oneProcess = buff4; + mContext->nPos = strlen("N|RunCmd|"); + mContext->nSize = strlen(buff4); + EXPECT_TRUE(RpcRunCmd(mServer, mContext) == 0); + char buff5[] = "N|RunCmd|0123456789012345678901|1|7|7d9c039dfeba46|"; + mContext->oneProcess = buff5; + mContext->nPos = strlen("N|RunCmd|"); + mContext->nSize = strlen(buff5); + EXPECT_TRUE(RpcRunCmd(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcSetWifiTxPowerTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcSetWifiTxPower(nullptr, nullptr) < 0); + char buff[] = "N|SetWifiTxPower|12"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|SetWifiTxPower|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcSetWifiTxPower(mServer, mContext) < 0); + char buff1[] = "N|SetWifiTxPower|12|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|SetWifiTxPower|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcSetWifiTxPower(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcRemoveNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcRemoveNetwork(nullptr, nullptr) < 0); + char buff[] = "N|RemoveNetwork|12"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|RemoveNetwork|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcRemoveNetwork(mServer, mContext) < 0); + char buff1[] = "N|RemoveNetwork|12|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|RemoveNetwork|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcRemoveNetwork(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcAddNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcAddNetwork(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcAddNetwork(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcEnableNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcEnableNetwork(nullptr, nullptr) < 0); + char buff[] = "N|EnableNetwork|12"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|EnableNetwork|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcEnableNetwork(mServer, mContext) < 0); + char buff1[] = "N|EnableNetwork|12|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|EnableNetwork|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcEnableNetwork(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcDisableNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcDisableNetwork(nullptr, nullptr) < 0); + char buff[] = "N|DisableNetwork|12"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|DisableNetwork|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcDisableNetwork(mServer, mContext) < 0); + char buff1[] = "N|DisableNetwork|12|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|DisableNetwork|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcDisableNetwork(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcSetNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcSetNetwork(nullptr, nullptr) < 0); + char buff[] = "N|SetNetwork|0|1"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|SetNetwork|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcSetNetwork(mServer, mContext) < 0); + char buff1[] = "N|SetNetwork|0|1|12|afsdgljsd"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|SetNetwork|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcSetNetwork(mServer, mContext) == 0); + char buff2[] = "N|SetNetwork|0|1|12|afsdgljsd|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|SetNetwork|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcSetNetwork(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcWpaGetNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcWpaGetNetwork(nullptr, nullptr) < 0); + char buff[] = "N|WpaGetNetwork|2|ssid"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|WpaGetNetwork|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcWpaGetNetwork(mServer, mContext) < 0); + char buff1[] = "N|WpaGetNetwork|2|ssid|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|WpaGetNetwork|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcWpaGetNetwork(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcSaveNetworkConfigTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcSaveNetworkConfig(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcSaveNetworkConfig(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcStartWpsPbcModeTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcStartWpsPbcMode(nullptr, nullptr) < 0); + char buff[] = "N|StartWpsPbcMode|1|2|adsgfkdsj"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|StartWpsPbcMode|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcStartWpsPbcMode(mServer, mContext) < 0); + char buff1[] = "N|StartWpsPbcMode|1|2|adsgfkdsj|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|StartWpsPbcMode|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcStartWpsPbcMode(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcStartWpsPinModeTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcStartWpsPinMode(nullptr, nullptr) < 0); + char buff[] = "N|StartWpsPinMode|1|2|adsgfkdsj"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|StartWpsPinMode|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcStartWpsPinMode(mServer, mContext) < 0); + char buff1[] = "N|StartWpsPinMode|1|2|adsgfkdsj|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|StartWpsPinMode|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcStartWpsPinMode(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcStopWpsTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcStopWps(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcStopWps(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcWpaBlocklistClearTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcWpaBlocklistClear(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcWpaBlocklistClear(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetRoamingCapabilitiesTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetRoamingCapabilities(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcGetRoamingCapabilities(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcSetRoamConfigTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcSetRoamConfig(nullptr, nullptr) < 0); + char buff[] = "N|SetRoamConfig|x|fdsagdsa|safdgfds|1|vcxzcbvx|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|SetRoamConfig|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcSetRoamConfig(mServer, mContext) < 0); + char buff1[] = "N|SetRoamConfig|2|fdsagdsa|safdgfds"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|SetRoamConfig|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcSetRoamConfig(mServer, mContext) < 0); + char buff2[] = "N|SetRoamConfig|2|fdsagdsa|safdgfds|x|vcxzcbvx|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|SetRoamConfig|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcSetRoamConfig(mServer, mContext) < 0); + char buff3[] = "N|SetRoamConfig|2|fdsagdsa|safdgfds|1|vcxzcbvx"; + mContext->oneProcess = buff3; + mContext->nPos = strlen("N|SetRoamConfig|"); + mContext->nSize = strlen(buff3); + EXPECT_TRUE(RpcSetRoamConfig(mServer, mContext) < 0); + char buff4[] = "N|SetRoamConfig|2|fdsagdsa|safdgfds|1|vcxzcbvx|"; + mContext->oneProcess = buff4; + mContext->nPos = strlen("N|SetRoamConfig|"); + mContext->nSize = strlen(buff4); + EXPECT_TRUE(RpcSetRoamConfig(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetConnectSignalInfoTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetConnectSignalInfo(nullptr, nullptr) < 0); + char buff[] = "N|GetConnectSignalInfo|ssid"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|GetConnectSignalInfo|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcGetConnectSignalInfo(mServer, mContext) < 0); + char buff1[] = "N|GetConnectSignalInfo|00:00:00:00:00:00|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|GetConnectSignalInfo|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcGetConnectSignalInfo(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcStartSoftApTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcStartSoftAp(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcStartSoftAp(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcStopSoftApTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcStopSoftAp(nullptr, nullptr) < 0); + EXPECT_TRUE(RpcStopSoftAp(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcSetHostapdConfigTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcSetHostapdConfig(nullptr, nullptr) < 0); + char buff[] = "N|SetHostapdConfig|tests|5|adc123456|9|1|0|6|20|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|SetHostapdConfig|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcSetHostapdConfig(mServer, mContext) == 0); + char buff1[] = "N|SetHostapdConfig|tests|5|adc123456|9|1|0|6|20"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|SetHostapdConfig|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcSetHostapdConfig(mServer, mContext) < 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetStaInfosTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetStaInfos(nullptr, nullptr) < 0); + char buff[] = "N|GetStaInfos|128"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|GetStaInfos|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcGetStaInfos(mServer, mContext) < 0); + char buff1[] = "N|GetStaInfos|128|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|GetStaInfos|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcGetStaInfos(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcSetCountryCodeTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcSetCountryCode(nullptr, nullptr) < 0); + char buff[] = "N|SetCountryCode|CN"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|SetCountryCode|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcSetCountryCode(mServer, mContext) < 0); + char buff1[] = "N|SetCountryCode|CN|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|SetCountryCode|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcSetCountryCode(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcSetMacFilterTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcSetMacFilter(nullptr, nullptr) < 0); + char buff[] = "N|SetMacFilter|x|345697dbf921d3|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|SetMacFilter|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcSetMacFilter(mServer, mContext) < 0); + char buff1[] = "N|SetMacFilter|6|345697dbf921d3|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|SetMacFilter|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcSetMacFilter(mServer, mContext) < 0); + char buff2[] = "N|SetMacFilter|7|345697dbf921d3|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|SetMacFilter|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcSetMacFilter(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcDelMacFilterTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcDelMacFilter(nullptr, nullptr) < 0); + char buff[] = "N|DelMacFilter|x|345697dbf921d3|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|DelMacFilter|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcDelMacFilter(mServer, mContext) < 0); + char buff1[] = "N|DelMacFilter|6|345697dbf921d3|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|DelMacFilter|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcDelMacFilter(mServer, mContext) < 0); + char buff2[] = "N|DelMacFilter|7|345697dbf921d3|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|DelMacFilter|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcDelMacFilter(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcDisassociateStaTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcDisassociateSta(nullptr, nullptr) < 0); + char buff[] = "N|DisassociateSta|x|345697dbf921d3|"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|DisassociateSta|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcDisassociateSta(mServer, mContext) < 0); + char buff1[] = "N|DisassociateSta|6|345697dbf921d3|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|DisassociateSta|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcDisassociateSta(mServer, mContext) < 0); + char buff2[] = "N|DisassociateSta|7|345697dbf921d3|"; + mContext->oneProcess = buff2; + mContext->nPos = strlen("N|DisassociateSta|"); + mContext->nSize = strlen(buff2); + EXPECT_TRUE(RpcDisassociateSta(mServer, mContext) == 0); +} + +HWTEST_F(WifiHalCRpcServerTest, RpcGetValidFrequenciesForBandTest, TestSize.Level1) +{ + EXPECT_TRUE(RpcGetValidFrequenciesForBand(nullptr, nullptr) < 0); + char buff[] = "N|GetValidFrequenciesForBand|1|128"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N|GetValidFrequenciesForBand|"); + mContext->nSize = strlen(buff); + EXPECT_TRUE(RpcGetValidFrequenciesForBand(mServer, mContext) < 0); + char buff1[] = "N|GetValidFrequenciesForBand|1|128|"; + mContext->oneProcess = buff1; + mContext->nPos = strlen("N|GetValidFrequenciesForBand|"); + mContext->nSize = strlen(buff1); + EXPECT_TRUE(RpcGetValidFrequenciesForBand(mServer, mContext) == 0); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.h b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.h new file mode 100644 index 000000000..afc0c295a --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.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_WIFI_HAL_CRPC_SERVER_TEST_H +#define OHOS_WIFI_HAL_CRPC_SERVER_TEST_H + +#include +#include "server.h" + +namespace OHOS { +namespace Wifi { +class WifiHalCRpcServerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp(); + virtual void TearDown(); + +public: + static RpcServer *mServer; + static Context *mContext; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.cpp b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.cpp new file mode 100644 index 000000000..a0d7a791c --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.cpp @@ -0,0 +1,187 @@ +/* + * 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 "wifi_hal_hostapd_test.h" +#include "securec.h" +#include "wifi_log.h" +#include "mock_wpa_ctrl.h" +#include "wifi_hal_crpc_server.h" +#include "wifi_hal_common_func.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +static std::string g_rpcSockPath = "./unix_sock_test.sock"; +WifiHostapdHalDevice *WifiHalHostapdTest::mInterface = nullptr; +RpcServer *WifiHalHostapdTest::mServer = nullptr; + +void WifiHalHostapdTest::SetUpTestCase() +{ + if (access(g_rpcSockPath.c_str(), 0) == 0) { + unlink(g_rpcSockPath.c_str()); + } + mServer = CreateRpcServer(g_rpcSockPath.c_str()); + if (mServer == nullptr) { + printf("Init rpc server failed!"); + exit(-1); + } + InitCallbackMsg(); + SetRpcServerInited(mServer); + MockInitApSupportedCmd(); + mInterface = GetWifiHostapdDev(); +} + +void WifiHalHostapdTest::TearDownTestCase() +{ + sleep(1); + ReleaseHostapdDev(); + if (mServer != nullptr) { + ReleaseRpcServer(mServer); + mServer = nullptr; + } + SetRpcServerInited(NULL); + ReleaseCallbackMsg(); +} + +HWTEST_F(WifiHalHostapdTest, EnableApTest, TestSize.Level1) +{ + MockEraseSupportedCmd("ENABLE"); + int ret = mInterface->enableAp(); + EXPECT_TRUE(ret != 0); + MockSetWpaExpectCmdResponse("ENABLE", "OK"); + ret = mInterface->enableAp(); + EXPECT_TRUE(ret == 0); + MockWpaCallback(mInterface->ctrlConn, "<3>AP-ENABLED \n"); +} + +HWTEST_F(WifiHalHostapdTest, SetApInfoTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->setApInfo(nullptr) < 0); + HostapdConfig conf; + ASSERT_TRUE(memset_s(&conf, sizeof(conf), 0, sizeof(conf)) == EOK); + conf.securityType = WPA_PSK; + EXPECT_TRUE(mInterface->setApInfo(&conf) < 0); + StrSafeCopy(conf.preSharedKey, sizeof(conf.preSharedKey), "1234567"); + EXPECT_TRUE(mInterface->setApInfo(&conf) < 0); + StrSafeCopy(conf.preSharedKey, sizeof(conf.preSharedKey), "12345678"); + conf.preSharedKeyLen = strlen(conf.preSharedKey); + EXPECT_TRUE(mInterface->setApInfo(&conf) == 0); + conf.securityType = WPA2_PSK; + EXPECT_TRUE(mInterface->setApInfo(&conf) == 0); + conf.securityType = NONE; + EXPECT_TRUE(mInterface->setApInfo(&conf) == 0); + conf.securityType = IEEE8021X; + EXPECT_TRUE(mInterface->setApInfo(&conf) < 0); + conf.securityType = NONE; + conf.band = AP_2GHZ_BAND; + EXPECT_TRUE(mInterface->setApInfo(&conf) == 0); + conf.band = AP_5GHZ_BAND; + EXPECT_TRUE(mInterface->setApInfo(&conf) == 0); + conf.band = -1; + EXPECT_TRUE(mInterface->setApInfo(&conf) < 0); + conf.band = AP_DFS_BAND; + EXPECT_TRUE(mInterface->setApInfo(&conf) < 0); +} + +HWTEST_F(WifiHalHostapdTest, DisableApTest, TestSize.Level1) +{ + MockEraseSupportedCmd("DISABLE"); + int ret = mInterface->disableAp(); + EXPECT_TRUE(ret != 0); + MockSetWpaExpectCmdResponse("DISABLE", "OK"); + ret = mInterface->disableAp(); + EXPECT_TRUE(ret == 0); + MockWpaCallback(mInterface->ctrlConn, "<3>AP-DISABLED \n"); +} + +HWTEST_F(WifiHalHostapdTest, AddBlockListTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->addBlocklist(nullptr) < 0); + EXPECT_TRUE(mInterface->addBlocklist("00:00:00:00:00:00") == 0); + MockSetWpaExpectCmdResponse("DENY_ACL", "UNKNOWN COMMAND"); + EXPECT_TRUE(mInterface->addBlocklist("00:00:00:00:00:00") == 0); + MockSetWpaExpectCmdResponse("DENY_ACL", "OK"); +} + +HWTEST_F(WifiHalHostapdTest, DelBlockListTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->delBlocklist(nullptr) < 0); + EXPECT_TRUE(mInterface->delBlocklist("00:00:00:00:00:00") == 0); + MockSetWpaExpectCmdResponse("DENY_ACL", "UNKNOWN COMMAND"); + EXPECT_TRUE(mInterface->delBlocklist("00:00:00:00:00:00") == 0); + MockSetWpaExpectCmdResponse("DENY_ACL", "OK"); +} + +HWTEST_F(WifiHalHostapdTest, GetApStatusTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->status(nullptr) < 0); + StatusInfo info; + ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); + EXPECT_TRUE(mInterface->status(&info) == 0); + char buf[BUFSIZE_REQUEST] = "test1=adsgdjks\nteset2=gflsdfis\ntest3=" + "gfdklse\nstate=disable\ngfdsd=gdhjs\n"; + MockSetWpaExpectCmdResponse("STATUS", buf); + EXPECT_TRUE(mInterface->status(&info) == 0); + EXPECT_TRUE(strcmp(info.state, "disable") == 0); +} + +HWTEST_F(WifiHalHostapdTest, HostapdCliCmdListStaTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->showConnectedDevList(nullptr, 0) < 0); + char buff[256] = {0}; + int size = 256; + MockEraseSupportedCmd("STA-FIRST"); + EXPECT_TRUE(mInterface->showConnectedDevList(buff, size) < 0); + MockSetWpaExpectCmdResponse("STA-FIRST", "00:00:00:00:00:00"); + MockSetWpaExpectCmdResponse("STA-NEXT", "FAIL"); + EXPECT_TRUE(mInterface->showConnectedDevList(buff, size) == 0); + EXPECT_TRUE(strcmp(buff, ",00:00:00:00:00:00") == 0); +} + +HWTEST_F(WifiHalHostapdTest, ReloadApConfigInfoTest, TestSize.Level1) +{ + MockEraseSupportedCmd("RELOAD"); + int ret = mInterface->reloadApConfigInfo(); + EXPECT_TRUE(ret != 0); + MockSetWpaExpectCmdResponse("RELOAD", "OK"); + ret = mInterface->reloadApConfigInfo(); + EXPECT_TRUE(ret == 0); +} + +HWTEST_F(WifiHalHostapdTest, DisConnectedDevTest, TestSize.Level1) +{ + MockWpaCallback(mInterface->ctrlConn, "<3>AP-STA-CONNECTED 00:00:00:00:00:00\n"); + EXPECT_TRUE(mInterface->disConnectedDev(nullptr) < 0); + MockEraseSupportedCmd("DISASSOCIATE"); + int ret = mInterface->disConnectedDev("00:00:00:00:00:00"); + EXPECT_TRUE(ret != 0); + MockSetWpaExpectCmdResponse("DISASSOCIATE", "OK"); + ret = mInterface->disConnectedDev("00:00:00:00:00:00"); + EXPECT_TRUE(ret == 0); + MockWpaCallback(mInterface->ctrlConn, "<3>AP-STA-DISCONNECTED 00:00:00:00:00:00\n"); +} + +HWTEST_F(WifiHalHostapdTest, SetCountryCodeTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->setCountryCode(nullptr) < 0); + MockEraseSupportedCmd("SET"); + int ret = mInterface->setCountryCode("CN"); + EXPECT_TRUE(ret != 0); + MockSetWpaExpectCmdResponse("SET", "OK"); + ret = mInterface->setCountryCode("CN"); + EXPECT_TRUE(ret == 0); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.h b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.h new file mode 100644 index 000000000..17958f0e2 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.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_WIFI_HAL_HOSTAPD_TEST_H +#define OHOS_WIFI_HAL_HOSTAPD_TEST_H + +#include +#include "server.h" +#include "wifi_hostapd_hal.h" + +namespace OHOS { +namespace Wifi { +class WifiHalHostapdTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() + {} + virtual void TearDown() + {} + + static WifiHostapdHalDevice *mInterface; + static RpcServer *mServer; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.cpp b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.cpp new file mode 100644 index 000000000..09bf66611 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.cpp @@ -0,0 +1,306 @@ +/* + * 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 "wifi_hal_p2p_interface_test.h" +#include "securec.h" +#include "wifi_log.h" +#include "wifi_hal_p2p_interface.h" +#include "wifi_p2p_hal.h" +#include "mock_wpa_ctrl.h" +#include "wifi_hal_common_func.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +static char P2pTestInterface[32] = "wlan0"; + +void WifiHalP2pInterfaceTest::SetUpTestCase() +{ + MockInitGlobalCmd(); + MockInitP2pSupportedCmd(); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pStartTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pStart() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetRandomMacTest, TestSize.Level1) +{ + MockSetWpaExpectCmdResponse("DRIVER_FLAGS", "DEDICATED_P2P_DEVICE\n"); + EXPECT_TRUE(P2pSetRandomMac(0) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetDeviceNameTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSetDeviceName(NULL) == WIFI_HAL_FAILED); + EXPECT_TRUE(P2pSetDeviceName("p2p-device") == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetSsidPostfixNameTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSetSsidPostfixName(NULL) == WIFI_HAL_FAILED); + EXPECT_TRUE(P2pSetSsidPostfixName("p2p-postfix") == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetWpsDeviceTypeTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSetWpsDeviceType(NULL) == WIFI_HAL_FAILED); + EXPECT_TRUE(P2pSetWpsDeviceType("6-0050F204-1") == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetWpsConfigMethodsTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSetWpsConfigMethods(NULL) == WIFI_HAL_FAILED); + EXPECT_TRUE(P2pSetWpsConfigMethods("label display push_button keypad") == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pGetDeviceAddressTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pGetDeviceAddress(nullptr, 0) == WIFI_HAL_FAILED); + MockSetWpaExpectCmdResponse("STATUS", "p2p_device_address=00:00:00:00:00:00\n"); + char deviceAddress[128] = {0}; + EXPECT_TRUE(P2pGetDeviceAddress(deviceAddress, 128) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pFlushTest, TestSize.Level1) +{ + MockEraseSupportedCmd("P2P_FLUSH"); + EXPECT_TRUE(P2pFlush() == WIFI_HAL_FAILED); + MockSetWpaExpectCmdResponse("P2P_FLUSH", "OK"); + EXPECT_TRUE(P2pFlush() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pFlushServiceTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pFlushService() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSaveConfigTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSaveConfig() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetupWpsPbcTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSetupWpsPbc(nullptr, nullptr) == WIFI_HAL_FAILED); + char bssid[32] = {0}; + EXPECT_TRUE(P2pSetupWpsPbc(P2pTestInterface, bssid) == WIFI_HAL_SUCCESS); + StrSafeCopy(bssid, sizeof(bssid), "dc:f0:9e:9b:06:c5"); + EXPECT_TRUE(P2pSetupWpsPbc(P2pTestInterface, bssid) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetupWpsPinTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSetupWpsPin(nullptr, nullptr, nullptr, nullptr, 0) == WIFI_HAL_FAILED); + char bssid[32] = {0}; + char pin[32] = {0}; + char result[32] = {0}; + EXPECT_TRUE(P2pSetupWpsPin(P2pTestInterface, bssid, pin, result, sizeof(result)) == WIFI_HAL_SUCCESS); + StrSafeCopy(pin, sizeof(pin), "12345678"); + EXPECT_TRUE(P2pSetupWpsPin(P2pTestInterface, bssid, pin, result, sizeof(result)) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pRemoveNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pRemoveNetwork(0) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pListNetworksTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pListNetworks(nullptr) == WIFI_HAL_FAILED); + char replyBuff[] = "network id / ssid / bssid / flags\n" + "0\tDIRECT-OHOS\t00:00:00:00:00:00\t[DISABLED][P2P-PERSISTENT]\n"; + MockSetWpaExpectCmdResponse("LIST_NETWORKS", replyBuff); + HidlP2pNetworkList info; + ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); + EXPECT_TRUE(P2pListNetworks(&info) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2PSetGroupIdleTest, TestSize.Level1) +{ + int time = 10; + EXPECT_TRUE(P2pSetGroupMaxIdle(NULL, time) == WIFI_HAL_FAILED); + EXPECT_TRUE(P2pSetGroupMaxIdle(P2pTestInterface, time) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetPowerSaveTest, TestSize.Level1) +{ + int enable = 0; + EXPECT_TRUE(P2pSetPowerSave(NULL, enable) == WIFI_HAL_FAILED); + EXPECT_TRUE(P2pSetPowerSave(P2pTestInterface, enable) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetWfdEnableTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSetWfdEnable(0) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetWfdDeviceConfigTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSetWfdDeviceConfig(nullptr) == WIFI_HAL_FAILED); + EXPECT_TRUE(P2pSetWfdDeviceConfig("input what?") == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pStartFindTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pStartFind(0) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pStopP2pFindTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pStopFind() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetExtListenTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSetExtListen(1, 500, 500) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetListenChannelTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSetListenChannel(1, 500) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pConnectTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pConnect(NULL) == WIFI_HAL_FAILED); + HidlP2pConnectInfo info; + ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); + EXPECT_TRUE(P2pConnect(&info) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pCancelConnectTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pCancelConnect() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pProvisionDiscoveryTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pProvisionDiscovery(nullptr, 0) == WIFI_HAL_FAILED); + EXPECT_TRUE(P2pProvisionDiscovery("00:00:00:00:00:00", (int)HAL_WPS_METHOD_PBC) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pAddGroupTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pAddGroup(1, -1, 0) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pRemoveGroupTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pRemoveGroup(nullptr) == WIFI_HAL_FAILED); + const char *name = "p2p-wlan0-0"; + EXPECT_TRUE(P2pRemoveGroup(name) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pInviteTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pInvite(0, nullptr, nullptr, nullptr) == WIFI_HAL_FAILED); + EXPECT_TRUE(P2pInvite(1, "00:00:00:00:00:00", "00:00:00:00:00:00", "p2p-dev-wlan0") == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pReinvokeTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pReinvoke(0, nullptr) == WIFI_HAL_FAILED); + EXPECT_TRUE(P2pReinvoke(0, "00:00:00:00:00:00") == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pGetGroupCapabilityTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pGetGroupCapability(nullptr, nullptr) == WIFI_HAL_FAILED); + int capability = 0; + EXPECT_TRUE(P2pGetGroupCapability("00:00:00:00:00:00", &capability) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pAddServiceTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pAddService(nullptr) == WIFI_HAL_FAILED); + HidlP2pServiceInfo info; + ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); + EXPECT_TRUE(P2pAddService(&info) == WIFI_HAL_INVALID_PARAM); + info.mode = 0; + StrSafeCopy(info.name, sizeof(info.name), "test_name"); + EXPECT_TRUE(P2pAddService(&info) == WIFI_HAL_SUCCESS); + info.mode = 1; + StrSafeCopy(info.query, sizeof(info.query), "query"); + StrSafeCopy(info.resp, sizeof(info.resp), "response"); + EXPECT_TRUE(P2pAddService(&info) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pRemoveServiceTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pRemoveService(nullptr) == WIFI_HAL_FAILED); + HidlP2pServiceInfo info; + ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); + EXPECT_TRUE(P2pRemoveService(&info) == WIFI_HAL_INVALID_PARAM); + info.mode = 0; + StrSafeCopy(info.name, sizeof(info.name), "test_name"); + EXPECT_TRUE(P2pRemoveService(&info) == WIFI_HAL_SUCCESS); + info.mode = 1; + StrSafeCopy(info.query, sizeof(info.query), "query"); + StrSafeCopy(info.resp, sizeof(info.resp), "response"); + EXPECT_TRUE(P2pRemoveService(&info) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pReqServiceDiscoveryTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pReqServiceDiscovery(nullptr, nullptr, nullptr, 0) == WIFI_HAL_FAILED); + char disc[1024] = {0}; + EXPECT_TRUE(P2pReqServiceDiscovery("00:00:00:00:00:00", "HELLO,MESSAGE", disc, 1024) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pCancelServiceDiscoveryTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pCancelServiceDiscovery(nullptr) == WIFI_HAL_FAILED); + EXPECT_TRUE(P2pCancelServiceDiscovery("string id") == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetMiracastTypeTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSetMiracastType(0) == WIFI_HAL_NOT_SUPPORT); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pRespServerDiscoveryTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pRespServerDiscovery(nullptr) == WIFI_HAL_FAILED); + HidlP2pServDiscReqInfo info; + ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); + info.tlvs = (char *)calloc(32, sizeof(char)); + EXPECT_TRUE(P2pRespServerDiscovery(&info) == WIFI_HAL_SUCCESS); + free(info.tlvs); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetServDiscExternalTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSetServDiscExternal(0) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pSetPersistentReconnectTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pSetPersistentReconnect(0) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pStopTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pStop() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalP2pInterfaceTest, P2pForceStopTest, TestSize.Level1) +{ + EXPECT_TRUE(P2pForceStop() == WIFI_HAL_SUCCESS); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.h b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.h new file mode 100644 index 000000000..f8ad41df4 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.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_WIFI_HAL_P2P_INTERFACE_TEST_H +#define OHOS_WIFI_HAL_P2P_INTERFACE_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiHalP2pInterfaceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + {} +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.cpp b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.cpp new file mode 100644 index 000000000..872fb002b --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.cpp @@ -0,0 +1,214 @@ +/* + * 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 "wifi_hal_sta_interface_test.h" +#include "securec.h" +#include "wifi_log.h" +#include "wifi_hal_sta_interface.h" +#include "wifi_supplicant_hal.h" +#include "mock_wpa_ctrl.h" +#include "wifi_hal_common_func.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +void WifiHalStaInterfaceTest::SetUpTestCase() +{ + MockInitGlobalCmd(); + MockInitStaSupportedCmd(); + Start(); +} + +void WifiHalStaInterfaceTest::TearDownTestCase() +{ + Stop(); +} + +HWTEST_F(WifiHalStaInterfaceTest, StartTest, TestSize.Level1) +{ + EXPECT_TRUE(Start() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, StartSupplicantTest, TestSize.Level1) +{ + EXPECT_TRUE(StartSupplicant() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, ConnectSupplicantTest, TestSize.Level1) +{ + EXPECT_TRUE(ConnectSupplicant() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, SetPowerSaveTest, TestSize.Level1) +{ + bool enable = false; + EXPECT_TRUE(SetPowerSave(enable) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, RemoveNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(RemoveNetwork(0) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, AddNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(AddNetwork(nullptr) == WIFI_HAL_FAILED); + int networkId = 0; + EXPECT_TRUE(AddNetwork(&networkId) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, EnableNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(EnableNetwork(0) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, DisableNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(DisableNetwork(0) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, SetNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(SetNetwork(0, nullptr, 0) == WIFI_HAL_FAILED); + HidlSetNetworkConfig conf; + conf.cfgParam = DEVICE_CONFIG_SSID; + StrSafeCopy(conf.cfgValue, sizeof(conf.cfgValue), "network_ssid"); + EXPECT_TRUE(SetNetwork(0, &conf, 1) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, SaveNetworkConfigTest, TestSize.Level1) +{ + EXPECT_TRUE(SaveNetworkConfig() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, ConnectTest, TestSize.Level1) +{ + EXPECT_TRUE(Connect(0) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, ReconnectTest, TestSize.Level1) +{ + EXPECT_TRUE(Reconnect() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, ReassociateTest, TestSize.Level1) +{ + EXPECT_TRUE(Reassociate() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, DisconnectTest, TestSize.Level1) +{ + EXPECT_TRUE(Disconnect() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, StartWpsPbcModeTest, TestSize.Level1) +{ + EXPECT_TRUE(StartWpsPbcMode(nullptr) == WIFI_HAL_SUCCESS); + WifiWpsParam conf; + ASSERT_TRUE(memset_s(&conf, sizeof(conf), 0, sizeof(conf)) == EOK); + conf.anyFlag = 1; + conf.multiAp = 0; + EXPECT_TRUE(StartWpsPbcMode(&conf) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, StartWpsPinModeTest, TestSize.Level1) +{ + EXPECT_TRUE(StartWpsPinMode(nullptr, nullptr) == WIFI_HAL_FAILED); + WifiWpsParam conf; + ASSERT_TRUE(memset_s(&conf, sizeof(conf), 0, sizeof(conf)) == EOK); + conf.anyFlag = 1; + conf.multiAp = 0; + int pincode = 0; + EXPECT_TRUE(StartWpsPinMode(&conf, &pincode) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, StopWpsTest, TestSize.Level1) +{ + EXPECT_TRUE(StopWps() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, WpaSetCountryCodeTest, TestSize.Level1) +{ + EXPECT_TRUE(WpaSetCountryCode(nullptr) == WIFI_HAL_FAILED); + EXPECT_TRUE(WpaSetCountryCode("CN") == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, WpaGetCountryCodeTest, TestSize.Level1) +{ + EXPECT_TRUE(WpaGetCountryCode(nullptr, 0) == WIFI_HAL_FAILED); + char countryCode[3] = {0}; + int size = 3; + EXPECT_TRUE(WpaGetCountryCode(countryCode, size) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, WpaGetNetWorkTest, TestSize.Level1) +{ + EXPECT_TRUE(WpaGetNetWork(nullptr) == WIFI_HAL_FAILED); + HidlGetNetworkConfig conf; + ASSERT_TRUE(memset_s(&conf, sizeof(conf), 0, sizeof(conf)) == EOK); + conf.networkId = 0; + StrSafeCopy(conf.param, sizeof(conf.param), "ssid"); + EXPECT_TRUE(WpaGetNetWork(&conf) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, WpaAutoConnectTest, TestSize.Level1) +{ + EXPECT_TRUE(WpaAutoConnect(0) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, GetNetworkListTest, TestSize.Level1) +{ + EXPECT_TRUE(GetNetworkList(nullptr, nullptr) == WIFI_HAL_FAILED); + HidlNetworkInfo infos[20]; + ASSERT_TRUE(memset_s(infos, sizeof(infos), 0, sizeof(infos)) == EOK); + int maxSize = 20; + EXPECT_TRUE(GetNetworkList(infos, &maxSize) == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, DisconnectSupplicantTest, TestSize.Level1) +{ + EXPECT_TRUE(DisconnectSupplicant() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, StopSupplicantTest, TestSize.Level1) +{ + EXPECT_TRUE(StopSupplicant() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, WpaBlocklistClearTest, TestSize.Level1) +{ + EXPECT_TRUE(WpaBlocklistClear() == WIFI_HAL_FAILED); +} + +HWTEST_F(WifiHalStaInterfaceTest, GetConnectSignalInfoTest, TestSize.Level1) +{ + EXPECT_TRUE(GetConnectSignalInfo(nullptr, nullptr) == WIFI_HAL_FAILED); + HidlWpaSignalInfo info; + ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); + WifiErrorNo ret = GetConnectSignalInfo("00:00:00:00:00:00", &info); + EXPECT_TRUE(ret != WIFI_HAL_SUPPLICANT_NOT_INIT && ret != WIFI_HAL_GET_WIFI_COND_FAILED); +} + +HWTEST_F(WifiHalStaInterfaceTest, StopTest, TestSize.Level1) +{ + EXPECT_TRUE(Stop() == WIFI_HAL_SUCCESS); +} + +HWTEST_F(WifiHalStaInterfaceTest, ForceStopTest, TestSize.Level1) +{ + EXPECT_TRUE(ForceStop() == WIFI_HAL_SUCCESS); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.h b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.h new file mode 100644 index 000000000..f64df43d3 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.h @@ -0,0 +1,33 @@ +/* + * 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_WIFI_HAL_STA_INTERFACE_TEST_H +#define OHOS_WIFI_HAL_STA_INTERFACE_TEST_H + +#include + +namespace OHOS { +namespace Wifi { +class WifiHalStaInterfaceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() + {} + virtual void TearDown() + {} +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_test.cpp b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_test.cpp new file mode 100644 index 000000000..5d68c0237 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_test.cpp @@ -0,0 +1,22 @@ +/* + * 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 + +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_vendor.conf b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_vendor.conf new file mode 100644 index 000000000..f87d332be --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_vendor.conf @@ -0,0 +1,13 @@ +# 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. +libWifiHalVendorTest.so \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_vendor_interface_test.c b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_vendor_interface_test.c new file mode 100644 index 000000000..4ade79854 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_vendor_interface_test.c @@ -0,0 +1,52 @@ +/* + * 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 +#include +#include "wifi_log.h" +#include "wifi_hal_vendor_interface.h" +#include "securec.h" + +#undef LOG_TAG +#define LOG_TAG "WifiHalVendorInterfaceTest" + +const int FEATURE_VALUE = 2; + +HalVendorError WifiInitializeTest(void) +{ + return HAL_VENDOR_SUCCESS; +} + +HalVendorError WifiCleanUpTest(void) +{ + return HAL_VENDOR_SUCCESS; +} + +HalVendorError WifiGetSupportedFeatureTest(long *feature) +{ + *feature = FEATURE_VALUE; + return HAL_VENDOR_SUCCESS; +} + +HalVendorError InitHalVendorFunc(WifiHalVendorFunc *func) +{ + func->wifiInitialize = WifiInitializeTest; + func->wifiCleanUp = WifiCleanUpTest; + func->wifiGetSupportedFeature = WifiGetSupportedFeatureTest; + return HAL_VENDOR_SUCCESS; +} diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.cpp b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.cpp new file mode 100644 index 000000000..7d19b97b7 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.cpp @@ -0,0 +1,720 @@ +/* + * 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 "wifi_hal_wpa_p2p_test.h" +#include "securec.h" +#include "mock_wpa_ctrl.h" +#include "wifi_hal_crpc_server.h" +#include "wifi_hal_common_func.h" +#include "wifi_log.h" +#undef LOG_TAG +#define LOG_TAG "WifiHalWpaP2pTest" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +const std::string g_rpcSockPath = "./unix_sock_test.sock"; +WifiWpaInterface *WifiHalWpaP2pTest::mGlobalInterface = nullptr; +WifiWpaP2pInterface *WifiHalWpaP2pTest::mInterface = nullptr; +RpcServer *WifiHalWpaP2pTest::mServer = nullptr; + +void WifiHalWpaP2pTest::SetUpTestCase() +{ + if (access(g_rpcSockPath.c_str(), 0) == 0) { + unlink(g_rpcSockPath.c_str()); + } + mServer = CreateRpcServer(g_rpcSockPath.c_str()); + if (mServer == nullptr) { + printf("Init rpc server failed!"); + exit(-1); + } + InitCallbackMsg(); + SetRpcServerInited(mServer); + MockInitGlobalCmd(); + MockInitP2pSupportedCmd(); + mGlobalInterface = GetWifiWapGlobalInterface(); + mGlobalInterface->wpaCliConnect(mGlobalInterface); + mInterface = GetWifiWapP2pInterface(); +} + +void WifiHalWpaP2pTest::TearDownTestCase() +{ + sleep(1); + RelesaeWpaP2pInterface(); + if (mServer != nullptr) { + ReleaseRpcServer(mServer); + mServer = nullptr; + } + SetRpcServerInited(NULL); + ReleaseCallbackMsg(); +} + +HWTEST_F(WifiHalWpaP2pTest, GetWifiWpaP2pInterfaceTest, TestSize.Level1) +{ + WifiWpaP2pInterface *p = GetWifiWapP2pInterface(); + EXPECT_TRUE(p == mInterface); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdSetWpsNameTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWpsName(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("SET"); + char name[] = "p2p_device"; + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWpsName(mInterface, name) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWpsName(mInterface, name) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWpsName(mInterface, name) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdSetWpsDeviceTypeTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWpsName(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("SET"); + char type[] = "p2p_device_type"; + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWpsDeviceType(mInterface, type) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWpsDeviceType(mInterface, type) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWpsDeviceType(mInterface, type) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdSetWpsConfigMethodsTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWpsConfigMethods(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("SET"); + char methods[] = "p2p_config_method"; + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWpsConfigMethods(mInterface, methods) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWpsConfigMethods(mInterface, methods) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWpsConfigMethods(mInterface, methods) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdSetSsidPostfixNameTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetSsidPostfixName(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("P2P_SET"); + char postfix[] = "p2p_postfix_name"; + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetSsidPostfixName(mInterface, postfix) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SET", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetSsidPostfixName(mInterface, postfix) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SET", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetSsidPostfixName(mInterface, postfix) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdGetDeviceAddressTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdGetDeviceAddress(nullptr, nullptr, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("STATUS"); + char address[18] = {0}; + int size = 18; + EXPECT_TRUE(mInterface->wpaP2pCliCmdGetDeviceAddress(mInterface, address, size) != P2P_SUP_ERRCODE_SUCCESS); + char buf1[] = "wpa_state=SCANNING\n" + "ip_address=192.168.xxx.xxx\n" + "freq=1024\n" + "key_mgmt=WPA-PSK\n"; + MockSetWpaExpectCmdResponse("STATUS", buf1); + EXPECT_TRUE(mInterface->wpaP2pCliCmdGetDeviceAddress(mInterface, address, size) != P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(strlen(address) == 0); + char buf2[] = "wpa_state=SCANNING\n" + "ip_address=192.168.xxx.xxx\n" + "freq=1024\n" + "key_mgmt=WPA-PSK\n" + "p2p_device_address=00:00:00:00:00:00\n"; + MockSetWpaExpectCmdResponse("STATUS", buf2); + EXPECT_TRUE(mInterface->wpaP2pCliCmdGetDeviceAddress(mInterface, address, size) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(strcmp(address, "00:00:00:00:00:00") == 0); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdFlushTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdFlush(nullptr) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("P2P_FLUSH"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdFlush(mInterface) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_FLUSH", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdFlush(mInterface) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_FLUSH", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdFlush(mInterface) == P2P_SUP_ERRCODE_SUCCESS); + char replyDeviceLost[] = "P2P-DEVICE-LOST p2p_dev_addr=00:00:00:00:00:00\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyDeviceLost); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdFlushServiceTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdFlushService(nullptr) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("P2P_SERVICE_FLUSH"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdFlushService(mInterface) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERVICE_FLUSH", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdFlushService(mInterface) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERVICE_FLUSH", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdFlushService(mInterface) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdP2pStopFindTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pStopFind(nullptr) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("P2P_STOP_FIND"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pStopFind(mInterface) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_STOP_FIND", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pStopFind(mInterface) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_STOP_FIND", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pStopFind(mInterface) == P2P_SUP_ERRCODE_SUCCESS); + char replyFindStop[] = "P2P-FIND-STOPPED \n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyFindStop); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdP2pRemoveGroupTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pRemoveGroup(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + char groupname[] = "p2p-dev-p2p0"; + MockEraseSupportedCmd("P2P_GROUP_REMOVE"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pRemoveGroup(mInterface, groupname) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_GROUP_REMOVE", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pRemoveGroup(mInterface, groupname) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_GROUP_REMOVE", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pRemoveGroup(mInterface, groupname) == P2P_SUP_ERRCODE_SUCCESS); + char replyGroupRemove[] = "P2P-GROUP-REMOVED p2p-dev-p2p0 GO reason=REQUESTED\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyGroupRemove); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdP2pFoundTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pFound(nullptr, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("P2P_FIND"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pFound(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_FIND", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pFound(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_FIND", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pFound(mInterface, 0) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pFound(mInterface, -1) == P2P_SUP_ERRCODE_SUCCESS); + + char replyP2pFound[] = + "<3>P2P-DEVICE-FOUND ff:ff:ff:ff:ff:ff p2p_dev_addr=00:00:00:00:00:00 pri_dev_type=1-0050f204-1 " + "name='Wireless Client' config_methods=0xa4 dev_capab=0x2C group_capab=0xdD " + "wfd_dev_info=0x00111c440032 new=1\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyP2pFound); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdRemoveNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdRemoveNetwork(nullptr, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("REMOVE_NETWORK"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdRemoveNetwork(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("REMOVE_NETWORK", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdRemoveNetwork(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("REMOVE_NETWORK", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdRemoveNetwork(mInterface, 0) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(mInterface->wpaP2pCliCmdRemoveNetwork(mInterface, -1) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(mInterface->wpaP2pCliCmdRemoveNetwork(mInterface, -2) != P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdSetWfdEnableTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWfdEnable(nullptr, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("SET"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWfdEnable(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWfdEnable(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWfdEnable(mInterface, 0) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdSetWfdDeviceInfoTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWfdDeviceInfo(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("WFD_SUBELEM_SET"); + char conf[] = "xxxxxxxx"; + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWfdDeviceInfo(mInterface, conf) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("WFD_SUBELEM_SET", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWfdDeviceInfo(mInterface, conf) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("WFD_SUBELEM_SET", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetWfdDeviceInfo(mInterface, conf) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdExtListenTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdExtListen(nullptr, 0, 0, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("P2P_EXT_LISTEN"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdExtListen(mInterface, 0, 0, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_EXT_LISTEN", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdExtListen(mInterface, 0, 0, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_EXT_LISTEN", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdExtListen(mInterface, 0, 0, 0) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(mInterface->wpaP2pCliCmdExtListen(mInterface, 1, 120, 30) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdSetListenChannelTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetListenChannel(nullptr, 0, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("P2P_SET"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetListenChannel(mInterface, 0, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SET", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetListenChannel(mInterface, 0, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SET", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetListenChannel(mInterface, 0, 0) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetListenChannel(mInterface, 0, 1) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdCancelConnectTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdCancelConnect(nullptr) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("P2P_CANCEL"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdCancelConnect(mInterface) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_CANCEL", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdCancelConnect(mInterface) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_CANCEL", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdCancelConnect(mInterface) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdInviteTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdInvite(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + P2pHalInviteArgv argv; + ASSERT_TRUE(memset_s(&argv, sizeof(argv), 0, sizeof(argv)) == EOK); + EXPECT_TRUE(mInterface->wpaP2pCliCmdInvite(mInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + StrSafeCopy(argv.ifname, sizeof(argv.ifname), "p2p-dev-p2p0"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdInvite(mInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + StrSafeCopy(argv.gobssid, sizeof(argv.gobssid), "00:00:00:00:00:00"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdInvite(mInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + StrSafeCopy(argv.peerbssid, sizeof(argv.peerbssid), "ff:ff:ff:ff:ff:ff"); + MockEraseSupportedCmd("P2P_INVITE"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdInvite(mInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_INVITE", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdInvite(mInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_INVITE", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdInvite(mInterface, &argv) == P2P_SUP_ERRCODE_SUCCESS); + char replyInviteResult1[] = "P2P-INVITATION-RESULT status=0 00:00:00:00:00:00\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyInviteResult1); + char replyInviteResult2[] = "P2P-INVITATION-RESULT status=0 \n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyInviteResult2); + char replyInviteReceive[] = "P2P-INVITATION-RECEIVED sa=00:00:00:00:00:00 persistent=4 freq=2467 " + "go_dev_addr=ff:ff:ff:ff:ff:ff bssid=0F:0F:0F:0F:0F:0F\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyInviteReceive); + char replyInviateAccept[] = "P2P-INVITATION-ACCEPTED sa=00:00:00:00:00:00 persistent=0 freq=5180\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyInviateAccept); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdReInviteTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdReInvite(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + P2pHalReInviteArgv argv; + ASSERT_TRUE(memset_s(&argv, sizeof(argv), 0, sizeof(argv)) == EOK); + EXPECT_TRUE(mInterface->wpaP2pCliCmdReInvite(mInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + StrSafeCopy(argv.peerbssid, sizeof(argv.peerbssid), "00:00:00:00:00:00"); + MockEraseSupportedCmd("P2P_INVITE"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdReInvite(mInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_INVITE", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdReInvite(mInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_INVITE", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdReInvite(mInterface, &argv) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdServiceAddTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceAdd(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + HidlP2pServiceInfo info; + ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceAdd(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + StrSafeCopy(info.name, sizeof(info.name), "random_string"); + MockEraseSupportedCmd("P2P_SERVICE_ADD"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceAdd(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERVICE_ADD", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceAdd(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERVICE_ADD", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceAdd(mInterface, &info) == P2P_SUP_ERRCODE_SUCCESS); + info.mode = 1; + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceAdd(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + StrSafeCopy(info.query, sizeof(info.query), "random_hex_type_query_message"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceAdd(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + StrSafeCopy(info.resp, sizeof(info.resp), "random_hex_type_resp_message"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceAdd(mInterface, &info) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdServiceDelTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceDel(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + HidlP2pServiceInfo info; + ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceDel(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + StrSafeCopy(info.name, sizeof(info.name), "random_string"); + MockEraseSupportedCmd("P2P_SERVICE_DEL"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceDel(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERVICE_DEL", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceDel(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERVICE_DEL", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceDel(mInterface, &info) == P2P_SUP_ERRCODE_SUCCESS); + info.mode = 1; + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceDel(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + StrSafeCopy(info.query, sizeof(info.query), "random_hex_type_query_message"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceDel(mInterface, &info) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdServDiscReqTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdServDiscReq(nullptr, nullptr, nullptr, nullptr, 0) != P2P_SUP_ERRCODE_SUCCESS); + char peerBssid[] = "00:00:00:00:00:00"; + char tlvs[256] = {0}; + char retSeq[64] = {0}; + unsigned size = sizeof(retSeq); + EXPECT_TRUE( + mInterface->wpaP2pCliCmdServDiscReq(mInterface, peerBssid, tlvs, retSeq, size) != P2P_SUP_ERRCODE_SUCCESS); + StrSafeCopy(tlvs, sizeof(tlvs), "hex_type_tlv_string"); + MockEraseSupportedCmd("P2P_SERV_DISC_REQ"); + EXPECT_TRUE( + mInterface->wpaP2pCliCmdServDiscReq(mInterface, peerBssid, tlvs, retSeq, size) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERV_DISC_REQ", "FAIL\n"); + EXPECT_TRUE( + mInterface->wpaP2pCliCmdServDiscReq(mInterface, peerBssid, tlvs, retSeq, size) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERV_DISC_REQ", "OK\n"); + EXPECT_TRUE( + mInterface->wpaP2pCliCmdServDiscReq(mInterface, peerBssid, tlvs, retSeq, size) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(strcmp(retSeq, "OK\n") == 0); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdServDiscCancelReqTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdServDiscCancelReq(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + char val[] = "hex_string"; + MockEraseSupportedCmd("P2P_SERV_DISC_CANCEL_REQ"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServDiscCancelReq(mInterface, val) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERV_DISC_CANCEL_REQ", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServDiscCancelReq(mInterface, val) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERV_DISC_CANCEL_REQ", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdServDiscCancelReq(mInterface, val) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdProvisionDiscoveryTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdProvisionDiscovery(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + P2pProvisionDiscoveryArgv argv; + ASSERT_TRUE(memset_s(&argv, sizeof(argv), 0, sizeof(argv)) == EOK); + EXPECT_TRUE(mInterface->wpaP2pCliCmdProvisionDiscovery(mInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + argv.mode = HAL_WPS_METHOD_PBC; + StrSafeCopy(argv.peerbssid, sizeof(argv.peerbssid), "00:00:00:00:00:00"); + MockEraseSupportedCmd("P2P_PROV_DISC"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdProvisionDiscovery(mInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_PROV_DISC", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdProvisionDiscovery(mInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_PROV_DISC", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdProvisionDiscovery(mInterface, &argv) == P2P_SUP_ERRCODE_SUCCESS); + argv.mode = HAL_WPS_METHOD_DISPLAY; + EXPECT_TRUE(mInterface->wpaP2pCliCmdProvisionDiscovery(mInterface, &argv) == P2P_SUP_ERRCODE_SUCCESS); + argv.mode = HAL_WPS_METHOD_KEYPAD; + EXPECT_TRUE(mInterface->wpaP2pCliCmdProvisionDiscovery(mInterface, &argv) == P2P_SUP_ERRCODE_SUCCESS); + argv.mode = HAL_WPS_METHOD_LABEL; + EXPECT_TRUE(mInterface->wpaP2pCliCmdProvisionDiscovery(mInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + argv.mode = HAL_WPS_METHOD_INVALID; + EXPECT_TRUE(mInterface->wpaP2pCliCmdProvisionDiscovery(mInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + + char replyDiscPbcReq1[] = "P2P-PROV-DISC-PBC-REQ 00:00:00:00:00:00 \n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyDiscPbcReq1); + char replyDiscPbcReq2[] = "P2P-PROV-DISC-PBC-REQ invalid mac \n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyDiscPbcReq2); + char replyDiscEnterPin1[] = "P2P-PROV-DISC-ENTER-PIN 00:00:00:00:00:00 \n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyDiscEnterPin1); + char replyDiscEnterPin2[] = "P2P-PROV-DISC-ENTER-PIN invalid mac \n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyDiscEnterPin2); + char replyDiscShowPin1[] = "P2P-PROV-DISC-SHOW-PIN 00:00:00:00:00:00 12345678\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyDiscShowPin1); + char replyDiscShowPin2[] = "P2P-PROV-DISC-SHOW-PIN invalid mac \n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyDiscShowPin2); + char replyServiceDiscReq[] = "P2P-SERV-DISC-REQ 2462 00:00:00:00:00:00 0 0 0200010102000202\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyServiceDiscReq); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdGroupAddTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdGroupAdd(nullptr, 0, 0, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("P2P_GROUP_ADD"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdGroupAdd(mInterface, 0, 0, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_GROUP_ADD", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdGroupAdd(mInterface, 0, 0, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_GROUP_ADD", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdGroupAdd(mInterface, 0, 0, 0) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(mInterface->wpaP2pCliCmdGroupAdd(mInterface, 1, -1, 0) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(mInterface->wpaP2pCliCmdGroupAdd(mInterface, 1, 0, 0) == P2P_SUP_ERRCODE_SUCCESS); + + char replyGroupStart[] = "P2P-GROUP-STARTED p2p-wlan0-0 GO " + "ssid=\"OHOS p2p ssid\" " + "freq=5180 " + "psk=pskmsg " + "passphrase=\"UotFDHj3\" " + "go_dev_addr=00:00:00:00:00:00\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyGroupStart); + char replyGroupFailure[] = "P2P-GROUP-FORMATION-FAILURE reason=FREQ_CONFLICT\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyGroupFailure); + char replyGroupSuccess[] = "P2P-GROUP-FORMATION-SUCCESS \n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyGroupSuccess); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdStoreConfigTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdStoreConfig(nullptr) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("SAVE_CONFIG"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdStoreConfig(mInterface) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SAVE_CONFIG", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdStoreConfig(mInterface) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SAVE_CONFIG", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdStoreConfig(mInterface) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdNetworkListTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdNetworkList(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + HidlP2pNetworkList infoList; + ASSERT_TRUE(memset_s(&infoList, sizeof(infoList), 0, sizeof(infoList)) == EOK); + MockEraseSupportedCmd("LIST_NETWORKS"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdNetworkList(mInterface, &infoList) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("LIST_NETWORKS", "OK"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdNetworkList(mInterface, &infoList) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("LIST_NETWORKS", "network id / ssid / bssid / flags\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdNetworkList(mInterface, &infoList) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(infoList.infoNum == 0); + char buf[] = "network id / ssid / bssid / flags\n" + "0\tp2p_ssid_1\t00:00:00:00:00:00\t[DISABLED][P2P-PERSISTENT]\n" + "1\tp2p_ssid_2\tff:ff:ff:ff:ff:ff\t[DISABLED]\n"; + MockSetWpaExpectCmdResponse("LIST_NETWORKS", buf); + EXPECT_TRUE(mInterface->wpaP2pCliCmdNetworkList(mInterface, &infoList) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(infoList.infoNum == 2); + EXPECT_TRUE(infoList.infos[0].id == 0); + EXPECT_TRUE(strcmp(infoList.infos[0].ssid, "p2p_ssid_1") == 0); + EXPECT_TRUE(strcmp(infoList.infos[0].bssid, "00:00:00:00:00:00") == 0); + EXPECT_TRUE(strcmp(infoList.infos[0].flags, "[DISABLED][P2P-PERSISTENT]") == 0); + EXPECT_TRUE(infoList.infos[1].id == 1); + EXPECT_TRUE(strcmp(infoList.infos[1].ssid, "p2p_ssid_2") == 0); + EXPECT_TRUE(strcmp(infoList.infos[1].bssid, "ff:ff:ff:ff:ff:ff") == 0); + EXPECT_TRUE(strcmp(infoList.infos[1].flags, "[DISABLED]") == 0); + free(infoList.infos); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdConnectTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdConnect(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + HidlP2pConnectInfo info; + ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); + info.mode = 0; + info.goIntent = 0; + info.provdisc = HAL_WPS_METHOD_DISPLAY; + StrSafeCopy(info.peerDevAddr, sizeof(info.peerDevAddr), "00:00:00:00:00:00"); + MockEraseSupportedCmd("P2P_CONNECT"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdConnect(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_CONNECT", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdConnect(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_CONNECT", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdConnect(mInterface, &info) == P2P_SUP_ERRCODE_SUCCESS); + info.mode = 1; + EXPECT_TRUE(mInterface->wpaP2pCliCmdConnect(mInterface, &info) == P2P_SUP_ERRCODE_SUCCESS); + info.provdisc = HAL_WPS_METHOD_KEYPAD; + EXPECT_TRUE(mInterface->wpaP2pCliCmdConnect(mInterface, &info) == P2P_SUP_ERRCODE_SUCCESS); + info.provdisc = HAL_WPS_METHOD_PBC; + EXPECT_TRUE(mInterface->wpaP2pCliCmdConnect(mInterface, &info) == P2P_SUP_ERRCODE_SUCCESS); + info.provdisc = HAL_WPS_METHOD_LABEL; + EXPECT_TRUE(mInterface->wpaP2pCliCmdConnect(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + info.provdisc = HAL_WPS_METHOD_DISPLAY; + StrSafeCopy(info.pin, sizeof(info.pin), "pin"); + MockSetWpaExpectCmdResponse("P2P_CONNECT", "12345678"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdConnect(mInterface, &info) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(strcmp(info.pin, "12345678") == 0); + char replyGoNegRequest1[] = "P2P-GO-NEG-REQUEST 00:00:00:00:00:00 dev_passwd_id=1 go_intent=7\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyGoNegRequest1); + char replyGoNegRequest2[] = "P2P-GO-NEG-REQUEST 00:00:00:00:00:00 \n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyGoNegRequest2); + char replyGoNegSuccess[] = "P2P-GO-NEG-SUCCESS role=GO freq=5180 ht40=0 peer_dev=00:00:00:00:00:00 " + "peer_iface=00:00:00:00:00:00 wps_method=Display\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyGoNegSuccess); + char replyGoNegFailure1[] = "P2P-GO-NEG-FAILURE status=1\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyGoNegFailure1); + char replyGoNegFailure2[] = "P2P-GO-NEG-FAILURE \n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyGoNegFailure2); + char replyConnect[] = "AP-STA-CONNECTED 00:00:00:00:00:00 p2p_dev_addr=ff:ff:ff:ff:ff:ff\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyConnect); + char replyDisconnect[] = "AP-STA-DISCONNECTED 00:00:00:00:00:00 p2p_dev_addr=ff:ff:ff:ff:ff:ff\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyDisconnect); + char replyDisconnect2[] = "AP-STA-DISCONNECTED 00:00:00:00:00:00\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyDisconnect2); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdP2pGetPeerTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pGetPeer(nullptr, nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + const char *bssid = "00:00:00:00:00:00"; + HidlP2pDeviceInfo info; + MockEraseSupportedCmd("P2P_PEER"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pGetPeer(mInterface, nullptr, &info) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_PEER", "group_capab=0x0\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pGetPeer(mInterface, bssid, &info) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdSetPersistentReconnectTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetPersistentReconnect(nullptr, 0) != P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetPersistentReconnect(mInterface, -1) != P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetPersistentReconnect(mInterface, 2) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("SET"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetPersistentReconnect(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetPersistentReconnect(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetPersistentReconnect(mInterface, 0) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdRespServerDiscoveryTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdRespServerDiscovery(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + HidlP2pServDiscReqInfo info; + ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); + info.freq = 2412; + info.dialogToken = 0; + StrSafeCopy(info.mac, sizeof(info.mac), "00:00:00:00:00:00"); + info.tlvs = (char *)calloc(256, sizeof(char)); + ASSERT_TRUE(info.tlvs != NULL); + StrSafeCopy(info.tlvs, 256, "08000104112233445566"); + MockEraseSupportedCmd("P2P_SERV_DISC_RESP"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdRespServerDiscovery(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERV_DISC_RESP", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdRespServerDiscovery(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERV_DISC_RESP", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdRespServerDiscovery(mInterface, &info) == P2P_SUP_ERRCODE_SUCCESS); + free(info.tlvs); + + char replyDiscPbc[] = "P2P-PROV-DISC-PBC-RESP 00:00:00:00:00:00\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyDiscPbc); + char replyDiscPbc2[] = "P2P-PROV-DISC-PBC-RESP invalid mac\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyDiscPbc2); + char replyServiceDisc[] = "P2P-SERV-DISC-RESP 00:00:00:00:00:00 0 03000101010300020201\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyServiceDisc); + char replyDiscFailure[] = "P2P-PROV-DISC-FAILURE p2p_dev_addr=00:00:00:00:00:00 status=0\n"; + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, replyDiscFailure); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdSetServDiscExternalTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetServDiscExternal(nullptr, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("P2P_SERV_DISC_EXTERNAL"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetServDiscExternal(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERV_DISC_EXTERNAL", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetServDiscExternal(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SERV_DISC_EXTERNAL", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetServDiscExternal(mInterface, 0) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdSetRandomMacTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetRandomMac(nullptr, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("DRIVER_FLAGS"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetRandomMac(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("DRIVER_FLAGS", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetRandomMac(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("DRIVER_FLAGS", "DEDICATED_P2P_DEVICE\n"); + MockEraseSupportedCmd("SET"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetRandomMac(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetRandomMac(mInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "OK\n"); + EXPECT_TRUE(mInterface->wpaP2pCliCmdSetRandomMac(mInterface, 0) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdWpsPbcTest, TestSize.Level1) +{ + WifiWpaP2pGroupInterface *groupInterface = GetWifiWpaP2pGroupInterface("p2p-dev-wlan0"); + ASSERT_TRUE(groupInterface != nullptr); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdWpsPbc(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + const char *bssid = "00:00:00:00:00:00"; + MockEraseSupportedCmd("WPS_PBC"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdWpsPbc(groupInterface, bssid) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("WPS_PBC", "FAIL\n"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdWpsPbc(groupInterface, bssid) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("WPS_PBC", "FAIL-PBC-OVERLAP\n"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdWpsPbc(groupInterface, bssid) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("WPS_PBC", "OK\n"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdWpsPbc(groupInterface, bssid) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdWpsPinTest, TestSize.Level1) +{ + WifiWpaP2pGroupInterface *groupInterface = GetWifiWpaP2pGroupInterface("p2p-dev-wlan0"); + ASSERT_TRUE(groupInterface != nullptr); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdWpsPin(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); + P2pWpsPinDisplayArgv argv; + ASSERT_TRUE(memset_s(&argv, sizeof(argv), 0, sizeof(argv)) == EOK); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdWpsPin(groupInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + argv.mode = P2P_PIN_KEYPAD; + EXPECT_TRUE(groupInterface->wpaP2pCliCmdWpsPin(groupInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + StrSafeCopy(argv.pinCode, sizeof(argv.pinCode), "12345678"); + MockEraseSupportedCmd("WPS_PIN"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdWpsPin(groupInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("WPS_PIN", "FAIL\n"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdWpsPin(groupInterface, &argv) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("WPS_PIN", "OK\n"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdWpsPin(groupInterface, &argv) == P2P_SUP_ERRCODE_SUCCESS); + argv.mode = P2P_PIN_DISPLAY; + MockSetWpaExpectCmdResponse("WPS_PIN", "987654321"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdWpsPin(groupInterface, &argv) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(strcmp(argv.pinCode, "98765432") == 0); + StrSafeCopy(argv.bssid, sizeof(argv.bssid), "00:00:00:00:00:00"); + MockSetWpaExpectCmdResponse("WPS_PIN", "00123456"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdWpsPin(groupInterface, &argv) == P2P_SUP_ERRCODE_SUCCESS); + EXPECT_TRUE(strcmp(argv.pinCode, "00123456") == 0); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdSetPowerSaveTest, TestSize.Level1) +{ + WifiWpaP2pGroupInterface *groupInterface = GetWifiWpaP2pGroupInterface("p2p-dev-wlan0"); + ASSERT_TRUE(groupInterface != nullptr); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdSetPowerSave(nullptr, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("P2P_SET"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdSetPowerSave(groupInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SET", "FAIL\n"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdSetPowerSave(groupInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("P2P_SET", "OK\n"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdSetPowerSave(groupInterface, 0) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdSetGroupIdleTest, TestSize.Level1) +{ + WifiWpaP2pGroupInterface *groupInterface = GetWifiWpaP2pGroupInterface("p2p-dev-wlan0"); + ASSERT_TRUE(groupInterface != nullptr); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdSetGroupIdle(nullptr, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockEraseSupportedCmd("SET"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdSetGroupIdle(groupInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "FAIL\n"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdSetGroupIdle(groupInterface, 0) != P2P_SUP_ERRCODE_SUCCESS); + MockSetWpaExpectCmdResponse("SET", "OK\n"); + EXPECT_TRUE(groupInterface->wpaP2pCliCmdSetGroupIdle(groupInterface, 0) == P2P_SUP_ERRCODE_SUCCESS); +} + +HWTEST_F(WifiHalWpaP2pTest, ConvertP2pErrCodeTest, TestSize.Level1) +{ + EXPECT_TRUE(ConvertP2pErrCode(P2P_SUP_ERRCODE_SUCCESS) == WIFI_HAL_SUCCESS); + EXPECT_TRUE(ConvertP2pErrCode(P2P_SUP_ERRCODE_PBC_OVERLAP) == WIFI_HAL_PBC_OVERLAP); + EXPECT_TRUE(ConvertP2pErrCode(P2P_SUP_ERRCODE_INPUT_ERROR) == WIFI_HAL_INVALID_PARAM); + EXPECT_TRUE(ConvertP2pErrCode(P2P_SUP_ERRCODE_FAILED) == WIFI_HAL_FAILED); + EXPECT_TRUE(ConvertP2pErrCode(P2P_SUP_ERRCODE_TIMEOUT) == WIFI_HAL_FAILED); +} + +HWTEST_F(WifiHalWpaP2pTest, GetWifiWpaP2pGroupInterfaceTest, TestSize.Level1) +{ + WifiWpaP2pGroupInterface *groupInterface = GetWifiWpaP2pGroupInterface("p2p-dev-wlan0"); + ASSERT_TRUE(groupInterface != nullptr); + WifiWpaP2pGroupInterface *groupInterface1 = GetWifiWpaP2pGroupInterface("p2p-dev-wlan0"); + ASSERT_TRUE(groupInterface1 != nullptr); + EXPECT_TRUE(groupInterface == groupInterface1); + ReleaseWpaP2pGroupInterface("p2p-dev-unknown"); + ReleaseWpaP2pGroupInterface("p2p-dev-wlan0"); + ReleaseWpaP2pGroupInterface("p2p-dev-wlan0"); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.h b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.h new file mode 100644 index 000000000..114ae8c49 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.h @@ -0,0 +1,40 @@ +/* + * 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_WIFI_HAL_WPA_P2P_TEST_H +#define OHOS_WIFI_HAL_WPA_P2P_TEST_H + +#include +#include "server.h" +#include "wifi_p2p_hal.h" +#include "wifi_wpa_hal.h" + +namespace OHOS { +namespace Wifi { +class WifiHalWpaP2pTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() + {} + virtual void TearDown() + {} + + static WifiWpaInterface *mGlobalInterface; + static WifiWpaP2pInterface *mInterface; + static RpcServer *mServer; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.cpp b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.cpp new file mode 100644 index 000000000..551d816e3 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.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 "wifi_hal_wpa_sta_test.h" +#include "securec.h" +#include "mock_wpa_ctrl.h" +#include "wifi_hal_crpc_server.h" +#include "wifi_hal_common_func.h" +#include "wifi_log.h" +#undef LOG_TAG +#define LOG_TAG "WifiHalWpaStaTest" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { +const std::string g_rpcSockPath = "./unix_sock_test.sock"; +WifiWpaInterface *WifiHalWpaStaTest::mGlobalInterface = nullptr; +WifiWpaStaInterface *WifiHalWpaStaTest::mInterface = nullptr; +RpcServer *WifiHalWpaStaTest::mServer = nullptr; + +void WifiHalWpaStaTest::SetUpTestCase() +{ + if (access(g_rpcSockPath.c_str(), 0) == 0) { + unlink(g_rpcSockPath.c_str()); + } + mServer = CreateRpcServer(g_rpcSockPath.c_str()); + if (mServer == nullptr) { + printf("Init rpc server failed!"); + exit(-1); + } + InitCallbackMsg(); + SetRpcServerInited(mServer); + MockInitGlobalCmd(); + MockInitStaSupportedCmd(); + mGlobalInterface = GetWifiWapGlobalInterface(); + mGlobalInterface->wpaCliConnect(mGlobalInterface); + mInterface = GetWifiStaInterface(0); +} + +void WifiHalWpaStaTest::TearDownTestCase() +{ + sleep(1); + ReleaseWpaGlobalInterface(); + ReleaseWifiStaInterface(0); + if (mServer != nullptr) { + ReleaseRpcServer(mServer); + mServer = nullptr; + } + SetRpcServerInited(NULL); + ReleaseCallbackMsg(); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdStatusTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaCliCmdStatus(mInterface, nullptr) < 0); + MockEraseSupportedCmd("STATUS"); + WpaHalCmdStatus status; + ASSERT_TRUE(memset_s(&status, sizeof(status), 0, sizeof(status)) == EOK); + EXPECT_TRUE(mInterface->wpaCliCmdStatus(mInterface, &status) < 0); + char buf1[] = "wpa_state=SCANNING\n" + "ip_address=192.168.xxx.xxx\n" + "freq=1024\n" + "key_mgmt=WPA-PSK\n"; + MockSetWpaExpectCmdResponse("STATUS", buf1); + EXPECT_TRUE(mInterface->wpaCliCmdStatus(mInterface, &status) < 0); + EXPECT_TRUE(status.freq == 1024); + char buf2[] = "wpa_state=SCANNING\n" + "ip_address=192.168.xxx.xxx\n" + "freq=1024\n" + "key_mgmt=WPA-PSK\n" + "address=00:00:00:00:00:00\n"; + MockSetWpaExpectCmdResponse("STATUS", buf2); + EXPECT_TRUE(mInterface->wpaCliCmdStatus(mInterface, &status) == 1); + EXPECT_TRUE(strcmp(status.address, "00:00:00:00:00:00") == 0); + char buf3[] = "wpa_state=SCANNING\n" + "ip_address=192.168.xxx.xxx\n" + "freq=1024\n" + "key_mgmt=WPA-PSK\n" + "address=00:00:00:00:00:00\n" + "bssid=00:00:00:00:00:00\n" + "ssid=testAp\n" + "id=1\n"; + MockSetWpaExpectCmdResponse("STATUS", buf3); + EXPECT_TRUE(mInterface->wpaCliCmdStatus(mInterface, &status) == 0); + EXPECT_TRUE(strcmp(status.address, "00:00:00:00:00:00") == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdAddNetworksTest, TestSize.Level1) +{ + MockEraseSupportedCmd("ADD_NETWORK"); + EXPECT_TRUE(mInterface->wpaCliCmdAddNetworks(mInterface) < 0); + MockSetWpaExpectCmdResponse("ADD_NETWORK", "1"); + int ret = mInterface->wpaCliCmdAddNetworks(mInterface); + EXPECT_TRUE(ret == 1); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdReconnectTest, TestSize.Level1) +{ + MockEraseSupportedCmd("RECONNECT"); + EXPECT_TRUE(mInterface->wpaCliCmdReconnect(mInterface) < 0); + MockSetWpaExpectCmdResponse("RECONNECT", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdReconnect(mInterface) < 0); + MockSetWpaExpectCmdResponse("RECONNECT", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdReconnect(mInterface) == 0); + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, + "<3>CTRL-EVENT-CONNECTED - Connection to 00:00:00:00:00:00 completed [id=1 id_str=]\n"); + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, "<3>CTRL-EVENT-STATE-CHANGE state=2\n"); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdReassociateTest, TestSize.Level1) +{ + MockEraseSupportedCmd("REASSOCIATE"); + EXPECT_TRUE(mInterface->wpaCliCmdReassociate(mInterface) < 0); + MockSetWpaExpectCmdResponse("REASSOCIATE", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdReassociate(mInterface) < 0); + MockSetWpaExpectCmdResponse("REASSOCIATE", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdReassociate(mInterface) == 0); + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, "<3>CTRL-EVENT-SSID-TEMP-DISABLED reason=WRONG_KEY\n"); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdDisconnectTest, TestSize.Level1) +{ + MockEraseSupportedCmd("DISCONNECT"); + EXPECT_TRUE(mInterface->wpaCliCmdDisconnect(mInterface) < 0); + MockSetWpaExpectCmdResponse("DISCONNECT", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdDisconnect(mInterface) < 0); + MockSetWpaExpectCmdResponse("DISCONNECT", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdDisconnect(mInterface) == 0); + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, + "<3>CTRL-EVENT-DISCONNECTED bssid=00:00:00:00:00:00 reason=4 locally_generated=1\n"); + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, "<3>CTRL-EVENT-STATE-CHANGE state=3\n"); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdSaveConfigTest, TestSize.Level1) +{ + MockEraseSupportedCmd("SAVE_CONFIG"); + EXPECT_TRUE(mInterface->wpaCliCmdSaveConfig(mInterface) < 0); + MockSetWpaExpectCmdResponse("SAVE_CONFIG", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdSaveConfig(mInterface) < 0); + MockSetWpaExpectCmdResponse("SAVE_CONFIG", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdSaveConfig(mInterface) == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdSetNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaCliCmdSetNetwork(mInterface, nullptr) < 0); + WpaSetNetworkArgv argv; + ASSERT_TRUE(memset_s(&argv, sizeof(argv), 0, sizeof(argv)) == EOK); + argv.id = 0; + argv.param = DEVICE_CONFIG_END_POS; + EXPECT_TRUE(mInterface->wpaCliCmdSetNetwork(mInterface, &argv) < 0); + argv.param = DEVICE_CONFIG_SSID; + EXPECT_TRUE(mInterface->wpaCliCmdSetNetwork(mInterface, &argv) == 0); + MockEraseSupportedCmd("SET_NETWORK"); + EXPECT_TRUE(mInterface->wpaCliCmdSetNetwork(mInterface, &argv) < 0); + MockSetWpaExpectCmdResponse("SET_NETWORK", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdSetNetwork(mInterface, &argv) < 0); + MockSetWpaExpectCmdResponse("SET_NETWORK", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdSetNetwork(mInterface, &argv) == 0); + argv.param = DEVICE_CONFIG_KEYMGMT; + EXPECT_TRUE(mInterface->wpaCliCmdSetNetwork(mInterface, &argv) == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdEnableNetworkTest, TestSize.Level1) +{ + MockEraseSupportedCmd("ENABLE_NETWORK"); + EXPECT_TRUE(mInterface->wpaCliCmdEnableNetwork(mInterface, 0) < 0); + MockSetWpaExpectCmdResponse("ENABLE_NETWORK", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdEnableNetwork(mInterface, 0) < 0); + MockSetWpaExpectCmdResponse("ENABLE_NETWORK", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdEnableNetwork(mInterface, 0) == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdSelectNetworkTest, TestSize.Level1) +{ + MockEraseSupportedCmd("SELECT_NETWORK"); + EXPECT_TRUE(mInterface->wpaCliCmdSelectNetwork(mInterface, 0) < 0); + MockSetWpaExpectCmdResponse("SELECT_NETWORK", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdSelectNetwork(mInterface, 0) < 0); + MockSetWpaExpectCmdResponse("SELECT_NETWORK", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdSelectNetwork(mInterface, 0) == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdDisableNetworkTest, TestSize.Level1) +{ + MockEraseSupportedCmd("DISABLE_NETWORK"); + EXPECT_TRUE(mInterface->wpaCliCmdDisableNetwork(mInterface, 0) < 0); + MockSetWpaExpectCmdResponse("DISABLE_NETWORK", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdDisableNetwork(mInterface, 0) < 0); + MockSetWpaExpectCmdResponse("DISABLE_NETWORK", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdDisableNetwork(mInterface, 0) == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdRemoveNetworkTest, TestSize.Level1) +{ + MockEraseSupportedCmd("REMOVE_NETWORK"); + EXPECT_TRUE(mInterface->wpaCliCmdRemoveNetwork(mInterface, 0) < 0); + MockSetWpaExpectCmdResponse("REMOVE_NETWORK", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdRemoveNetwork(mInterface, 0) < 0); + MockSetWpaExpectCmdResponse("REMOVE_NETWORK", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdRemoveNetwork(mInterface, 0) == 0); + EXPECT_TRUE(mInterface->wpaCliCmdRemoveNetwork(mInterface, -1) == 0); + EXPECT_TRUE(mInterface->wpaCliCmdRemoveNetwork(mInterface, -2) < 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdGetNetworkTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaCliCmdGetNetwork(mInterface, nullptr, nullptr, 0) < 0); + WpaGetNetworkArgv argv; + ASSERT_TRUE(memset_s(&argv, sizeof(argv), 0, sizeof(argv)) == EOK); + char getBuffer[256] = {0}; + MockEraseSupportedCmd("GET_NETWORK"); + EXPECT_TRUE(mInterface->wpaCliCmdGetNetwork(mInterface, &argv, getBuffer, sizeof(getBuffer)) < 0); + MockSetWpaExpectCmdResponse("GET_NETWORK", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdGetNetwork(mInterface, &argv, getBuffer, sizeof(getBuffer)) == 0); + EXPECT_TRUE(strcmp(getBuffer, "OK") == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdWpsPbcTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaCliCmdWpsPbc(mInterface, nullptr) == 0); + WpaWpsPbcArgv argv; + ASSERT_TRUE(memset_s(&argv, sizeof(argv), 0, sizeof(argv)) == EOK); + MockEraseSupportedCmd("WPS_PBC"); + EXPECT_TRUE(mInterface->wpaCliCmdWpsPbc(mInterface, &argv) < 0); + MockSetWpaExpectCmdResponse("WPS_PBC", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdWpsPbc(mInterface, &argv) < 0); + MockSetWpaExpectCmdResponse("WPS_PBC", "FAIL-PBC-OVERLAP"); + EXPECT_TRUE(mInterface->wpaCliCmdWpsPbc(mInterface, &argv) == 3); + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, "<3>WPS-OVERLAP-DETECTED PBC session overlap\n"); + MockSetWpaExpectCmdResponse("WPS_PBC", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdWpsPbc(mInterface, &argv) == 0); + MockWpaCallback(mGlobalInterface->wpaCtrl.pSend, "<3>WPS-TIMEOUT Requested operation timed out\n"); + argv.anyFlag = 1; + argv.multiAp = 1; + EXPECT_TRUE(mInterface->wpaCliCmdWpsPbc(mInterface, &argv) == 0); + argv.anyFlag = 0; + StrSafeCopy(argv.bssid, sizeof(argv.bssid), "00:00:00:00:00:00"); + EXPECT_TRUE(mInterface->wpaCliCmdWpsPbc(mInterface, &argv) == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdWpsPinTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaCliCmdWpsPin(mInterface, nullptr, nullptr) < 0); + WpaWpsPinArgv argv; + ASSERT_TRUE(memset_s(&argv, sizeof(argv), 0, sizeof(argv)) == EOK); + int pinCode = 0; + MockEraseSupportedCmd("WPS_PIN"); + EXPECT_TRUE(mInterface->wpaCliCmdWpsPin(mInterface, &argv, &pinCode) < 0); + MockSetWpaExpectCmdResponse("WPS_PIN", "12345678"); + EXPECT_TRUE(mInterface->wpaCliCmdWpsPin(mInterface, &argv, &pinCode) == 0); + EXPECT_TRUE(pinCode == 12345678); + StrSafeCopy(argv.bssid, sizeof(argv.bssid), "00:00:00:00:00:00"); + StrSafeCopy(argv.pinCode, sizeof(argv.pinCode), "87654321"); + MockSetWpaExpectCmdResponse("WPS_PIN", argv.pinCode); + EXPECT_TRUE(mInterface->wpaCliCmdWpsPin(mInterface, &argv, &pinCode) == 0); + EXPECT_TRUE(pinCode == 87654321); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdWpsCancelTest, TestSize.Level1) +{ + MockEraseSupportedCmd("WPS_CANCEL"); + EXPECT_TRUE(mInterface->wpaCliCmdWpsCancel(mInterface) < 0); + MockSetWpaExpectCmdResponse("WPS_CANCEL", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdWpsCancel(mInterface) < 0); + MockSetWpaExpectCmdResponse("WPS_CANCEL", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdWpsCancel(mInterface) == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdPowerSaveTest, TestSize.Level1) +{ + MockEraseSupportedCmd("SET"); + EXPECT_TRUE(mInterface->wpaCliCmdPowerSave(mInterface, 0) < 0); + MockSetWpaExpectCmdResponse("SET", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdPowerSave(mInterface, 0) < 0); + MockSetWpaExpectCmdResponse("SET", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdPowerSave(mInterface, 0) == 0); + EXPECT_TRUE(mInterface->wpaCliCmdPowerSave(mInterface, 1) == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdSetCountryCodeTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaCliCmdSetCountryCode(mInterface, nullptr) < 0); + MockEraseSupportedCmd("SET"); + EXPECT_TRUE(mInterface->wpaCliCmdSetCountryCode(mInterface, "CN") < 0); + MockSetWpaExpectCmdResponse("SET", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdSetCountryCode(mInterface, "CN") < 0); + MockSetWpaExpectCmdResponse("SET", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdSetCountryCode(mInterface, "CN") == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdGetCountryCodeTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaCliCmdGetCountryCode(mInterface, nullptr, 0) < 0); + char countryCode[3] = {0}; + int codeSize = 3; + MockEraseSupportedCmd("GET"); + EXPECT_TRUE(mInterface->wpaCliCmdGetCountryCode(mInterface, countryCode, codeSize) < 0); + MockSetWpaExpectCmdResponse("GET", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdGetCountryCode(mInterface, countryCode, codeSize) < 0); + MockSetWpaExpectCmdResponse("GET", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdGetCountryCode(mInterface, countryCode, codeSize) == 0); + EXPECT_TRUE(strcmp(countryCode, "OK") == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdSetAutoConnectTest, TestSize.Level1) +{ + MockEraseSupportedCmd("STA_AUTOCONNECT"); + EXPECT_TRUE(mInterface->wpaCliCmdSetAutoConnect(mInterface, 0) < 0); + MockSetWpaExpectCmdResponse("STA_AUTOCONNECT", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdSetAutoConnect(mInterface, 0) < 0); + MockSetWpaExpectCmdResponse("STA_AUTOCONNECT", "OK"); + EXPECT_TRUE(mInterface->wpaCliCmdSetAutoConnect(mInterface, 0) == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdWpaBlockListClearTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaCliCmdWpaBlockListClear(mInterface) < 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdListNetworksTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaCliCmdListNetworks(mInterface, nullptr, nullptr) < 0); + HidlNetworkInfo a[256]; + ASSERT_TRUE(memset_s(a, sizeof(a), 0, sizeof(a)) == EOK); + int size = 256; + MockEraseSupportedCmd("LIST_NETWORKS"); + EXPECT_TRUE(mInterface->wpaCliCmdListNetworks(mInterface, a, &size) < 0); + char buf[] = "network id / ssid / bssid / flags\n" + "1\tssid1\t00:xx:xx:xx:xx:00\t[DISABLED]\n" + "2\tssid2\tany\t[DISABLED]\n" + "3\tssid3\t00:00:00:00:00:00\t[CURRENT]\n" + "4\tssid4\tany\t[DISABLED]\n"; + MockSetWpaExpectCmdResponse("LIST_NETWORKS", buf); + EXPECT_TRUE(mInterface->wpaCliCmdListNetworks(mInterface, a, &size) == 0); + EXPECT_TRUE(size == 4); + size = 2; + EXPECT_TRUE(mInterface->wpaCliCmdListNetworks(mInterface, a, &size) == 0); + EXPECT_TRUE(size == 2); + EXPECT_TRUE(a[0].id == 1); + EXPECT_TRUE(strcmp(a[0].ssid, "ssid1") == 0); + EXPECT_TRUE(strcmp(a[0].bssid, "00:xx:xx:xx:xx:00") == 0); + EXPECT_TRUE(strcmp(a[0].flags, "[DISABLED]") == 0); + EXPECT_TRUE(a[1].id == 2); + EXPECT_TRUE(strcmp(a[1].ssid, "ssid2") == 0); + EXPECT_TRUE(strcmp(a[1].bssid, "any") == 0); + EXPECT_TRUE(strcmp(a[1].flags, "[DISABLED]") == 0); +} + +HWTEST_F(WifiHalWpaStaTest, WpaCliCmdGetSignalInfoTest, TestSize.Level1) +{ + EXPECT_TRUE(mInterface->wpaCliCmdGetSignalInfo(mInterface, nullptr) < 0); + HidlWpaSignalInfo info; + ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); + EXPECT_TRUE(mInterface->wpaCliCmdGetSignalInfo(mInterface, &info) == 0); + MockEraseSupportedCmd("SIGNAL_POLL"); + EXPECT_TRUE(mInterface->wpaCliCmdGetSignalInfo(mInterface, &info) < 0); + MockSetWpaExpectCmdResponse("SIGNAL_POLL", "FAIL\n"); + EXPECT_TRUE(mInterface->wpaCliCmdGetSignalInfo(mInterface, &info) < 0); + char buf[] = "RSSI=-86\nLINKSPEED=1024\nNOISE=128\nFREQUENCY=5555\n"; + MockSetWpaExpectCmdResponse("SIGNAL_POLL", buf); + EXPECT_TRUE(mInterface->wpaCliCmdGetSignalInfo(mInterface, &info) == 0); + EXPECT_TRUE(info.signal == -86); + EXPECT_TRUE(info.txrate == 1024); + EXPECT_TRUE(info.noise == 128); + EXPECT_TRUE(info.frequency == 5555); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.h b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.h new file mode 100644 index 000000000..978138bc6 --- /dev/null +++ b/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.h @@ -0,0 +1,40 @@ +/* + * 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_WIFI_HAL_WPA_STA_TEST_H +#define OHOS_WIFI_HAL_WPA_STA_TEST_H + +#include +#include "server.h" +#include "wifi_supplicant_hal.h" +#include "wifi_wpa_hal.h" + +namespace OHOS { +namespace Wifi { +class WifiHalWpaStaTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + virtual void SetUp() + {} + virtual void TearDown() + {} + + static WifiWpaInterface *mGlobalInterface; + static WifiWpaStaInterface *mInterface; + static RpcServer *mServer; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file