add unittest code

Signed-off-by: zhangfeng <hw.zhangfeng@huawei.com>
This commit is contained in:
zhangfeng 2021-09-23 02:29:29 +00:00
parent 61027849f7
commit 03cda74abb
318 changed files with 39443 additions and 508 deletions

View File

@ -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"
]
},

View File

@ -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;
}

View File

@ -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

View File

@ -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};

View File

@ -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();

View File

@ -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

View File

@ -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)
{

View File

@ -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
*

View File

@ -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",

View File

@ -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

View File

@ -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 <getopt.h>
#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], "<interface>", "network interface name.", "--ifname eth0", 1, PutArgument},
{&longOptions[NUM_ONE], "<file>", "configure file name.", "--conf /etc/conf/dhcp_server.conf", 0, PutArgument},
{&longOptions[NUM_TWO], "<dns1>[,dns2][,dns3][...]", "domain name server IP address list.", "", 0, PutArgument},
{&longOptions[NUM_THREE], "<gateway>", "gateway option.", "", 0, PutIpArgument},
{&longOptions[NUM_FOUR], "<server>", "server identifier.", "", 1, PutIpArgument},
{&longOptions[NUM_FIVE], "<netmask>", "default subnet mask.", "", 1, PutIpArgument},
{&longOptions[NUM_SIX], "<beginip>,<endip>", "pool address range.", "", 0,
PutPoolArgument},
{&longOptions[NUM_SEVEN], "<leaseTime>", "set lease time value, the value is in units of seconds.", "", 0,
PutArgument},
{&longOptions[NUM_EIGHT], "<renewalTime>", "set renewal time value, the value is in units of seconds.", "", 0,
PutArgument},
{&longOptions[NUM_NINE], "<rebindingTime>", "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);
}

View File

@ -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], "<interface>", "network interface name.", "--ifname eth0", 1, PutArgument},
{&longOptions[NUM_ONE], "<file>", "configure file name.", "--conf /etc/conf/dhcp_server.conf", 0, PutArgument},
{&longOptions[NUM_TWO], "<dns1>[,dns2][,dns3][...]", "domain name server IP address list.", "", 0, PutArgument},
{&longOptions[NUM_THREE], "<gateway>", "gateway option.", "", 0, PutIpArgument},
{&longOptions[NUM_FOUR], "<server>", "server identifier.", "", 1, PutIpArgument},
{&longOptions[NUM_FIVE], "<netmask>", "default subnet mask.", "", 1, PutIpArgument},
{&longOptions[NUM_SIX], "<beginip>,<endip>", "pool address range.", "", 0,
PutPoolArgument},
{&longOptions[NUM_SEVEN], "<leaseTime>", "set lease time value, the value is in units of seconds.", "", 0,
PutArgument},
{&longOptions[NUM_EIGHT], "<renewalTime>", "set renewal time value, the value is in units of seconds.", "", 0,
PutArgument},
{&longOptions[NUM_NINE], "<rebindingTime>", "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) {

View File

@ -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!");

View File

@ -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;

View File

@ -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

View File

@ -1135,7 +1135,10 @@ WifiErrorNo WifiIdlClient::ReqP2pListNetworks(std::map<int, WifiP2pGroupInfo> &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);

View File

@ -74,7 +74,7 @@ bool ApStationsManager::EnableAllBlockList() const
bool ret = true;
for (std::vector<StationInfo>::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<StationInfo> 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<StationInfo> 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<int>(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;
}

View File

@ -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;

View File

@ -22,6 +22,7 @@
namespace OHOS {
namespace Wifi {
class ScanInterface : public IScanService {
FRIEND_GTEST(ScanInterface);
public:
ScanInterface();
~ScanInterface();

View File

@ -25,6 +25,7 @@
namespace OHOS {
namespace Wifi {
class ScanMonitor {
FRIEND_GTEST(ScanMonitor);
public:
ScanMonitor();
~ScanMonitor();

View File

@ -15,6 +15,8 @@
#include <inttypes.h>
#include "scan_service.h"
#include "wifi_logger.h"
#include "wifi_settings.h"
#include "wifi_sta_hal_interface.h"
DEFINE_WIFILOG_SCAN_LABEL("ScanService");

View File

@ -20,9 +20,7 @@
#include <ctime>
#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 &params);
virtual ErrCode ScanWithParam(const WifiScanParams &params);
/**
* @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<int, StoreScanConfig>;

View File

@ -1528,7 +1528,7 @@ bool ScanStateMachine::GetScanInfos(std::vector<InterScanInfo> &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.");

View File

@ -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

View File

@ -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");
}

View File

@ -21,7 +21,6 @@
#include <unordered_map>
#include <vector>
#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<InterScanInfo> &scanInfos);
virtual void OnScanInfosReadyHandler(const std::vector<InterScanInfo> &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<InterScanInfo> &scanInfos,
virtual ErrCode AutoSelectDevice(WifiDeviceConfig &electedDevice, const std::vector<InterScanInfo> &scanInfos,
std::vector<std::string> &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;

View File

@ -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

View File

@ -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 {

View File

@ -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) {

View File

@ -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;

View File

@ -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");

View File

@ -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.

View File

@ -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;

View File

@ -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()

View File

@ -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;

View File

@ -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");

View File

@ -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<InterScanInfo> &scanInfos);
virtual ErrCode AutoConnectService(const std::vector<InterScanInfo> &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:

View File

@ -14,13 +14,19 @@
*/
#include "sta_state_machine.h"
#include <cstdio>
#include <random>
#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"

View File

@ -21,16 +21,14 @@
#include <vector>
#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();

View File

@ -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);

View File

@ -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" ]
}

View File

@ -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

View File

@ -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 <gtest/gtest.h>
#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

View File

@ -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

View File

@ -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 <gtest/gtest.h>
#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

View File

@ -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

View File

@ -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 <gtest/gtest.h>
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

View File

@ -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 <gtest/gtest.h>
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();
}

View File

@ -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

View File

@ -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 <gtest/gtest.h>
#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

View File

@ -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" ]
}

View File

@ -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 <gtest/gtest.h>
int main(int argc, char *argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -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<int>(DhcpIpType::DHCP_IPTYPE_IPV4);
std::vector<WifiConfig> 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<int>(WifiDeviceConfigStatus::ENABLED);
tmp.bssid = "01:xx:xx:xx:xx:06";
tmp.ssid = "my wifi";
tmp.band = static_cast<int>(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<WifiDeviceConfig> 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<HotspotConfig> 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<StationInfo> 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<WifiP2pGroupInfo> &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<WifiP2pGroupInfo> &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<WifiP2pGroupInfo> 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<P2pGroupCapability>(vec.at(1).GetClientDevices().at(1).GetGroupCapabilitys()));
}
} // namespace Wifi
} // namespace OHOS

View File

@ -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 <gtest/gtest.h>
#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<WifiConfig> mWifiCfg;
WifiConfigFileImpl<WifiDeviceConfig> mDeviceCfg;
WifiConfigFileImpl<HotspotConfig> mHotspotCfg;
WifiConfigFileImpl<StationInfo> mBlockCfg;
WifiConfigFileImpl<WifiP2pGroupInfo> mWifiP2pGroupInfo;
};
} // namespace Wifi
} // namespace OHOS
#endif

View File

@ -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<BandType> 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<BandType> 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<std::string> 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<char> 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

View File

@ -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 <gtest/gtest.h>
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

View File

@ -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 <net/if.h>
#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<unsigned char> 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<unsigned char> 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<std::string> 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

View File

@ -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 <gtest/gtest.h>
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

View File

@ -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

View File

@ -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 <gtest/gtest.h>
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

View File

@ -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<Ipv4Address> vecIPv4;
std::vector<Ipv6Address> 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<Ipv4Address> 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<Ipv6Address> vecIpv6;
EXPECT_TRUE(NetworkInterface::GetAllIpv6Address("wlan0", vecIpv6) == true);
EXPECT_TRUE(NetworkInterface::ClearAllIpAddress("wlan0") == true);
}
} // namespace Wifi
} // namespace OHOS

View File

@ -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 <gtest/gtest.h>
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

View File

@ -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" ]
}

View File

@ -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 <gtest/gtest.h>
#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

View File

@ -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 <gtest/gtest.h>
#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

View File

@ -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 <gtest/gtest.h>
#include <sys/stat.h>
#include <fcntl.h>
#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

View File

@ -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 <gtest/gtest.h>
#include <gmock/gmock.h>
#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();
}

View File

@ -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 <gtest/gtest.h>
#include "wifi_log.h"
#include "dhcp_options.h"
#include "dhcp_client.h"
#include "securec.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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

View File

@ -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 <gtest/gtest.h>
#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

View File

@ -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");
}

View File

@ -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<gtest/gtest.h>
class GlobalTest : public testing::Environment {
public:
virtual void SetUp();
virtual void TearDown();
};
#endif

View File

@ -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

View File

@ -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 <gmock/gmock.h>
#include <dlfcn.h>
#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

View File

@ -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

View File

@ -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 <gmock/gmock.h>
#include <dlfcn.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
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

View File

@ -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" ]
}

View File

@ -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 <gtest/gtest.h>
#include <stdint.h>
#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));
}

View File

@ -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 <gtest/gtest.h>
#include <stdint.h>
#include <stdbool.h>
#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);
}

View File

@ -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 <gtest/gtest.h>
#include <string>
#include <securec.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#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<char *>(""),
const_cast<char *>("--dns=192.168.1.1,192.168.1.2"),
const_cast<char *>("--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);
}

View File

@ -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 <gtest/gtest.h>
#include <string>
#include <securec.h>
#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);
}

View File

@ -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 <gtest/gtest.h>
#include <string>
#include <securec.h>
#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);
}

View File

@ -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 <stdio.h>
#include <stdint.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <fcntl.h>
#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;
}

View File

@ -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 <queue>
#include <mutex>
#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<DhcpMessage> m_recvMessages;
std::mutex m_sendQueueLocker;
std::queue<DhcpMessage> 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

View File

@ -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 <gtest/gtest.h>
#include <stdint.h>
#include <stdbool.h>
#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);
}

View File

@ -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 <gtest/gtest.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <thread>
#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);
}

View File

@ -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 <gtest/gtest.h>
#include <stdint.h>
#include <stdbool.h>
#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));
}

View File

@ -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 <stdint.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#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);
}
}

View File

@ -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 <gmock/gmock.h>
#include <stdint.h>
#include <dlfcn.h>
#include <sys/socket.h>
#include <unistd.h>
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

View File

@ -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" ]
}

View File

@ -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 <gtest/gtest.h>
#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<DhcpClientServiceImpl>();
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<DhcpClientServiceImpl> 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);
}

View File

@ -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 <gtest/gtest.h>
#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);
}

View File

@ -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 <gtest/gtest.h>
#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();
}

View File

@ -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 <iostream>
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

View File

@ -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;
/**
* @Descriptionasyn 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;
/**
* @Descriptionasyn 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

View File

@ -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 <gtest/gtest.h>
#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<DhcpServerService>();
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<DhcpServerService> 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<std::string> vecLeases;
EXPECT_EQ(DHCP_OPT_SUCCESS, pServerService->GetLeases(ifname, vecLeases));
ASSERT_TRUE(DhcpFunc::RemoveFile(strFile));
}

View File

@ -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 <gtest/gtest.h>
#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<DhcpService>();
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<IDhcpService> 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<std::string> 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));
}

View File

@ -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");
}

View File

@ -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 <gtest/gtest.h>
class GlobalTest : public testing::Environment {
public:
virtual void SetUp();
virtual void TearDown();
};
#endif

View File

@ -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

View File

@ -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 <gmock/gmock.h>
#include <dlfcn.h>
#include <sys/types.h>
#include <sys/socket.h>
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

Some files were not shown because too many files have changed in this diff Show More