Home | History | Annotate | Download | only in testing
      1 // Copyright 2006 The RE2 Authors.  All Rights Reserved.
      2 // Use of this source code is governed by a BSD-style
      3 // license that can be found in the LICENSE file.
      4 
      5 // Test parse.cc, dump.cc, and tostring.cc.
      6 
      7 #include <string>
      8 #include <vector>
      9 #include "util/test.h"
     10 #include "re2/regexp.h"
     11 
     12 namespace re2 {
     13 
     14 // Test that overflowed ref counts work.
     15 TEST(Regexp, BigRef) {
     16   Regexp* re;
     17   re = Regexp::Parse("x", Regexp::NoParseFlags, NULL);
     18   for (int i = 0; i < 100000; i++)
     19     re->Incref();
     20   for (int i = 0; i < 100000; i++)
     21     re->Decref();
     22   CHECK_EQ(re->Ref(), 1);
     23   re->Decref();
     24 }
     25 
     26 // Test that very large Concats work.
     27 // Depends on overflowed ref counts working.
     28 TEST(Regexp, BigConcat) {
     29   Regexp* x;
     30   x = Regexp::Parse("x", Regexp::NoParseFlags, NULL);
     31   vector<Regexp*> v(90000, x);  // ToString bails out at 100000
     32   for (int i = 0; i < v.size(); i++)
     33     x->Incref();
     34   CHECK_EQ(x->Ref(), 1 + v.size()) << x->Ref();
     35   Regexp* re = Regexp::Concat(&v[0], v.size(), Regexp::NoParseFlags);
     36   CHECK_EQ(re->ToString(), string(v.size(), 'x'));
     37   re->Decref();
     38   CHECK_EQ(x->Ref(), 1) << x->Ref();
     39   x->Decref();
     40 }
     41 
     42 TEST(Regexp, NamedCaptures) {
     43   Regexp* x;
     44   RegexpStatus status;
     45   x = Regexp::Parse(
     46       "(?P<g1>a+)|(e)(?P<g2>w*)+(?P<g1>b+)", Regexp::PerlX, &status);
     47   EXPECT_TRUE(status.ok());
     48   EXPECT_EQ(4, x->NumCaptures());
     49   const map<string, int>* have = x->NamedCaptures();
     50   EXPECT_TRUE(have != NULL);
     51   EXPECT_EQ(2, have->size());  // there are only two named groups in
     52                                // the regexp: 'g1' and 'g2'.
     53   map<string, int> want;
     54   want["g1"] = 1;
     55   want["g2"] = 3;
     56   EXPECT_EQ(want, *have);
     57   x->Decref();
     58   delete have;
     59 }
     60 
     61 TEST(Regexp, CaptureNames) {
     62   Regexp* x;
     63   RegexpStatus status;
     64   x = Regexp::Parse(
     65       "(?P<g1>a+)|(e)(?P<g2>w*)+(?P<g1>b+)", Regexp::PerlX, &status);
     66   EXPECT_TRUE(status.ok());
     67   EXPECT_EQ(4, x->NumCaptures());
     68   const map<int, string>* have = x->CaptureNames();
     69   EXPECT_TRUE(have != NULL);
     70   EXPECT_EQ(3, have->size());
     71   map<int, string> want;
     72   want[1] = "g1";
     73   want[3] = "g2";
     74   want[4] = "g1";
     75 
     76   EXPECT_EQ(want, *have);
     77   x->Decref();
     78   delete have;
     79 }
     80 
     81 }  // namespace re2
     82