summaryrefslogtreecommitdiff
path: root/vendor/bandit/bandit/assertion_frameworks/snowhouse/snowhouse/constraints/containsconstraint.h
blob: f20d680049333ef21ee8028b10fdb7b3e00a126e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//          Copyright Joakim Karlsson & Kim Gräsman 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef IGLOO_CONTAINSCONSTRAINT_H
#define IGLOO_CONTAINSCONSTRAINT_H

#include <algorithm>

#include "./expressions/expression.h"

namespace snowhouse {
  
  template <typename ContainerType>
  struct find_in_container_traits
  {
    template <typename ExpectedType>
    static bool find(const ContainerType& container, const ExpectedType& expected)
    {
      return std::find(container.begin(), container.end(), expected) != container.end();
    }
  };
  
  template <typename KeyType, typename ValueType>
  struct find_in_container_traits<std::map<KeyType, ValueType> >
  {
    template <typename ExpectedType>
    static bool find(const std::map<KeyType, ValueType>& container, const ExpectedType& expected)
    {
      return container.find(expected) != container.end();
    }
  };
  
  template <typename ExpectedType>
  struct ContainsConstraint : Expression< ContainsConstraint<ExpectedType> >
  {
    ContainsConstraint(const ExpectedType& expected) 
    : m_expected(expected) {}
    
    template <typename ActualType>
    bool operator()(const ActualType& actual) const
    {
      return find_in_container_traits<ActualType>::find(actual, m_expected);
    } 
    
    bool operator()(const std::string& actual) const
    {
      return actual.find(m_expected) != actual.npos; 
    }   
    
    ExpectedType m_expected;
  };              

  template< typename ExpectedType >
  inline ContainsConstraint<ExpectedType> Contains(const ExpectedType& expected)
  {
    return ContainsConstraint<ExpectedType>(expected);
  }        
  
  inline ContainsConstraint<std::string> Contains(const char* expected)
  {
    return ContainsConstraint<std::string>(expected);
  }
  
  template< typename ExpectedType >
  struct Stringizer< ContainsConstraint< ExpectedType > >
  {
    static std::string ToString(const ContainsConstraint<ExpectedType>& constraint)
    {
      std::ostringstream builder;
	  builder << "contains " << snowhouse::Stringize(constraint.m_expected);

      return builder.str();
    }
  };
}

#endif