Skip to content

Commit

Permalink
util: add unit tests for CIDRFromMask()
Browse files Browse the repository at this point in the history
  • Loading branch information
satta authored and victorjulien committed Apr 30, 2022
1 parent 394356f commit 5ec6f3b
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/runmode-unittests.c
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ static void RegisterUnittests(void)
SourceWinDivertRegisterTests();
#endif
SCProtoNameRegisterTests();
UtilCIDRTests();
}
#endif

Expand Down
59 changes: 59 additions & 0 deletions src/util-cidr.c
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

#include "suricata-common.h"
#include "util-cidr.h"
#include "util-unittest.h"

/** \brief turn 32 bit mask into CIDR
* \retval cidr cidr value or -1 if the netmask can't be expressed as cidr
Expand Down Expand Up @@ -94,3 +95,61 @@ void CIDRGetIPv6(int cidr, struct in6_addr *in6)
in6->s6_addr[i] = in6->s6_addr[i] >> 1;
}
}

#ifdef UNITTESTS

static int CIDRFromMaskTest01(void)
{
struct in_addr in;
int v = inet_pton(AF_INET, "255.255.255.0", &in);

FAIL_IF(v <= 0);
FAIL_IF_NOT(24 == CIDRFromMask(in.s_addr));

PASS;
}

static int CIDRFromMaskTest02(void)
{
struct in_addr in;
int v = inet_pton(AF_INET, "255.255.0.42", &in);

FAIL_IF(v <= 0);
FAIL_IF_NOT(-1 == CIDRFromMask(in.s_addr));

PASS;
}

static int CIDRFromMaskTest03(void)
{
struct in_addr in;
int v = inet_pton(AF_INET, "0.0.0.0", &in);

FAIL_IF(v <= 0);
FAIL_IF_NOT(0 == CIDRFromMask(in.s_addr));

PASS;
}

static int CIDRFromMaskTest04(void)
{
struct in_addr in;
int v = inet_pton(AF_INET, "255.255.255.255", &in);

FAIL_IF(v <= 0);
FAIL_IF_NOT(32 == CIDRFromMask(in.s_addr));

PASS;
}

#endif /* UNITTESTS */

void UtilCIDRTests(void)
{
#ifdef UNITTESTS
UtRegisterTest("CIDRFromMaskTest01", CIDRFromMaskTest01);
UtRegisterTest("CIDRFromMaskTest02", CIDRFromMaskTest02);
UtRegisterTest("CIDRFromMaskTest03", CIDRFromMaskTest03);
UtRegisterTest("CIDRFromMaskTest04", CIDRFromMaskTest04);
#endif /* UNITTESTS */
}
2 changes: 2 additions & 0 deletions src/util-cidr.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,7 @@ int CIDRFromMask(uint32_t netmask);
uint32_t CIDRGet(int);
void CIDRGetIPv6(int cidr, struct in6_addr *in6);

void UtilCIDRTests(void);

#endif /* __UTIL_NETMASK_H__ */

0 comments on commit 5ec6f3b

Please sign in to comment.