jeudi 31 janvier 2019

How to perform string validation & unit testing using google test in C++?

I am trying to write some string validation functions such as

  • check whether the string is NULL, Empty or have only spaces!

  • check whether the string is alphanumeric or uppercase!

I am only interested in strings with lowercase alphabets from a-z.(VALID strings) rest I want to block, so I have written the following functions:

std::string isEmpty(const std::string &input){
    // empty string
    if (NULL ==input || input=="\0" || !input.size())
        return "";
}
std::string isMalfunctioned(const std::string &input){
    for (int i = 0; i < input.size(); ++i){
        // string is not a-z or alphanumeric or uppercase
        if ( input[i] < 'a' || input[i] > 'z'|| isalpha(input[i]) || isupper(input[i]) )
            return "";
    }
}

and from the main function, I am just calling myFunc() using a reference to the input string & it calls the validation function written above to notify a user of incoming invalid strings:

#include"myFunc.h"

std::string myFunc(const std::string & input){
    if( isEmpty(input)== "")
        std::cout<<"Empty input"<< std::endl;
    if( isMalfunctioned(input)== "")
        std::cout<<"malfunctioned input"<< std::endl;
    return input;
}
int main(){
    std::string input="1234";
    std::cout << myFunc(input)<< std::endl;
    return  0;
}

My question:

  • First, I think my validation functions are not syntaticaly correct, since I am getting compile time errors as below, could anyone help in this regards?

mismatched types ‘const __gnu_cxx::__normal_iterator<_
Iterator, _Container>’ and ‘long int’

candidate: template<class _Iterator,
 class _Container> bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator<_Iterat
or, _Container>&, const __gnu_cxx::__normal_iterator<_Iterator, _Container>&)
     operator==(const __normal_iterator<_Iterator, _Container>& __lhs,

  • Second, I think, my validation functions are not fully covering my specifications. Any suggestion for it?

  • Third, I have written some test cases using google test, but unable to interface with the above functionality, Any suggestions on what I am doing wrong & how to correct them? Also, any suggestion on refactoring the code is also welcomed!


#include "myfunc.h"
#include <gtest/gtest.h>

TEST(testbundle, EmptyString){
  ASSERT_EQ("", myfunc(""));
}

TEST(testbundle, Malfunctioned){
  ASSERT_EQ("", myfunc("ad34534654"));
  ASSERT_EQ("", myfunc("!$#sadasfd1"));
}

TEST(testbundle, LowerCase){
  ASSERT_EQ("abbsbdbbdbdb", myfunc("abbsbdbbdbdb"));
}
TEST(PreliminaryTest, UpperCaseString){
  ASSERT_EQ("", myfunc("ASDFFGGGHH"));
}

int main(int argc, char **argv){
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Aucun commentaire:

Enregistrer un commentaire