<commit_before>#!/usr/bin/env python

"""
"""
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.node import RemoteController
from mininet.node import Node
from mininet.node import CPULimitedHost
from mininet.link import TCLink
from mininet.cli import CLI
from mininet.log import setLogLevel
from mininet.util import dumpNodeConnections

class AttMplsTopo( Topo ):
    "Internet Topology Zoo Specimen."

    def __init__( self ):
        "Create a topology."

        # Initialize Topology
        Topo.__init__( self )

        # add nodes, switches first...
        NY54 = self.addSwitch( 's25' ) // 40.728270, -73.994483
        CMBR = self.addSwitch( 's1' )  // 42.373730, -71.109734
        CHCG = self.addSwitch( 's2' )  // 41.877461, -87.642892
        CLEV = self.addSwitch( 's3' )  // 41.498928, -81.695217
        RLGH = self.addSwitch( 's4' )  // 35.780150, -78.644026
        ATLN = self.addSwitch( 's5' )  // 33.749017, -84.394168
        PHLA = self.addSwitch( 's6' )  // 39.952906, -75.172278
        WASH = self.addSwitch( 's7' )  // 38.906696, -77.035509
        NSVL = self.addSwitch( 's8' )  // 36.166410, -86.787305
        STLS = self.addSwitch( 's9' )  // 38.626418, -90.198143
        NWOR = self.addSwitch( 's10' ) // 29.951475, -90.078434
        HSTN = self.addSwitch( 's11' ) // 29.763249, -95.368332
        SNAN = self.addSwitch( 's12' ) // 29.424331, -98.491745
        DLLS = self.addSwitch( 's13' ) // 32.777665, -96.802064
        ORLD = self.addSwitch( 's14' ) // 28.538641, -81.381110
        DNVR = self.addSwitch( 's15' ) // 39.736623, -104.984887
        KSCY = self.addSwitch( 's16' ) // 39.100725, -94.581228
        SNFN = self.addSwitch( 's17' ) // 37.779751, -122.409791
        SCRM = self.addSwitch( 's18' ) // 38.581001, -121.497844
        PTLD = self.addSwitch( 's19' ) // 45.523317, -122.677768
        STTL = self.addSwitch( 's20' ) // 47.607326, -122.331786
        SLKC = self.addSwitch( 's21' ) // 40.759577, -111.895079
        LA03 = self.addSwitch( 's22' ) // 34.056346, -118.235951
        SNDG = self.addSwitch( 's23' ) // 32.714564, -117.153528
        PHNX = self.addSwitch( 's24' ) // 33.448289, -112.076299

        # ... and now hosts
        NY54_host = self.addHost( 'h25' )
        CMBR_host = self.addHost( 'h1' )
        CHCG_host = self.addHost( 'h2' )
        CLEV_host = self.addHost( 'h3' )
        RLGH_host = self.addHost( 'h4' )
        ATLN_host = self.addHost( 'h5' )
        PHLA_host = self.addHost( 'h6' )
        WASH_host = self.addHost( 'h7' )
        NSVL_host = self.addHost( 'h8' )
        STLS_host = self.addHost( 'h9' )
        NWOR_host = self.addHost( 'h10' )
        HSTN_host = self.addHost( 'h11' )
        SNAN_host = self.addHost( 'h12' )
        DLLS_host = self.addHost( 'h13' )
        ORLD_host = self.addHost( 'h14' )
        DNVR_host = self.addHost( 'h15' )
        KSCY_host = self.addHost( 'h16' )
        SNFN_host = self.addHost( 'h17' )
        SCRM_host = self.addHost( 'h18' )
        PTLD_host = self.addHost( 'h19' )
        STTL_host = self.addHost( 'h20' )
        SLKC_host = self.addHost( 'h21' )
        LA03_host = self.addHost( 'h22' )
        SNDG_host = self.addHost( 'h23' )
        PHNX_host = self.addHost( 'h24' )

        # add edges between switch and corresponding host
        self.addLink( NY54 , NY54_host )
        self.addLink( CMBR , CMBR_host )
        self.addLink( CHCG , CHCG_host )
        self.addLink( CLEV , CLEV_host )
        self.addLink( RLGH , RLGH_host )
        self.addLink( ATLN , ATLN_host )
        self.addLink( PHLA , PHLA_host )
        self.addLink( WASH , WASH_host )
        self.addLink( NSVL , NSVL_host )
        self.addLink( STLS , STLS_host )
        self.addLink( NWOR , NWOR_host )
        self.addLink( HSTN , HSTN_host )
        self.addLink( SNAN , SNAN_host )
        self.addLink( DLLS , DLLS_host )
        self.addLink( ORLD , ORLD_host )
        self.addLink( DNVR , DNVR_host )
        self.addLink( KSCY , KSCY_host )
        self.addLink( SNFN , SNFN_host )
        self.addLink( SCRM , SCRM_host )
        self.addLink( PTLD , PTLD_host )
        self.addLink( STTL , STTL_host )
        self.addLink( SLKC , SLKC_host )
        self.addLink( LA03 , LA03_host )
        self.addLink( SNDG , SNDG_host )
        self.addLink( PHNX , PHNX_host )

        # add edges between switches
        self.addLink( NY54 , CMBR, bw=10, delay='0.979030824185ms')
        self.addLink( NY54 , CHCG, bw=10, delay='0.806374975652ms')
        self.addLink( NY54 , PHLA, bw=10, delay='0.686192970166ms')
        self.addLink( NY54 , WASH, bw=10, delay='0.605826192092ms')
        self.addLink( CMBR , PHLA, bw=10, delay='1.4018238197ms')
        self.addLink( CHCG , CLEV, bw=10, delay='0.232315346482ms')
        self.addLink( CHCG , PHLA, bw=10, delay='1.07297714274ms')
        self.addLink( CHCG , STLS, bw=10, delay='1.12827896944ms')
        self.addLink( CHCG , DNVR, bw=10, delay='1.35964770335ms')
        self.addLink( CHCG , KSCY, bw=10, delay='1.5199778541ms')
        self.addLink( CHCG , SNFN, bw=10, delay='0.620743405435ms')
        self.addLink( CHCG , STTL, bw=10, delay='0.93027212534ms')
        self.addLink( CHCG , SLKC, bw=10, delay='0.735621751348ms')
        self.addLink( CLEV , NSVL, bw=10, delay='0.523419372248ms')
        self.addLink( CLEV , STLS, bw=10, delay='1.00360290845ms')
        self.addLink( CLEV , PHLA, bw=10, delay='0.882912133249ms')
        self.addLink( RLGH , ATLN, bw=10, delay='1.1644489729ms')
        self.addLink( RLGH , WASH, bw=10, delay='1.48176810502ms')
        self.addLink( ATLN , WASH, bw=10, delay='0.557636936322ms')
        self.addLink( ATLN , NSVL, bw=10, delay='1.32869749865ms')
        self.addLink( ATLN , STLS, bw=10, delay='0.767705554748ms')
        self.addLink( ATLN , DLLS, bw=10, delay='0.544782086448ms')
        self.addLink( ATLN , ORLD, bw=10, delay='1.46119152532ms')
        self.addLink( PHLA , WASH, bw=10, delay='0.372209320106ms')
        self.addLink( NSVL , STLS, bw=10, delay='1.43250491305ms')
        self.addLink( NSVL , DLLS, bw=10, delay='1.67698215288ms')
        self.addLink( STLS , DLLS, bw=10, delay='0.256389964194ms')
        self.addLink( STLS , KSCY, bw=10, delay='0.395511571791ms')
        self.addLink( STLS , LA03, bw=10, delay='0.257085227363ms')
        self.addLink( NWOR , HSTN, bw=10, delay='0.0952906633914ms')
        self.addLink( NWOR , DLLS, bw=10, delay='1.60231329739ms')
        self.addLink( NWOR , ORLD, bw=10, delay='0.692731063896ms')
        self.addLink( HSTN , SNAN, bw=10, delay='0.284150653798ms')
        self.addLink( HSTN , DLLS, bw=10, delay='1.65690128332ms')
        self.addLink( HSTN , ORLD, bw=10, delay='0.731886304782ms')
        self.addLink( SNAN , PHNX, bw=10, delay='1.34258627257ms')
        self.addLink( SNAN , DLLS, bw=10, delay='1.50063532341ms')
        self.addLink( DLLS , DNVR, bw=10, delay='0.251471593235ms')
        self.addLink( DLLS , KSCY, bw=10, delay='0.18026026737ms')
        self.addLink( DLLS , SNFN, bw=10, delay='0.74304274592ms')
        self.addLink( DLLS , LA03, bw=10, delay='0.506439293357ms')
        self.addLink( DNVR , KSCY, bw=10, delay='0.223328790403ms')
        self.addLink( DNVR , SNFN, bw=10, delay='0.889017541903ms')
        self.addLink( DNVR , SLKC, bw=10, delay='0.631898982721ms')
        self.addLink( KSCY , SNFN, bw=10, delay='0.922778522233ms')
        self.addLink( SNFN , SCRM, bw=10, delay='0.630352278097ms')
        self.addLink( SNFN , PTLD, bw=10, delay='0.828572513655ms')
        self.addLink( SNFN , STTL, bw=10, delay='1.54076081649ms')
        self.addLink( SNFN , SLKC, bw=10, delay='0.621507502625ms')
        self.addLink( SNFN , LA03, bw=10, delay='0.602936230151ms')
        self.addLink( SCRM , SLKC, bw=10, delay='0.461350343644ms')
        self.addLink( PTLD , STTL, bw=10, delay='1.17591515181ms')
        self.addLink( SLKC , LA03, bw=10, delay='0.243225267023ms')
        self.addLink( LA03 , SNDG, bw=10, delay='0.681264950821ms')
        self.addLink( LA03 , PHNX, bw=10, delay='0.343709457969ms')
        # self.addLink( LA03 , PHNX, bw=10, delay='0.343709457969ms')
        self.addLink( SNDG , PHNX, bw=10, delay='0.345064487693ms')

topos = { 'att': ( lambda: AttMplsTopo() ) }
<commit_msg>Fixed issue in the att-mpls.py mininet script.<commit_after>#!/usr/bin/env python

"""
"""
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.node import RemoteController
from mininet.node import Node
from mininet.node import CPULimitedHost
from mininet.link import TCLink
from mininet.cli import CLI
from mininet.log import setLogLevel
from mininet.util import dumpNodeConnections

class AttMplsTopo( Topo ):
    "Internet Topology Zoo Specimen."

    def __init__( self ):
        "Create a topology."

        # Initialize Topology
        Topo.__init__( self )

        # add nodes, switches first...
        NY54 = self.addSwitch( 's25' ) # 40.728270, -73.994483
        CMBR = self.addSwitch( 's1' )  # 42.373730, -71.109734
        CHCG = self.addSwitch( 's2' )  # 41.877461, -87.642892
        CLEV = self.addSwitch( 's3' )  # 41.498928, -81.695217
        RLGH = self.addSwitch( 's4' )  # 35.780150, -78.644026
        ATLN = self.addSwitch( 's5' )  # 33.749017, -84.394168
        PHLA = self.addSwitch( 's6' )  # 39.952906, -75.172278
        WASH = self.addSwitch( 's7' )  # 38.906696, -77.035509
        NSVL = self.addSwitch( 's8' )  # 36.166410, -86.787305
        STLS = self.addSwitch( 's9' )  # 38.626418, -90.198143
        NWOR = self.addSwitch( 's10' ) # 29.951475, -90.078434
        HSTN = self.addSwitch( 's11' ) # 29.763249, -95.368332
        SNAN = self.addSwitch( 's12' ) # 29.424331, -98.491745
        DLLS = self.addSwitch( 's13' ) # 32.777665, -96.802064
        ORLD = self.addSwitch( 's14' ) # 28.538641, -81.381110
        DNVR = self.addSwitch( 's15' ) # 39.736623, -104.984887
        KSCY = self.addSwitch( 's16' ) # 39.100725, -94.581228
        SNFN = self.addSwitch( 's17' ) # 37.779751, -122.409791
        SCRM = self.addSwitch( 's18' ) # 38.581001, -121.497844
        PTLD = self.addSwitch( 's19' ) # 45.523317, -122.677768
        STTL = self.addSwitch( 's20' ) # 47.607326, -122.331786
        SLKC = self.addSwitch( 's21' ) # 40.759577, -111.895079
        LA03 = self.addSwitch( 's22' ) # 34.056346, -118.235951
        SNDG = self.addSwitch( 's23' ) # 32.714564, -117.153528
        PHNX = self.addSwitch( 's24' ) # 33.448289, -112.076299

        # ... and now hosts
        NY54_host = self.addHost( 'h25' )
        CMBR_host = self.addHost( 'h1' )
        CHCG_host = self.addHost( 'h2' )
        CLEV_host = self.addHost( 'h3' )
        RLGH_host = self.addHost( 'h4' )
        ATLN_host = self.addHost( 'h5' )
        PHLA_host = self.addHost( 'h6' )
        WASH_host = self.addHost( 'h7' )
        NSVL_host = self.addHost( 'h8' )
        STLS_host = self.addHost( 'h9' )
        NWOR_host = self.addHost( 'h10' )
        HSTN_host = self.addHost( 'h11' )
        SNAN_host = self.addHost( 'h12' )
        DLLS_host = self.addHost( 'h13' )
        ORLD_host = self.addHost( 'h14' )
        DNVR_host = self.addHost( 'h15' )
        KSCY_host = self.addHost( 'h16' )
        SNFN_host = self.addHost( 'h17' )
        SCRM_host = self.addHost( 'h18' )
        PTLD_host = self.addHost( 'h19' )
        STTL_host = self.addHost( 'h20' )
        SLKC_host = self.addHost( 'h21' )
        LA03_host = self.addHost( 'h22' )
        SNDG_host = self.addHost( 'h23' )
        PHNX_host = self.addHost( 'h24' )

        # add edges between switch and corresponding host
        self.addLink( NY54 , NY54_host )
        self.addLink( CMBR , CMBR_host )
        self.addLink( CHCG , CHCG_host )
        self.addLink( CLEV , CLEV_host )
        self.addLink( RLGH , RLGH_host )
        self.addLink( ATLN , ATLN_host )
        self.addLink( PHLA , PHLA_host )
        self.addLink( WASH , WASH_host )
        self.addLink( NSVL , NSVL_host )
        self.addLink( STLS , STLS_host )
        self.addLink( NWOR , NWOR_host )
        self.addLink( HSTN , HSTN_host )
        self.addLink( SNAN , SNAN_host )
        self.addLink( DLLS , DLLS_host )
        self.addLink( ORLD , ORLD_host )
        self.addLink( DNVR , DNVR_host )
        self.addLink( KSCY , KSCY_host )
        self.addLink( SNFN , SNFN_host )
        self.addLink( SCRM , SCRM_host )
        self.addLink( PTLD , PTLD_host )
        self.addLink( STTL , STTL_host )
        self.addLink( SLKC , SLKC_host )
        self.addLink( LA03 , LA03_host )
        self.addLink( SNDG , SNDG_host )
        self.addLink( PHNX , PHNX_host )

        # add edges between switches
        self.addLink( NY54 , CMBR, bw=10, delay='0.979030824185ms')
        self.addLink( NY54 , CHCG, bw=10, delay='0.806374975652ms')
        self.addLink( NY54 , PHLA, bw=10, delay='0.686192970166ms')
        self.addLink( NY54 , WASH, bw=10, delay='0.605826192092ms')
        self.addLink( CMBR , PHLA, bw=10, delay='1.4018238197ms')
        self.addLink( CHCG , CLEV, bw=10, delay='0.232315346482ms')
        self.addLink( CHCG , PHLA, bw=10, delay='1.07297714274ms')
        self.addLink( CHCG , STLS, bw=10, delay='1.12827896944ms')
        self.addLink( CHCG , DNVR, bw=10, delay='1.35964770335ms')
        self.addLink( CHCG , KSCY, bw=10, delay='1.5199778541ms')
        self.addLink( CHCG , SNFN, bw=10, delay='0.620743405435ms')
        self.addLink( CHCG , STTL, bw=10, delay='0.93027212534ms')
        self.addLink( CHCG , SLKC, bw=10, delay='0.735621751348ms')
        self.addLink( CLEV , NSVL, bw=10, delay='0.523419372248ms')
        self.addLink( CLEV , STLS, bw=10, delay='1.00360290845ms')
        self.addLink( CLEV , PHLA, bw=10, delay='0.882912133249ms')
        self.addLink( RLGH , ATLN, bw=10, delay='1.1644489729ms')
        self.addLink( RLGH , WASH, bw=10, delay='1.48176810502ms')
        self.addLink( ATLN , WASH, bw=10, delay='0.557636936322ms')
        self.addLink( ATLN , NSVL, bw=10, delay='1.32869749865ms')
        self.addLink( ATLN , STLS, bw=10, delay='0.767705554748ms')
        self.addLink( ATLN , DLLS, bw=10, delay='0.544782086448ms')
        self.addLink( ATLN , ORLD, bw=10, delay='1.46119152532ms')
        self.addLink( PHLA , WASH, bw=10, delay='0.372209320106ms')
        self.addLink( NSVL , STLS, bw=10, delay='1.43250491305ms')
        self.addLink( NSVL , DLLS, bw=10, delay='1.67698215288ms')
        self.addLink( STLS , DLLS, bw=10, delay='0.256389964194ms')
        self.addLink( STLS , KSCY, bw=10, delay='0.395511571791ms')
        self.addLink( STLS , LA03, bw=10, delay='0.257085227363ms')
        self.addLink( NWOR , HSTN, bw=10, delay='0.0952906633914ms')
        self.addLink( NWOR , DLLS, bw=10, delay='1.60231329739ms')
        self.addLink( NWOR , ORLD, bw=10, delay='0.692731063896ms')
        self.addLink( HSTN , SNAN, bw=10, delay='0.284150653798ms')
        self.addLink( HSTN , DLLS, bw=10, delay='1.65690128332ms')
        self.addLink( HSTN , ORLD, bw=10, delay='0.731886304782ms')
        self.addLink( SNAN , PHNX, bw=10, delay='1.34258627257ms')
        self.addLink( SNAN , DLLS, bw=10, delay='1.50063532341ms')
        self.addLink( DLLS , DNVR, bw=10, delay='0.251471593235ms')
        self.addLink( DLLS , KSCY, bw=10, delay='0.18026026737ms')
        self.addLink( DLLS , SNFN, bw=10, delay='0.74304274592ms')
        self.addLink( DLLS , LA03, bw=10, delay='0.506439293357ms')
        self.addLink( DNVR , KSCY, bw=10, delay='0.223328790403ms')
        self.addLink( DNVR , SNFN, bw=10, delay='0.889017541903ms')
        self.addLink( DNVR , SLKC, bw=10, delay='0.631898982721ms')
        self.addLink( KSCY , SNFN, bw=10, delay='0.922778522233ms')
        self.addLink( SNFN , SCRM, bw=10, delay='0.630352278097ms')
        self.addLink( SNFN , PTLD, bw=10, delay='0.828572513655ms')
        self.addLink( SNFN , STTL, bw=10, delay='1.54076081649ms')
        self.addLink( SNFN , SLKC, bw=10, delay='0.621507502625ms')
        self.addLink( SNFN , LA03, bw=10, delay='0.602936230151ms')
        self.addLink( SCRM , SLKC, bw=10, delay='0.461350343644ms')
        self.addLink( PTLD , STTL, bw=10, delay='1.17591515181ms')
        self.addLink( SLKC , LA03, bw=10, delay='0.243225267023ms')
        self.addLink( LA03 , SNDG, bw=10, delay='0.681264950821ms')
        self.addLink( LA03 , PHNX, bw=10, delay='0.343709457969ms')
        # self.addLink( LA03 , PHNX, bw=10, delay='0.343709457969ms')
        self.addLink( SNDG , PHNX, bw=10, delay='0.345064487693ms')

topos = { 'att': ( lambda: AttMplsTopo() ) }
<|endoftext|>


<commit_before>#  Copyright 2008 Nokia Siemens Networks Oyj
#
#  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.

# TODO: assertions, checks, generate html and check, write internal tests

import os
import re
import shutil
import time
import fnmatch
import glob
from types import ListType
from types import StringType

from robot import utils
from robot.errors import DataError
import robot.output
from random import Random
import string

class String:

    """This library contains keywords related to string operations."""

    ROBOT_LIBRARY_SCOPE = 'GLOBAL'

    def get_first_line(self, lines):
        """

      Returns the first line of input: head -1
        """
        line_list = lines.splitlines(0)
        print "*INFO* Got '%d' lines" % len(line_list)
        if line_list:
            return line_list[0]
        return ''

    def get_second_part_of_lines_after_string(self, lines, split_string):
        """
        Splits each line using split_with, returns second part
        Like awk -F 'split_with' '{print $2}'
        Only lines containing requested string are taken.
        """
        result_lines=''
        line_list = lines.splitlines(0)
        for line in line_list:
            # include only lines which contain requested string
            if (split_string in line):
                splitLine = line.split(split_string)
                result_lines += splitLine[1] + '\n'
        return result_lines

    def get_head_lines_as_list(self, lines, line_count):
        """
        Returns the first line_count lines of input: head -line_count
        as a list
        """
        line_count = int(line_count)
        line_list = lines.splitlines(0)
        print "*INFO* Got '%d' lines" % len(line_list)
        if line_list:
            return line_list[0 : (line_count)]
        return ''

    def get_line_count(self, lines):
        """
      Returns the number of lines.
        """
        line_list = lines.splitlines(0)
        print "*INFO* Got '%d' lines" % len(line_list)
        line_count = len(line_list)
        return line_count

    def get_last_line(self, lines):
        """
        Returns the last line of input
        """
        line_list = lines.splitlines(0)
        print "*INFO* Got '%d' lines" % len(line_list)
        if line_list:
            return line_list[- 1]
        return ""

    def get_all_but_last_line_as_list(self, lines):
        """
        Returns list of all but the last line of input
        """
        line_list = lines.splitlines(0)
        print "*INFO* Got '%d' lines" % len(line_list)
        line_count = len(line_list)
        if line_list:
            return line_list[0 : line_count - 1]
        return []

    def get_all_but_last_line(self, lines):
        """
        Returns all but the last line of input as string (cuts out the last line)
        """
        line_list = lines.splitlines(0)
        all_but_last = "";
        print "*INFO* Got '%d' lines" % len(line_list)
        line_count = len(line_list)
        if (line_count < 2): return ""
        for i in range (0, line_count - 1):
        	all_but_last += line_list[i] + "\n"
        return all_but_last

    def get_lines_as_list(self, lines, remove_empty_lines = 0):
        """
        Converts multiline input to list of lines. Ends of lines removed.
        If removeEmptyLines != 0, empty lines are removed
        """
        line_list = lines.splitlines(0)
        print "*INFO* Got '%d' lines" % len(line_list)
        line_count = len(line_list)
        if (line_count == 0): return list()
        if (remove_empty_lines):
            line_list = self._remove_empty_elements_from_list(line_list)
        return line_list

    def _remove_empty_elements_from_list(self, elements):
        """
        Removes empty elements from list. Returns list.
        """
        newelements = []
        for element in elements:
            if element:
                newelement.append(element)
        return newelements

    def split_to_last_line_and_rest(self, lines):
        """
        Splits multiline input to all_but_last and last line.
        Returns a list [last_line, all_but_last_line]
        Used for getting RC and output from the command executed via SSH, RC being the last line.
        """
        line_list = lines.splitlines(0)
        line_count = len(line_list)

        # just last line. Return list of [last line, '']
        if (line_count == 1):
            result_list = []
            result_list.append(line_list[0])
            result_list.append('')
            return result_list

        last_line = line_list[-1]
        # if line before last is empty, remove it - comes from additional \n in the echo
        if (line_list [line_count-2] == ""): line_count = line_count - 1
        all_but_last = ""
        for i in range (0, line_count - 1):
            all_but_last += line_list[i] + "\n"
        result_list = [last_line, all_but_last]
        return result_list

    def add_crlf_to_all_lines(self, lines):
        """
        Adds \\r\\n to all lines
        """

        result_lines = ''
        # replace CRLF with LF (in case there's some inside)
        result_lines = lines.replace('\r\n','\n')
        result_lines = result_lines.replace('\n','\r\n')
        return result_lines

    def replace_string(self, replace_in, search_for, replace_with):
        """
        Searches search_for in replace_in and replaces with replace_with)
        """
        result = replace_in.replace(search_for, replace_with)
        return result

    def convert_list_to_csv(self, convert_list):
        """
        Converts a list of elements to comma-separated element string
        ['a','b','c'] => 'a,b,c'
        """
        result = ''
        if isinstance(convert_list, StringType):
            tempList = []
            tempList.append(convert_list)
            convert_list = tempList
        for listElement in convert_list:
            result += listElement + ","
        result = result[0 : -1]
        #result = result.rstrip(',')
        return result

    def convert_csv_to_list(self, csv_string):
        """
        Converts a comma-separated element string to a list of elements
        'a,b,c' => ['a','b','c']
        """
        result = csv_string.split(',')
        return result

    def split_string(self, to_split, split_with):
        """
        Split to_split, divided by split_with
        """
        result = to_split.split(split_with)
        return result

    def get_lines_not_matching_any_of_elements(self, to_match, to_exclude):
        """
        This keyword returns to_match without lines where any of to_exclude is a substring.
        """
        result_lines = ""
        some_matches = 0
        to_matchList = to_match.splitlines(0)
        for line_to_match in to_matchList:
            some_matches = 0
            for line_to_exclude in to_exclude:
                # check if is a substring
                if (line_to_exclude in line_to_match):
                    some_matches = 1
            if not (some_matches): result_lines = line_to_match + "\n"
        return result_lines

    def generate_random_string(self, length=8, chars=string.letters + string.digits):
        """
            Generates a random string of the required length (8 by default).
            Second argument is a set of characters to draw from, letters + digits for default
        """
        length = int(length)
        src_len = len(chars)
        times = int(length / src_len)
        result = ''
        for i in range (0, times):
            result += ''.join( Random().sample(chars, src_len) )
        rest = length % src_len
        result += ''.join(Random().sample(chars, rest) )
        return result

    def get_substring(self, string, left_index, right_index):
        """
        Returns a substring from left_index to right_index, which should be numbers (0, len-1)
        """
        return string[int(left_index) : int(right_index)]

<commit_msg>String.py: new keywords: should (not) be a string, is a string, get column<commit_after>#  Copyright 2008 Nokia Siemens Networks Oyj
#
#  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.

# TODO: assertions, checks, generate html and check, write internal tests

import os
import re
import shutil
import time
import fnmatch
import glob
from types import ListType
from types import StringType

from robot import utils
from robot.errors import DataError
import robot.output
from random import Random
import string

class String:

    """This library contains keywords related to string operations."""

    ROBOT_LIBRARY_SCOPE = 'GLOBAL'

    def get_first_line(self, lines):
        """

      Returns the first line of input: head -1
        """
        line_list = lines.splitlines(0)
        print "*INFO* Got '%d' lines" % len(line_list)
        if line_list:
            return line_list[0]
        return ''

    def get_second_part_of_lines_after_string(self, lines, split_string):
        """
        Splits each line using split_with, returns second part
        Like awk -F 'split_with' '{print $2}'
        Only lines containing requested string are taken.
        """
        result_lines=''
        line_list = lines.splitlines(0)
        for line in line_list:
            # include only lines which contain requested string
            if (split_string in line):
                splitLine = line.split(split_string)
                result_lines += splitLine[1] + '\n'
        return result_lines

    def get_head_lines_as_list(self, lines, line_count):
        """
        Returns the first line_count lines of input: head -line_count
        as a list
        """
        line_count = int(line_count)
        line_list = lines.splitlines(0)
        print "*INFO* Got '%d' lines" % len(line_list)
        if line_list:
            return line_list[0 : (line_count)]
        return ''

    def get_line_count(self, lines):
        """
      Returns the number of lines.
        """
        line_list = lines.splitlines(0)
        print "*INFO* Got '%d' lines" % len(line_list)
        line_count = len(line_list)
        return line_count

    def get_last_line(self, lines):
        """
        Returns the last line of input
        """
        line_list = lines.splitlines(0)
        print "*INFO* Got '%d' lines" % len(line_list)
        if line_list:
            return line_list[- 1]
        return ""

    def get_all_but_last_line_as_list(self, lines):
        """
        Returns list of all but the last line of input
        """
        line_list = lines.splitlines(0)
        print "*INFO* Got '%d' lines" % len(line_list)
        line_count = len(line_list)
        if line_list:
            return line_list[0 : line_count - 1]
        return []

    def get_all_but_last_line(self, lines):
        """
        Returns all but the last line of input as string (cuts out the last line)
        """
        line_list = lines.splitlines(0)
        all_but_last = "";
        print "*INFO* Got '%d' lines" % len(line_list)
        line_count = len(line_list)
        if (line_count < 2): return ""
        for i in range (0, line_count - 1):
        	all_but_last += line_list[i] + "\n"
        return all_but_last

    def get_lines_as_list(self, lines, remove_empty_lines = 0):
        """
        Converts multiline input to list of lines. Ends of lines removed.
        If removeEmptyLines != 0, empty lines are removed
        """
        line_list = lines.splitlines(0)
        print "*INFO* Got '%d' lines" % len(line_list)
        line_count = len(line_list)
        if (line_count == 0): return list()
        if (remove_empty_lines):
            line_list = self._remove_empty_elements_from_list(line_list)
        return line_list

    def _remove_empty_elements_from_list(self, elements):
        """
        Removes empty elements from list. Returns list.
        """
        newelements = []
        for element in elements:
            if element:
                newelement.append(element)
        return newelements

    def split_to_last_line_and_rest(self, lines):
        """
        Splits multiline input to all_but_last and last line.
        Returns a list [last_line, all_but_last_line]
        Used for getting RC and output from the command executed via SSH, RC being the last line.
        """
        line_list = lines.splitlines(0)
        line_count = len(line_list)

        # just last line. Return list of [last line, '']
        if (line_count == 1):
            result_list = []
            result_list.append(line_list[0])
            result_list.append('')
            return result_list

        last_line = line_list[-1]
        # if line before last is empty, remove it
        # - comes from additional \n in the echo
        if (line_list [line_count-2] == ""): line_count = line_count - 1
        all_but_last = ""
        for i in range (0, line_count - 1):
            all_but_last += line_list[i] + "\n"
        result_list = [last_line, all_but_last]
        return result_list

    def add_crlf_to_all_lines(self, lines):
        """
        Adds \\r\\n to all lines
        """

        result_lines = ''
        # replace CRLF with LF (in case there's some inside)
        result_lines = lines.replace('\r\n','\n')
        result_lines = result_lines.replace('\n','\r\n')
        return result_lines

    def replace_string(self, replace_in, search_for, replace_with):
        """
        Searches search_for in replace_in and replaces with replace_with)
        """
        result = replace_in.replace(search_for, replace_with)
        return result

    def convert_list_to_csv(self, convert_list):
        """
        Converts a list of elements to comma-separated element string
        ['a','b','c'] => 'a,b,c'
        """
        result = ''
        if isinstance(convert_list, StringType):
            tempList = []
            tempList.append(convert_list)
            convert_list = tempList
        for listElement in convert_list:
            result += listElement + ","
        result = result[0 : -1]
        #result = result.rstrip(',')
        return result

    def convert_csv_to_list(self, csv_string):
        """
        Converts a comma-separated element string to a list of elements
        'a,b,c' => ['a','b','c']
        """
        result = csv_string.split(',')
        return result

    def split_string(self, to_split, split_with):
        """
        Split to_split, divided by split_with
        """
        result = to_split.split(split_with)
        return result

    def get_lines_not_matching_any_of_elements(self, to_match, to_exclude):
        """
        This keyword returns to_match without lines
        where any of to_exclude is a substring.
        """
        result_lines = ""
        some_matches = 0
        to_matchList = to_match.splitlines(0)
        for line_to_match in to_matchList:
            some_matches = 0
            for line_to_exclude in to_exclude:
                # check if is a substring
                if (line_to_exclude in line_to_match):
                    some_matches = 1
            if not (some_matches): result_lines = line_to_match + "\n"
        return result_lines

    def generate_random_string(self, length=8, chars=string.letters + string.digits):
        """
            Generates a random string of the required length (8 by default).
            Second argument is a set of characters to draw from,
            letters + digits for default
        """
        length = int(length)
        src_len = len(chars)
        times = int(length / src_len)
        result = ''
        for i in range (0, times):
            result += ''.join( Random().sample(chars, src_len) )
        rest = length % src_len
        result += ''.join(Random().sample(chars, rest) )
        return result

    def get_substring(self, string, left_index, right_index):
        """
        Returns a substring from left_index to right_index,
        which should be numbers (0, len-1)
        """
        return string[int(left_index) : int(right_index)]

    def is_a_string(self, item):
        """ Checks whether item is a string. Returns true or false"""
        if isinstance(item, basestring):
            print "*INFO* is a string '%s' lines" % item
            return True
        return False

    def should_be_a_string(self, item, msg=None):
        """ Fails if item is not a string (e.g. list, number)"""
        if not (self.is_a_string(item)):
            if msg is None:
                msg = "Given item is not a string"
            raise AssertionError(msg)

    def should_not_be_a_string(self, item, msg=None):
        """ Fails if item is a string (e.g. list, number)"""
        if (self.is_a_string(item)):
            if msg is None:
                msg = "Given item '%s' is a string" % item
            raise AssertionError(msg)

    def get_column(self, input_text, column_number, delimiter=' '):
        """
        Takes input text, splits into columns using delimiter
        and returns the column_number column.
        Column numbering starts from 1. Default delimiter is single space.
        """
        if (not delimiter):
            raise AssertionError("Delimiter should not be empty")

        lines = input_text.splitlines(0)
        column = ''

        column_number = int(column_number - 1)
        for line in lines:
            row = line.split(delimiter)
            try:
                item = row[column_number]
            except IndexError:
                item = ''
            column += item + '\n'
        return column
<|endoftext|>


<commit_before>#  Copyright 2008-2009 Nokia Siemens Networks Oyj
#
#  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 os
import sys

from robot import utils
from robot.errors import DataError

class _Metadata:

    def __init__(self, metadata=None):
        self._data = {}
        for name in self._names.values():
            self._data[name.replace(' ','')] = None
        if metadata is not None:
            for item in metadata:
                self.set(item)

    def set(self, item):
        try:
            name = self._names[utils.normalize(item.name)].replace(' ', '')
        except KeyError:
            self._report_invalid_meta(item)
        else:
            if self._data[name] is None:
                self._data[name] = item.value
            else:
                self._data[name].extend(item.value)

    def _report_invalid_meta(self, item):
        name = self.__class__.__name__.replace('Metadata','')
        name = utils.printable_name(name, code_style=True)
        available = self._get_available_names()
        msg = "%s does not have metadata '%s'. Available: %s"
        item.report_invalid_syntax(msg % (name, item.name, available))

    def _get_available_names(self):
        names = dict([ (name, 1) for name in self._names.values() ]).keys()
        names.sort()
        return utils.seq2str(names)

    def get(self, key, default=None):
        value = self._data[key]
        if value is None:
            return default
        if key == 'Documentation':
            return ' '.join(value)
        return value

    def __getitem__(self, key):
        return self.get(key)

class TestCaseMetadata(_Metadata):
    _names = { 'documentation': 'Documentation',
               'document': 'Documentation',
               'setup': 'Setup',
               'precondition': 'Setup',
               'teardown': 'Teardown',
               'postcondition': 'Teardown',
               'tags': 'Tags',
               'timeout': 'Timeout' }

class UserKeywordMetadata(_Metadata):
    _names = { 'documentation': 'Documentation',
               'document': 'Documentation',
               'arguments': 'Arguments',
               'return': 'Return',
               'timeout': 'Timeout' }

class TestSuiteMetadata(_Metadata):
    _names = { 'documentation': 'Documentation',
               'document': 'Documentation',
               'suitesetup': 'Suite Setup',
               'suiteprecondition': 'Suite Setup',
               'suiteteardown': 'Suite Teardown',
               'suitepostcondition': 'Suite Teardown',
               'testsetup': 'Test Setup',
               'testprecondition': 'Test Setup',
               'testteardown': 'Test Teardown',
               'testpostcondition': 'Test Teardown',
               'defaulttags': 'Default Tags',
               'forcetags': 'Force Tags',
               'testtimeout': 'Test Timeout' }

    def __init__(self, rawdata=None):
        _Metadata.__init__(self)
        self.user_metadata = {}
        self.imports = []
        if rawdata is not None:
            self._set_rawdata(rawdata)

    def _set_rawdata(self, rawdata):
        for item in rawdata.settings:
            name = item.name.lower()
            if name in ['library', 'resource', 'variables']:
                self.imports.append(ImportSetting(item))
            elif name.startswith('meta:'):
                self._set_user_metadata(item.name[5:].strip(), item.value)
            else:
                self.set(item)

    def _set_user_metadata(self, name, value):
        name = utils.printable_name(name)
        value = ' '.join(value)
        if self.user_metadata.has_key(name):
            value = '%s %s' % (self.user_metadata[name], value)
        self.user_metadata[name] = value

class ImportSetting:

    def __init__(self, item):
        self._item = item
        self.name = item.name = utils.normalize(item.name).capitalize()
        self.value = None

    def replace_variables(self, variables):
        item = self._item.copy()
        try:
            self.value = variables.replace_list(item.value)
        except DataError, err:
            raise DataError("Replacing variables from setting '%s' failed: %s"
                            % (self.name, str(err)))
        if len(self.value) == 0:
            raise DataError("Setting '%s' requires a value" % self.name)
        if self.name == 'Resource' and len(self.value) > 1:
            raise DataError('Invalid resource import parameters: %s' % utils.seq2str2(self.value))
        basedir = utils.get_directory(item._parent._source)
        self.value[0] = self._get_path(self.name, self.value[0], basedir)

    def _get_path(self, name, path, basedir):
        if name == 'Library' and not self._is_library_by_path(path, basedir):
            return path
        try:
            path = self._resolve_path(path.replace('/', os.sep), basedir)
        except DataError:
            if name == 'Variables': name = 'Variable file'
            if name == 'Resource': name = 'Resource file'
            raise DataError("%s '%s' does not exist" % (name, path))
        if name in ['Variables','Library']:
            dirname, filename = os.path.split(os.path.normpath(path))
            path = os.path.join(utils.normpath(dirname), filename)
        else:
            path = utils.normpath(path)
        return path

    def _is_library_by_path(self, path, basedir):
        if os.path.splitext(path)[1].lower() in ['.py','.java','.class']:
            return os.path.isfile(os.path.join(basedir, path))
        if not path.endswith('/'):
            return False
        init = os.path.join(basedir, path.replace('/',os.sep), '__init__.py')
        return os.path.isfile(init)

    def _resolve_path(self, respath, basedir):
        for base in [basedir] + sys.path:
            if not os.path.isdir(base):
                continue
            path = os.path.join(base, respath)
            if os.path.exists(path):
                return path
        raise DataError()

    def report_invalid_syntax(self):
        self._item.report_invalid_syntax()
<commit_msg>whitespace<commit_after>#  Copyright 2008-2009 Nokia Siemens Networks Oyj
#
#  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 os
import sys

from robot import utils
from robot.errors import DataError

class _Metadata:

    def __init__(self, metadata=None):
        self._data = {}
        for name in self._names.values():
            self._data[name.replace(' ','')] = None
        if metadata is not None:
            for item in metadata:
                self.set(item)

    def set(self, item):
        try:
            name = self._names[utils.normalize(item.name)].replace(' ', '')
        except KeyError:
            self._report_invalid_meta(item)
        else:
            if self._data[name] is None:
                self._data[name] = item.value
            else:
                self._data[name].extend(item.value)

    def _report_invalid_meta(self, item):
        name = self.__class__.__name__.replace('Metadata','')
        name = utils.printable_name(name, code_style=True)
        available = self._get_available_names()
        msg = "%s does not have metadata '%s'. Available: %s"
        item.report_invalid_syntax(msg % (name, item.name, available))

    def _get_available_names(self):
        names = dict([ (name, 1) for name in self._names.values() ]).keys()
        names.sort()
        return utils.seq2str(names)

    def get(self, key, default=None):
        value = self._data[key]
        if value is None:
            return default
        if key == 'Documentation':
            return ' '.join(value)
        return value

    def __getitem__(self, key):
        return self.get(key)

class TestCaseMetadata(_Metadata):
    _names = { 'documentation': 'Documentation',
               'document': 'Documentation',
               'setup': 'Setup',
               'precondition': 'Setup',
               'teardown': 'Teardown',
               'postcondition': 'Teardown',
               'tags': 'Tags',
               'timeout': 'Timeout' }

class UserKeywordMetadata(_Metadata):
    _names = { 'documentation': 'Documentation',
               'document': 'Documentation',
               'arguments': 'Arguments',
               'return': 'Return',
               'timeout': 'Timeout' }

class TestSuiteMetadata(_Metadata):
    _names = { 'documentation': 'Documentation',
               'document': 'Documentation',
               'suitesetup': 'Suite Setup',
               'suiteprecondition': 'Suite Setup',
               'suiteteardown': 'Suite Teardown',
               'suitepostcondition': 'Suite Teardown',
               'testsetup': 'Test Setup',
               'testprecondition': 'Test Setup',
               'testteardown': 'Test Teardown',
               'testpostcondition': 'Test Teardown',
               'defaulttags': 'Default Tags',
               'forcetags': 'Force Tags',
               'testtimeout': 'Test Timeout' }

    def __init__(self, rawdata=None):
        _Metadata.__init__(self)
        self.user_metadata = {}
        self.imports = []
        if rawdata is not None:
            self._set_rawdata(rawdata)

    def _set_rawdata(self, rawdata):
        for item in rawdata.settings:
            name = item.name.lower()
            if name in ['library', 'resource', 'variables']:
                self.imports.append(ImportSetting(item))
            elif name.startswith('meta:'):
                self._set_user_metadata(item.name[5:].strip(), item.value)
            else:
                self.set(item)

    def _set_user_metadata(self, name, value):
        name = utils.printable_name(name)
        value = ' '.join(value)
        if self.user_metadata.has_key(name):
            value = '%s %s' % (self.user_metadata[name], value)
        self.user_metadata[name] = value

class ImportSetting:

    def __init__(self, item):
        self._item = item
        self.name = item.name = utils.normalize(item.name).capitalize()
        self.value = None

    def replace_variables(self, variables):
        item = self._item.copy()
        try:
            self.value = variables.replace_list(item.value)
        except DataError, err:
            raise DataError("Replacing variables from setting '%s' failed: %s"
                            % (self.name, str(err)))
        if len(self.value) == 0:
            raise DataError("Setting '%s' requires a value" % self.name)
        if self.name == 'Resource' and len(self.value) > 1:
            raise DataError('Invalid resource import parameters: %s' % utils.seq2str2(self.value))
        basedir = utils.get_directory(item._parent._source)
        self.value[0] = self._get_path(self.name, self.value[0], basedir)

    def _get_path(self, name, path, basedir):
        if name == 'Library' and not self._is_library_by_path(path, basedir):
            return path
        try:
            path = self._resolve_path(path.replace('/', os.sep), basedir)
        except DataError:
            if name == 'Variables': name = 'Variable file'
            if name == 'Resource': name = 'Resource file'
            raise DataError("%s '%s' does not exist" % (name, path))
        if name in ['Variables','Library']:
            dirname, filename = os.path.split(os.path.normpath(path))
            path = os.path.join(utils.normpath(dirname), filename)
        else:
            path = utils.normpath(path)
        return path

    def _is_library_by_path(self, path, basedir):
        if os.path.splitext(path)[1].lower() in ['.py','.java','.class']:
            return os.path.isfile(os.path.join(basedir, path))
        if not path.endswith('/'):
            return False
        init = os.path.join(basedir, path.replace('/',os.sep), '__init__.py')
        return os.path.isfile(init)

    def _resolve_path(self, respath, basedir):
        for base in [basedir] + sys.path:
            if not os.path.isdir(base):
                continue
            path = os.path.join(base, respath)
            if os.path.exists(path):
                return path
        raise DataError()

    def report_invalid_syntax(self):
        self._item.report_invalid_syntax()
<|endoftext|>


<commit_before>import json
import os

from django.test import TestCase, Client

from pdl.models import Proyecto
from pdl.models import Seguimientos
from pdl.models import Slug

class TestSearchAdvancedViews(TestCase):
    def setUp(self):
        self.maxDiff = None
        self.c = Client()

        this_folder = os.path.abspath(os.path.dirname(__file__))
        dummy_db_json = os.path.join(this_folder, '..', '..', 'pdl', 'tests', 'dummy_db.json')
        dummy_items = json.loads(open(dummy_db_json, 'r').read())

        for i in dummy_items:
            b = Proyecto(**i)
            b.save()
            s = Seguimientos(proyecto=b, fecha='2014-06-23',
                             evento='Decreado a... Ciencia, Innovación y Tecnología')
            s.save()

        Slug(nombre='Chihuan Ramos, Leyla Felicita', ascii='Chihuan Ramos, Leyla Felicita',
             slug='chihuan-ramos-leyla-felicita').save()

    def test_index(self):
        response = self.c.get('/search-advanced/')
        self.assertEqual(200, response.status_code)

    def test_index_form_invalid(self):
        response = self.c.get('/search-advanced/?date_from=hola&date_to=12%2F19%2F2014')
        self.assertEqual(200, response.status_code)

    def test_index_search_date(self):
        response = self.c.get('/search-advanced/?date_from=03%2F03%2F2015&date_to=07%2F02%2F2015')
        self.assertEqual(200, response.status_code)

    def test_index_search_comission(self):
        response = self.c.get('/search-advanced/?comision=Ciencia&grupo_parlamentario=--Escoger bancada--')
        self.assertTrue('arco y flecha' in str(response.content))

    def test_search_congresista(self):
        response = self.c.get('/search-advanced/?congresista=1&grupo_parlamentario=--Escoger bancada--')
        self.assertTrue('arco y flecha' in str(response.content))

    def test_search_bancada(self):
        response = self.c.get('/search-advanced/?grupo_parlamentario=Fujimorista')
        self.assertTrue('arco y flecha' in str(response.content))

    def test_numero_total_de_leyes(self):
        response = self.c.get('/search-advanced/?dictamen=NÚMERO TOTAL DE LEYES')
        self.assertEqual(200, response.status_code)

    def test_exonerados_dictamen(self):
        response = self.c.get('/search-advanced/?dictamen=Exonerados de dictamen')
        self.assertEqual(200, response.status_code)

    def test_numero_total_aprobados(self):
        response = self.c.get('/search-advanced/?dispensados_2da_votacion=TOTAL aprobados')
        self.assertEqual(200, response.status_code)

    def test_numero_total_dispensados(self):
        response = self.c.get('/search-advanced/?dispensados_2da_votacion=TOTAL dispensados')
        self.assertEqual(200, response.status_code)

    def test_dispensados_acuerdo_pleno(self):
        response = self.c.get('/search-advanced/?dispensados_2da_votacion=Dispensados por acuerdo del pleno')
        self.assertEqual(200, response.status_code)

    def test_dispensados_junta_portavoces(self):
        response = self.c.get('/search-advanced/?dispensados_2da_votacion=Dispensados por junta portavoces')
        self.assertEqual(200, response.status_code)

    def test_dispensados_otros(self):
        response = self.c.get('/search-advanced/?dispensados_2da_votacion=Otros proyectos dispensados')
        self.assertEqual(200, response.status_code)
<commit_msg>rm test search for bancada por ahora<commit_after>import json
import os

from django.test import TestCase, Client

from pdl.models import Proyecto
from pdl.models import Seguimientos
from pdl.models import Slug

class TestSearchAdvancedViews(TestCase):
    def setUp(self):
        self.maxDiff = None
        self.c = Client()

        this_folder = os.path.abspath(os.path.dirname(__file__))
        dummy_db_json = os.path.join(this_folder, '..', '..', 'pdl', 'tests', 'dummy_db.json')
        dummy_items = json.loads(open(dummy_db_json, 'r').read())

        for i in dummy_items:
            b = Proyecto(**i)
            b.save()
            s = Seguimientos(proyecto=b, fecha='2014-06-23',
                             evento='Decreado a... Ciencia, Innovación y Tecnología')
            s.save()

        Slug(nombre='Chihuan Ramos, Leyla Felicita', ascii='Chihuan Ramos, Leyla Felicita',
             slug='chihuan-ramos-leyla-felicita').save()

    def test_index(self):
        response = self.c.get('/search-advanced/')
        self.assertEqual(200, response.status_code)

    def test_index_form_invalid(self):
        response = self.c.get('/search-advanced/?date_from=hola&date_to=12%2F19%2F2014')
        self.assertEqual(200, response.status_code)

    def test_index_search_date(self):
        response = self.c.get('/search-advanced/?date_from=03%2F03%2F2015&date_to=07%2F02%2F2015')
        self.assertEqual(200, response.status_code)

    def test_index_search_comission(self):
        response = self.c.get('/search-advanced/?comision=Ciencia&grupo_parlamentario=--Escoger bancada--')
        self.assertTrue('arco y flecha' in str(response.content))

    def test_search_congresista(self):
        response = self.c.get('/search-advanced/?congresista=1&grupo_parlamentario=--Escoger bancada--')
        self.assertTrue('arco y flecha' in str(response.content))

    def test_numero_total_de_leyes(self):
        response = self.c.get('/search-advanced/?dictamen=NÚMERO TOTAL DE LEYES')
        self.assertEqual(200, response.status_code)

    def test_exonerados_dictamen(self):
        response = self.c.get('/search-advanced/?dictamen=Exonerados de dictamen')
        self.assertEqual(200, response.status_code)

    def test_numero_total_aprobados(self):
        response = self.c.get('/search-advanced/?dispensados_2da_votacion=TOTAL aprobados')
        self.assertEqual(200, response.status_code)

    def test_numero_total_dispensados(self):
        response = self.c.get('/search-advanced/?dispensados_2da_votacion=TOTAL dispensados')
        self.assertEqual(200, response.status_code)

    def test_dispensados_acuerdo_pleno(self):
        response = self.c.get('/search-advanced/?dispensados_2da_votacion=Dispensados por acuerdo del pleno')
        self.assertEqual(200, response.status_code)

    def test_dispensados_junta_portavoces(self):
        response = self.c.get('/search-advanced/?dispensados_2da_votacion=Dispensados por junta portavoces')
        self.assertEqual(200, response.status_code)

    def test_dispensados_otros(self):
        response = self.c.get('/search-advanced/?dispensados_2da_votacion=Otros proyectos dispensados')
        self.assertEqual(200, response.status_code)
<|endoftext|>


<commit_before>#  Copyright 2008-2015 Nokia Networks
#  Copyright 2016-     Robot Framework Foundation
#
#  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.

from copy import copy
import inspect

from robot.utils import (getdoc, getshortdoc, is_java_init, is_java_method,
                         is_list_like, normpath, printable_name,
                         split_tags_from_doc, type_name, unwrap)
from robot.errors import DataError
from robot.model import Tags

from .arguments import (ArgumentSpec, DynamicArgumentParser,
                        JavaArgumentCoercer, JavaArgumentParser,
                        PythonArgumentParser)
from .dynamicmethods import GetKeywordSource, GetKeywordTypes
from .librarykeywordrunner import (EmbeddedArgumentsRunner,
                                   LibraryKeywordRunner, RunKeywordRunner)
from .runkwregister import RUN_KW_REGISTER

def Handler(library, name, method):
    if RUN_KW_REGISTER.is_run_keyword(library.orig_name, name):
        return _RunKeywordHandler(library, name, method)
    if is_java_method(method):
        return _JavaHandler(library, name, method)
    else:
        return _PythonHandler(library, name, method)

def DynamicHandler(library, name, method, doc, argspec, tags=None):
    if RUN_KW_REGISTER.is_run_keyword(library.orig_name, name):
        return _DynamicRunKeywordHandler(library, name, method, doc, argspec, tags)
    return _DynamicHandler(library, name, method, doc, argspec, tags)

def InitHandler(library, method=None, docgetter=None):
    Init = _PythonInitHandler if not is_java_init(method) else _JavaInitHandler
    return Init(library, '__init__', method, docgetter)

class _RunnableHandler(object):

    def __init__(self, library, handler_name, handler_method, doc='', tags=None):
        self.library = library
        self._handler_name = handler_name
        self.name = self._get_name(handler_name, handler_method)
        self.arguments = self._parse_arguments(handler_method)
        self._method = self._get_initial_handler(library, handler_name,
                                                 handler_method)
        doc, tags_from_doc = split_tags_from_doc(doc or '')
        tags_from_attr = self._get_tags_from_attribute(handler_method)
        self._doc = doc
        self.tags = Tags(tuple(tags_from_doc) +
                         tuple(tags_from_attr) +
                         tuple(tags or ()))

    def _get_name(self, handler_name, handler_method):
        robot_name = getattr(handler_method, 'robot_name', None)
        name = robot_name or printable_name(handler_name, code_style=True)
        if not name:
            raise DataError('Keyword name cannot be empty.')
        return name

    def _parse_arguments(self, handler_method):
        raise NotImplementedError

    def _get_tags_from_attribute(self, handler_method):
        tags = getattr(handler_method, 'robot_tags', ())
        if not is_list_like(tags):
            raise DataError("Expected tags to be list-like, got %s."
                            % type_name(tags))
        return tags

    def _get_initial_handler(self, library, name, method):
        if library.scope.is_global:
            return self._get_global_handler(method, name)
        return None

    def resolve_arguments(self, args, variables=None):
        return self.arguments.resolve(args, variables)

    @property
    def doc(self):
        return self._doc

    @property
    def longname(self):
        return '%s.%s' % (self.library.name, self.name)

    @property
    def shortdoc(self):
        return getshortdoc(self.doc)

    @property
    def libname(self):
        return self.library.name

    @property
    def source(self):
        return self.library.source

    @property
    def lineno(self):
        return -1

    def create_runner(self, name):
        return LibraryKeywordRunner(self)

    def current_handler(self):
        if self._method:
            return self._method
        return self._get_handler(self.library.get_instance(), self._handler_name)

    def _get_global_handler(self, method, name):
        return method

    def _get_handler(self, lib_instance, handler_name):
        try:
            return getattr(lib_instance, handler_name)
        except AttributeError:
            # Occurs with old-style classes.
            if handler_name == '__init__':
                return None
            raise

class _PythonHandler(_RunnableHandler):

    def __init__(self, library, handler_name, handler_method):
        _RunnableHandler.__init__(self, library, handler_name, handler_method,
                                  getdoc(handler_method))

    def _parse_arguments(self, handler_method):
        return PythonArgumentParser().parse(handler_method, self.longname)

    @property
    def source(self):
        handler = self.current_handler()
        try:
            return normpath(inspect.getsourcefile(unwrap(handler)))
        except TypeError:
            return self.library.source

    @property
    def lineno(self):
        handler = self.current_handler()
        try:
            lines, start_lineno = inspect.getsourcelines(unwrap(handler))
        except (TypeError, OSError, IOError):
            return -1
        for increment, line in enumerate(lines):
            if line.strip().startswith('def '):
                return start_lineno + increment
        return start_lineno

class _JavaHandler(_RunnableHandler):

    def __init__(self, library, handler_name, handler_method):
        _RunnableHandler.__init__(self, library, handler_name, handler_method)
        signatures = self._get_signatures(handler_method)
        self._arg_coercer = JavaArgumentCoercer(signatures, self.arguments)

    def _parse_arguments(self, handler_method):
        signatures = self._get_signatures(handler_method)
        return JavaArgumentParser().parse(signatures, self.longname)

    def _get_signatures(self, handler):
        code_object = getattr(handler, 'im_func', handler)
        return code_object.argslist[:code_object.nargs]

    def resolve_arguments(self, args, variables=None):
        positional, named = self.arguments.resolve(args, variables,
                                                   dict_to_kwargs=True)
        arguments = self._arg_coercer.coerce(positional, named,
                                             dryrun=not variables)
        return arguments, []

class _DynamicHandler(_RunnableHandler):

    def __init__(self, library, handler_name, dynamic_method, doc='',
                 argspec=None, tags=None):
        self._argspec = argspec
        self._run_keyword_method_name = dynamic_method.name
        self._supports_kwargs = dynamic_method.supports_kwargs
        _RunnableHandler.__init__(self, library, handler_name,
                                  dynamic_method.method, doc, tags)
        self._source_info = None

    def _parse_arguments(self, handler_method):
        spec = DynamicArgumentParser().parse(self._argspec, self.longname)
        if not self._supports_kwargs:
            if spec.kwargs:
                raise DataError("Too few '%s' method parameters for **kwargs "
                                "support." % self._run_keyword_method_name)
            if spec.kwonlyargs:
                raise DataError("Too few '%s' method parameters for "
                                "keyword-only arguments support."
                                % self._run_keyword_method_name)
        get_keyword_types = GetKeywordTypes(self.library.get_instance())
        spec.types = get_keyword_types(self._handler_name)
        return spec

    @property
    def source(self):
        if self._source_info is None:
            self._source_info = self._get_source_info()
        return self._source_info[0]

    def _get_source_info(self):
        get_keyword_source = GetKeywordSource(self.library.get_instance())
        try:
            source = get_keyword_source(self._handler_name)
        except DataError as err:
            self.library.report_error(
                "Getting source information for keyword '%s' failed: %s"
                % (self.name, err.message), err.details
            )
            return None, -1
        if not source:
            return self.library.source, -1
        if ':' not in source:
            return source, -1
        path, lineno = source.rsplit(':', 1)
        try:
            return path or self.library.source, int(lineno)
        except ValueError:
            return source, -1

    @property
    def lineno(self):
        if self._source_info is None:
            self._source_info = self._get_source_info()
        return self._source_info[1]

    def resolve_arguments(self, arguments, variables=None):
        positional, named = self.arguments.resolve(arguments, variables)
        if not self._supports_kwargs:
            positional, named = self.arguments.map(positional, named)
        return positional, named

    def _get_handler(self, lib_instance, handler_name):
        runner = getattr(lib_instance, self._run_keyword_method_name)
        return self._get_dynamic_handler(runner, handler_name)

    def _get_global_handler(self, method, name):
        return self._get_dynamic_handler(method, name)

    def _get_dynamic_handler(self, runner, name):
        def handler(*positional, **kwargs):
            if self._supports_kwargs:
                return runner(name, positional, kwargs)
            else:
                return runner(name, positional)
        return handler

class _RunKeywordHandler(_PythonHandler):

    def create_runner(self, name):
        default_dry_run_keywords = ('name' in self.arguments.positional and
                                    self._args_to_process)
        return RunKeywordRunner(self, default_dry_run_keywords)

    @property
    def _args_to_process(self):
        return RUN_KW_REGISTER.get_args_to_process(self.library.orig_name,
                                                   self.name)

    def resolve_arguments(self, args, variables=None):
        args_to_process = self._args_to_process
        return self.arguments.resolve(args, variables, resolve_named=False,
                                      resolve_variables_until=args_to_process)

class _DynamicRunKeywordHandler(_DynamicHandler, _RunKeywordHandler):
    _parse_arguments = _RunKeywordHandler._parse_arguments
    resolve_arguments = _RunKeywordHandler.resolve_arguments

class _PythonInitHandler(_PythonHandler):

    def __init__(self, library, handler_name, handler_method, docgetter):
        _PythonHandler.__init__(self, library, handler_name, handler_method)
        self._docgetter = docgetter

    @property
    def doc(self):
        if self._docgetter:
            self._doc = self._docgetter() or self._doc
            self._docgetter = None
        return self._doc

    def _parse_arguments(self, init_method):
        parser = PythonArgumentParser(type='Test Library')
        return parser.parse(init_method or (lambda: None), self.library.name)

class _JavaInitHandler(_JavaHandler):

    def __init__(self, library, handler_name, handler_method, docgetter):
        _JavaHandler.__init__(self, library, handler_name, handler_method)
        self._docgetter = docgetter

    @property
    def doc(self):
        if self._docgetter:
            self._doc = self._docgetter() or self._doc
            self._docgetter = None
        return self._doc

    def _parse_arguments(self, handler_method):
        parser = JavaArgumentParser(type='Test Library')
        signatures = self._get_signatures(handler_method)
        return parser.parse(signatures, self.library.name)

class EmbeddedArgumentsHandler(object):

    def __init__(self, name_regexp, orig_handler):
        self.arguments = ArgumentSpec()  # Show empty argument spec for Libdoc
        self.name_regexp = name_regexp
        self._orig_handler = orig_handler

    def __getattr__(self, item):
        return getattr(self._orig_handler, item)

    @property
    def library(self):
        return self._orig_handler.library

    @library.setter
    def library(self, library):
        self._orig_handler.library = library

    def matches(self, name):
        return self.name_regexp.match(name) is not None

    def create_runner(self, name):
        return EmbeddedArgumentsRunner(self, name)

    def __copy__(self):
        orig_handler = copy(self._orig_handler)
        return EmbeddedArgumentsHandler(self.name_regexp, orig_handler)
<commit_msg>Fix getting kw source when inspect.getsourcefile returns None.<commit_after>#  Copyright 2008-2015 Nokia Networks
#  Copyright 2016-     Robot Framework Foundation
#
#  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.

from copy import copy
import inspect

from robot.utils import (getdoc, getshortdoc, is_java_init, is_java_method,
                         is_list_like, normpath, printable_name,
                         split_tags_from_doc, type_name, unwrap)
from robot.errors import DataError
from robot.model import Tags

from .arguments import (ArgumentSpec, DynamicArgumentParser,
                        JavaArgumentCoercer, JavaArgumentParser,
                        PythonArgumentParser)
from .dynamicmethods import GetKeywordSource, GetKeywordTypes
from .librarykeywordrunner import (EmbeddedArgumentsRunner,
                                   LibraryKeywordRunner, RunKeywordRunner)
from .runkwregister import RUN_KW_REGISTER

def Handler(library, name, method):
    if RUN_KW_REGISTER.is_run_keyword(library.orig_name, name):
        return _RunKeywordHandler(library, name, method)
    if is_java_method(method):
        return _JavaHandler(library, name, method)
    else:
        return _PythonHandler(library, name, method)

def DynamicHandler(library, name, method, doc, argspec, tags=None):
    if RUN_KW_REGISTER.is_run_keyword(library.orig_name, name):
        return _DynamicRunKeywordHandler(library, name, method, doc, argspec, tags)
    return _DynamicHandler(library, name, method, doc, argspec, tags)

def InitHandler(library, method=None, docgetter=None):
    Init = _PythonInitHandler if not is_java_init(method) else _JavaInitHandler
    return Init(library, '__init__', method, docgetter)

class _RunnableHandler(object):

    def __init__(self, library, handler_name, handler_method, doc='', tags=None):
        self.library = library
        self._handler_name = handler_name
        self.name = self._get_name(handler_name, handler_method)
        self.arguments = self._parse_arguments(handler_method)
        self._method = self._get_initial_handler(library, handler_name,
                                                 handler_method)
        doc, tags_from_doc = split_tags_from_doc(doc or '')
        tags_from_attr = self._get_tags_from_attribute(handler_method)
        self._doc = doc
        self.tags = Tags(tuple(tags_from_doc) +
                         tuple(tags_from_attr) +
                         tuple(tags or ()))

    def _get_name(self, handler_name, handler_method):
        robot_name = getattr(handler_method, 'robot_name', None)
        name = robot_name or printable_name(handler_name, code_style=True)
        if not name:
            raise DataError('Keyword name cannot be empty.')
        return name

    def _parse_arguments(self, handler_method):
        raise NotImplementedError

    def _get_tags_from_attribute(self, handler_method):
        tags = getattr(handler_method, 'robot_tags', ())
        if not is_list_like(tags):
            raise DataError("Expected tags to be list-like, got %s."
                            % type_name(tags))
        return tags

    def _get_initial_handler(self, library, name, method):
        if library.scope.is_global:
            return self._get_global_handler(method, name)
        return None

    def resolve_arguments(self, args, variables=None):
        return self.arguments.resolve(args, variables)

    @property
    def doc(self):
        return self._doc

    @property
    def longname(self):
        return '%s.%s' % (self.library.name, self.name)

    @property
    def shortdoc(self):
        return getshortdoc(self.doc)

    @property
    def libname(self):
        return self.library.name

    @property
    def source(self):
        return self.library.source

    @property
    def lineno(self):
        return -1

    def create_runner(self, name):
        return LibraryKeywordRunner(self)

    def current_handler(self):
        if self._method:
            return self._method
        return self._get_handler(self.library.get_instance(), self._handler_name)

    def _get_global_handler(self, method, name):
        return method

    def _get_handler(self, lib_instance, handler_name):
        try:
            return getattr(lib_instance, handler_name)
        except AttributeError:
            # Occurs with old-style classes.
            if handler_name == '__init__':
                return None
            raise

class _PythonHandler(_RunnableHandler):

    def __init__(self, library, handler_name, handler_method):
        _RunnableHandler.__init__(self, library, handler_name, handler_method,
                                  getdoc(handler_method))

    def _parse_arguments(self, handler_method):
        return PythonArgumentParser().parse(handler_method, self.longname)

    @property
    def source(self):
        handler = self.current_handler()
        # `getsourcefile` can return None and raise TypeError.
        try:
            source = inspect.getsourcefile(unwrap(handler))
        except TypeError:
            source = None
        return normpath(source) if source else self.library.source

    @property
    def lineno(self):
        handler = self.current_handler()
        try:
            lines, start_lineno = inspect.getsourcelines(unwrap(handler))
        except (TypeError, OSError, IOError):
            return -1
        for increment, line in enumerate(lines):
            if line.strip().startswith('def '):
                return start_lineno + increment
        return start_lineno

class _JavaHandler(_RunnableHandler):

    def __init__(self, library, handler_name, handler_method):
        _RunnableHandler.__init__(self, library, handler_name, handler_method)
        signatures = self._get_signatures(handler_method)
        self._arg_coercer = JavaArgumentCoercer(signatures, self.arguments)

    def _parse_arguments(self, handler_method):
        signatures = self._get_signatures(handler_method)
        return JavaArgumentParser().parse(signatures, self.longname)

    def _get_signatures(self, handler):
        code_object = getattr(handler, 'im_func', handler)
        return code_object.argslist[:code_object.nargs]

    def resolve_arguments(self, args, variables=None):
        positional, named = self.arguments.resolve(args, variables,
                                                   dict_to_kwargs=True)
        arguments = self._arg_coercer.coerce(positional, named,
                                             dryrun=not variables)
        return arguments, []

class _DynamicHandler(_RunnableHandler):

    def __init__(self, library, handler_name, dynamic_method, doc='',
                 argspec=None, tags=None):
        self._argspec = argspec
        self._run_keyword_method_name = dynamic_method.name
        self._supports_kwargs = dynamic_method.supports_kwargs
        _RunnableHandler.__init__(self, library, handler_name,
                                  dynamic_method.method, doc, tags)
        self._source_info = None

    def _parse_arguments(self, handler_method):
        spec = DynamicArgumentParser().parse(self._argspec, self.longname)
        if not self._supports_kwargs:
            if spec.kwargs:
                raise DataError("Too few '%s' method parameters for **kwargs "
                                "support." % self._run_keyword_method_name)
            if spec.kwonlyargs:
                raise DataError("Too few '%s' method parameters for "
                                "keyword-only arguments support."
                                % self._run_keyword_method_name)
        get_keyword_types = GetKeywordTypes(self.library.get_instance())
        spec.types = get_keyword_types(self._handler_name)
        return spec

    @property
    def source(self):
        if self._source_info is None:
            self._source_info = self._get_source_info()
        return self._source_info[0]

    def _get_source_info(self):
        get_keyword_source = GetKeywordSource(self.library.get_instance())
        try:
            source = get_keyword_source(self._handler_name)
        except DataError as err:
            self.library.report_error(
                "Getting source information for keyword '%s' failed: %s"
                % (self.name, err.message), err.details
            )
            return None, -1
        if not source:
            return self.library.source, -1
        if ':' not in source:
            return source, -1
        path, lineno = source.rsplit(':', 1)
        try:
            return path or self.library.source, int(lineno)
        except ValueError:
            return source, -1

    @property
    def lineno(self):
        if self._source_info is None:
            self._source_info = self._get_source_info()
        return self._source_info[1]

    def resolve_arguments(self, arguments, variables=None):
        positional, named = self.arguments.resolve(arguments, variables)
        if not self._supports_kwargs:
            positional, named = self.arguments.map(positional, named)
        return positional, named

    def _get_handler(self, lib_instance, handler_name):
        runner = getattr(lib_instance, self._run_keyword_method_name)
        return self._get_dynamic_handler(runner, handler_name)

    def _get_global_handler(self, method, name):
        return self._get_dynamic_handler(method, name)

    def _get_dynamic_handler(self, runner, name):
        def handler(*positional, **kwargs):
            if self._supports_kwargs:
                return runner(name, positional, kwargs)
            else:
                return runner(name, positional)
        return handler

class _RunKeywordHandler(_PythonHandler):

    def create_runner(self, name):
        default_dry_run_keywords = ('name' in self.arguments.positional and
                                    self._args_to_process)
        return RunKeywordRunner(self, default_dry_run_keywords)

    @property
    def _args_to_process(self):
        return RUN_KW_REGISTER.get_args_to_process(self.library.orig_name,
                                                   self.name)

    def resolve_arguments(self, args, variables=None):
        args_to_process = self._args_to_process
        return self.arguments.resolve(args, variables, resolve_named=False,
                                      resolve_variables_until=args_to_process)

class _DynamicRunKeywordHandler(_DynamicHandler, _RunKeywordHandler):
    _parse_arguments = _RunKeywordHandler._parse_arguments
    resolve_arguments = _RunKeywordHandler.resolve_arguments

class _PythonInitHandler(_PythonHandler):

    def __init__(self, library, handler_name, handler_method, docgetter):
        _PythonHandler.__init__(self, library, handler_name, handler_method)
        self._docgetter = docgetter

    @property
    def doc(self):
        if self._docgetter:
            self._doc = self._docgetter() or self._doc
            self._docgetter = None
        return self._doc

    def _parse_arguments(self, init_method):
        parser = PythonArgumentParser(type='Test Library')
        return parser.parse(init_method or (lambda: None), self.library.name)

class _JavaInitHandler(_JavaHandler):

    def __init__(self, library, handler_name, handler_method, docgetter):
        _JavaHandler.__init__(self, library, handler_name, handler_method)
        self._docgetter = docgetter

    @property
    def doc(self):
        if self._docgetter:
            self._doc = self._docgetter() or self._doc
            self._docgetter = None
        return self._doc

    def _parse_arguments(self, handler_method):
        parser = JavaArgumentParser(type='Test Library')
        signatures = self._get_signatures(handler_method)
        return parser.parse(signatures, self.library.name)

class EmbeddedArgumentsHandler(object):

    def __init__(self, name_regexp, orig_handler):
        self.arguments = ArgumentSpec()  # Show empty argument spec for Libdoc
        self.name_regexp = name_regexp
        self._orig_handler = orig_handler

    def __getattr__(self, item):
        return getattr(self._orig_handler, item)

    @property
    def library(self):
        return self._orig_handler.library

    @library.setter
    def library(self, library):
        self._orig_handler.library = library

    def matches(self, name):
        return self.name_regexp.match(name) is not None

    def create_runner(self, name):
        return EmbeddedArgumentsRunner(self, name)

    def __copy__(self):
        orig_handler = copy(self._orig_handler)
        return EmbeddedArgumentsHandler(self.name_regexp, orig_handler)
<|endoftext|>