Beispiel #1
0
def genpass(pattern=r'[\w]{32}'):
    """generates a password with random chararcters
    """
    try:
        return rstr.xeger(pattern)
    except re.error as e:
        raise ValueError(str(e))
Beispiel #2
0
def get_all_urls(urllist, depth=0, prefix='', result=None):
    if result is None:
        result = []
    for entry in urllist:
        url = prefix + entry.regex.pattern.strip('^$')
        if hasattr(entry, 'url_patterns'):
            get_all_urls(entry.url_patterns, depth + 1,
                         prefix=url,
                         result=result)
        else:
            if not url.startswith('/'):
                url = '/' + url
            # Значения и с вложенными скобками "(/(\w+)/)", и без
            regexp = '((\([^\(\)]*?)?' \
                     '\([^\(\)]+\)' \
                     '(?(2)[^\(\)]*\)|))'
            # открывающая скобка и текст без скобок
            # значение в скобках. Например (?P<pk>\d+)
            # если есть первая открывающая скобка, нужно взять строку до закрывающей
            fres = re.findall(regexp, url)
            for fr in fres:
                fr = fr[0]
                value_for_replace = '123'
                if (re.findall('>(.+?)\)', fr) and
                    not set(re.findall('>(.+?)\)', fr)).intersection(['.*', '\d+', '.+', '[^/.]+'])):
                    value_for_replace = rstr.xeger(fr)
                url = url.replace(fr, value_for_replace)
            result.append(url)
    result.sort()
    return result
Beispiel #3
0
def get_all_urls(urllist, depth=0, prefix="", result=None):
    if result is None:
        result = []
    for entry in urllist:
        url = prefix + entry.regex.pattern.strip("^$")
        if hasattr(entry, "url_patterns"):
            get_all_urls(entry.url_patterns, depth + 1, prefix=url, result=result)
        else:
            if not url.startswith("/"):
                url = "/" + url
            # Значения и с вложенными скобками "(/(\w+)/)", и без
            regexp = "((\([^\(\)]*?)?" "\([^\(\)]+\)" "(?(2)[^\(\)]*\)|))"
            # открывающая скобка и текст без скобок
            # значение в скобках. Например (?P<pk>\d+)
            # если есть первая открывающая скобка, нужно взять строку до закрывающей
            fres = re.findall(regexp, url)
            for fr in fres:
                fr = fr[0]
                value_for_replace = "123"
                if re.findall(">(.+?)\)", fr) and not set(re.findall(">(.+?)\)", fr)).intersection(
                    [".*", "\d+", ".+", "[^/.]+"]
                ):
                    value_for_replace = rstr.xeger(fr)
                url = url.replace(fr, value_for_replace)
            result.append(url)
    result.sort()
    return result
Beispiel #4
0
def _issue_new_recommend_code():
    while True:
        code = rstr.xeger(User.RECOMMEND_CODE_REGEX)
        try:
            User.objects.get(recommend_code=code)
        except User.DoesNotExist, e:
            return code
 def generate(self):
     if self.enum:
         return random.choice(self.enum)
     elif self.pattern:
         return rstr.xeger(self.pattern)
     else:
         return rstr.rstr(string.letters+string.digits,self.minLength,self.maxLength)
Beispiel #6
0
 def generate(self):
     if '{' in self.format:
         self.format = self._parse_field_format(self.format)
     if self.str_type == 'xeger':
         return rstr.xeger(self.format)[:self.maxlen]
     else:
         return generate_string(self.str_type, self.maxlen)
    def test_get_counters_match(self):
        import rstr
        content = ''

        for counter_name, regexp in lib.COUNTER_TYPES:
            content += rstr.xeger(regexp)

        self.assertEquals(len(lib.COUNTER_TYPES), len(lib.get_counters(content)))
 def CreateTestCase(self, caseId: int, count: int, wordSizeMin: int, wordSizeMax: int, reg: str):
     try:        
         w = ''  
         print("Generating {0} {1}-{2}".format(caseId, wordSizeMin, wordSizeMax))
         with open(self.__CreateName('positive', caseId, wordSizeMin, wordSizeMax), 'w') as file1,\
              open(self.__CreateName('negative', caseId, wordSizeMin, wordSizeMax), 'w') as file2:                
                 unique = []
                 for i in range(count):
                     print("Word: {0}".format(i+1))
                     tooLow,tooHigh = 0,0
                     currWordSizeMin, currWordSizeMax = wordSizeMin, wordSizeMax
                     regGen, currWordSizeMin, currWordSizeMax = self.__CalculateRepetitions(reg, currWordSizeMin, currWordSizeMax, tooLow, tooHigh)            
                     while True:                        
                         if tooLow > 3 or tooHigh > 3:
                             regGen, currWordSizeMin, currWordSizeMax = self.__CalculateRepetitions(reg, currWordSizeMin, currWordSizeMax, tooLow, tooHigh)
                             tooLow = tooHigh = 0
                         pattern = re.compile(reg)
                         #positive                        
                         w = rstr.xeger(regGen)
                         if len(w) < wordSizeMin:
                             tooLow += 1
                             continue
                         elif len(w) > wordSizeMax:
                             tooHigh += 1
                             continue
                         if w in unique:
                             continue
                         if pattern.fullmatch(w) is None:
                             continue
                         unique.append(w)
                         file1.write(w+'\n')                        
                         #negative
                         if len(w) == 0:
                             w = str(rand.choice(['a','b']))
                             print("Zero length")
                         counter = 0                            
                         try:
                             while True:
                                 counter += 1                                
                                 list1 = list(w)
                                 pos = rand.randint(0, len(w)-1)
                                 list1[pos] = rand.choice(['a','b'])
                                 w = ''.join(list1)
                                 if counter > 3:
                                     w += str(rand.choice(['a','b']))
                                 if pattern.fullmatch(w) is None:
                                     file2.write(w+'\n')                                    
                                     break
                             break
                         except Exception as e:
                             print("Error while parsing: {0}".format(e))
                             with open(__CreateName('error', caseId, wordSizeMin, wordSizeMax), 'w') as fileE:
                                 fileE.write(w+'\n')
                         break                    
     except Exception as e:
         print("General error parsing: {0}".format(e))
         with open(self.__CreateName('error', caseId, wordSizeMin, wordSizeMax), 'w') as fileE:
             fileE.write(w+'\n')   
def gen_testlog():
    with open('conf.yaml') as f:
        test_conf = yaml.safe_load(f)['test']
    total_size = test_conf['size']
    size_dict = {t : int(total_size * float(f)) for t, f in test_conf['frequency'].iteritems()}
    local_id = server.find_local_id()
    
    # Placeholder
    log_list = ['' for i in xrange(total_size)]
 
    # Gen a line for only this server
    random_idx = int(random.random() * total_size)
    log_list[random_idx] = 'server %d' % local_id

    # Gen a line for specified servers
    if local_id in test_conf['hit_servers']:
        random_idx = int(random.random() * total_size)
        while log_list[random_idx]:
            random_idx = int(random.random() * total_size)
        log_list[random_idx] = 'hit_server'

    # Gen a line for all servers
    random_idx = int(random.random() * total_size)
    while log_list[random_idx]:
        random_idx = int(random.random() * total_size)
    log_list[random_idx] = 'all_server'

    # Gen lines for patterns with different frequencies
    for t, s in size_dict.iteritems():
        cnt = 0
        while cnt < s:
            random_idx = int(random.random() * total_size)
            while log_list[random_idx]:
                random_idx = int(random.random() * total_size)
            log_list[random_idx] = rstr.xeger(test_conf['pattern'][t]) 
            cnt += 1

    # Gen randomly for the rest
    for i in xrange(total_size):
        if not log_list[i]:
            log_list[i] = rstr.xeger(test_conf['pattern']['random']) 
     
    with open('%svm%d.log' % (test_conf['log_path'], local_id), 'w') as f:
        for i in xrange(total_size):
            f.write(log_list[i] + '\n')
def generate_list_of_mail_ids_and_save_to_text_file(no_of_ids, text_file_address):
    if not isinstance(no_of_ids, int):
        return
    f = open(text_file_address, "rw+")
    f.seek(0, 0)
    for i in range(no_of_ids):
        mail = rstr.xeger(r'\w[\w\.-]*@\w[\w\.-]+\.\w+')
        f.write(mail + "\n")
    f.close()
    def test_get_counters(self):
        page = ''

        for counter_name, regexp in lib.COUNTER_TYPES:
            page += rstr.xeger(regexp)

        counters = lib.get_counters(page)

        self.assertEqual(len(counters), len(lib.COUNTER_TYPES), 'Not all counter found, or too mny counters found')
    def test_get_counters(self):
        page = str()

        for counter_name, regexp in COUNTER_TYPES:
            page += rstr.xeger(regexp)

        counters = get_counters(page)

        self.assertEqual(len(counters), len(COUNTER_TYPES))
Beispiel #13
0
 def make_many_application_sources(count=2, in_doaj=False):
     application_sources = []
     for i in range(0, count):
         template = deepcopy(APPLICATION_SOURCE)
         template['id'] = 'applicationid{0}'.format(i)
         # now some very quick and very dirty date generation
         fakemonth = i
         if fakemonth < 1:
             fakemonth = 1
         if fakemonth > 9:
             fakemonth = 9
         template['created_date'] = "2000-0{fakemonth}-01T00:00:00Z".format(fakemonth=fakemonth)
         template["bibjson"]['identifier'] = [
             {"type": "pissn", "id": rstr.xeger(forms.ISSN_REGEX)},
             {"type": "eissn", "id": rstr.xeger(forms.ISSN_REGEX)},
         ]
         template['bibjson']['title'] = 'Test Title {}'.format(i)
         application_sources.append(deepcopy(template))
     return application_sources
Beispiel #14
0
    def process(self, value):
        if value.startswith("pattern:"):
            pattern = value.replace("pattern:", "", 1)

            import rstr
            gen_value = rstr.xeger(pattern)

            return gen_value
        else:
            return value
Beispiel #15
0
def mock_leaf_response(leaf_node, path):

    type_schema_node = leaf_node['typeSchemaNode']
    node_type = type_schema_node['leafType']

    body = "{\"#{leaf_node['name']}\":"
    value = None

    if node_type == 'STRING':
        if 'typeValidator' in type_schema_node:
            type_validator = type_schema_node['typeValidator']
            length = len(type_validator)
            
            # value we are going to return
            if length > 0:
                ranges_obj = type_validator[0]
                ranges_array = ranges_obj['ranges']
                # Get the max size
                value_length = ranges_array[0]['end']
                example = "abcdefghijklmnopqrstuvwxyz"
                value = example[:value_length]
            if length > 1:
                pattern = type_validator[1]
                regex_pattern = pattern['pattern']
                value = rstr.xeger(regex_pattern)[:value_length]

        # Base case
        if not value:
            value = "string"

        body += '"' + value + '"}'
    elif node_type == 'BOOLEAN':
        # Randomly calculate a true or false value
        random_boolean = bool(random.getrandbits(1))

        if random_boolean:
            value = "true"
        else: 
            value = "false"

        body += value + '}'
    elif node_type == 'INTEGER':
        body += '1}'
    elif node_type == 'ENUMERATION':
        # Will there ever be more than one type validator?
        enums = type_schema_node['typeValidator'][0]['names'].keys()
        enum = random.choice(enums)
        body += "\"#{enum}\"}"
    else:
        print "Missing node_type #{node_type}"

    print body
    responses.add(responses.GET, PREFIX + path,
              body=body, status=200,
              content_type='application/json')
Beispiel #16
0
 def make_many_journal_sources(count=2, in_doaj=False):
     journal_sources = []
     for i in range(0, count):
         template = deepcopy(JOURNAL_SOURCE)
         template['id'] = 'journalid{0}'.format(i)
         # now some very quick and very dirty date generation
         fakemonth = i
         if fakemonth < 1:
             fakemonth = 1
         if fakemonth > 9:
             fakemonth = 9
         template['created_date'] = "2000-0{fakemonth}-01T00:00:00Z".format(fakemonth=fakemonth)
         template["bibjson"]['identifier'] = [
             {"type": "pissn", "id": rstr.xeger(forms.ISSN_REGEX)},
             {"type": "eissn", "id": rstr.xeger(forms.ISSN_REGEX)}
         ]
         template['admin']['in_doaj'] = in_doaj
         template['bibjson']['active'] = in_doaj  # legacy field?
         template['bibjson']['title'] = 'Test Title {}'.format(i)
         journal_sources.append(deepcopy(template))
     return journal_sources
    def test_get_url_http_new_redirect_and_ok_redirect(self):
        url = 'http://mail.ru'
        timeout = 10
        expected_redirect_url = rstr.xeger(lib.OK_REDIRECT)
        expected_content = self.get_redirect_html('page.html')

        with mock.patch('source.lib.make_pycurl_request', mock.Mock(return_value=(expected_content, expected_redirect_url))):
            redirect_url, redirect_type, content = lib.get_url(url, timeout)

            self.assertIsNone(redirect_url, 'redirect_url is not None')
            self.assertIsNone(redirect_type, 'redirect_type is not None')
            self.assertEqual(content, expected_content, 'content not match')
Beispiel #18
0
 def generate_values(self, annotations):
     """
     :type annotations: dict [str, cts_core.metadata.model.annotation.Annotation]
     :rtype: list
     """
     if "Validation.Pattern" in annotations:
         pattern = str(annotations["Validation.Pattern"].value)
         # this simple hack blocking CTS from sending special characters ex. symbol of new line
         sample_value = xeger(pattern.replace(".", "[\w\d \.,]"))
         return [sample_value]
     else:
         return ["example value", "", "AZaz09[]!@#$%^&*()_+"]
Beispiel #19
0
    def random_string(self, schema=dict()):
        # pattern = schema.get("pattern", None)
        if "pattern" in schema:
            return rstr.xeger(schema["pattern"])

        min_length = schema.get("minLength", self.string_range[0])
        max_length = schema.get("maxLength", self.string_range[1])

        if min_length > max_length:
            max_length = min_length
        length = random.randint(min_length, max_length)
        return ''.join(random.choice(self.string_charset) for x in range(length))
Beispiel #20
0
def get_all_urls(urllist, depth=0, prefix='', result=None):
    if result is None:
        result = []
    for entry in urllist:
        url = prefix + getattr(entry, 'pattern', entry).regex.pattern.strip('^$').replace('\\/', '/')
        if hasattr(entry, 'url_patterns'):
            get_all_urls(entry.url_patterns, depth + 1, prefix=url, result=result)
        else:
            if not url.startswith('/'):
                url = '/' + url
            url = rstr.xeger(url.replace('\\d+', '123'))
            result.append(url)
    result.sort()
    return result
Beispiel #21
0
    def __status_url(ctx, server_preferred=False):
        """
        Creates stub/plus status url based on context

        :param ctx: {} of current parsing context
        :param server_preferred: bool - use server_name instead of listen
        :return: [] of urls
        """
        results = []
        location = ctx.get('location', '/')

        # remove all modifiers
        location_parts = location.split(' ')
        final_location_part = location_parts[-1]

        # generate a random sting that will fit regex location
        if location.startswith('~'):
            try:
                exact_location = rstr.xeger(final_location_part)

                # check that regex location has / and add it
                if not exact_location.startswith('/'):
                    exact_location = '/%s' % exact_location
            except:
                context.log.debug('bad regex location: %s' % final_location_part)
                exact_location = None
        else:
            exact_location = final_location_part

            # if an exact location doesn't have / that's not a working location, we should not use it
            if not exact_location.startswith('/'):
                context.log.debug('bad exact location: %s' % final_location_part)
                exact_location = None

        if exact_location:
            for ip_port in ctx.get('ip_port'):
                address, port = ip_port
                if server_preferred and 'server_name' in ctx:
                    if isinstance(ctx['server_name'], list):
                        address = ctx['server_name'][0].split(' ')[0]
                    else:
                        address = ctx['server_name'].split(' ')[0]

                results.append('%s:%s%s' % (address, port, exact_location))

        return results
Beispiel #22
0
def new_page_style(name, style):
	if isinstance(style, str):
		new_c = ""
		temp = style.replace("\\d", "10")		#replace the digit expression with 10, there is a total of 10 digits
		temp = temp.replace("[A-Z]", "26")		#replace the alphabet expression with 26, there is 26 letters in the alphabet
		temp = temp.replace("[a-z]", "26")		#replace the alphabet expression with 26, there is 26 letters in the alphabet
		temp = temp.replace("|", "+")			#replace the or symbol with +
		temp = temp.replace(")", ")*")			#replace the end paranthes with end paranthes and *
		temp = temp.replace("*+", "+")			#replace *+ with +
		temp = temp.replace("2610", "26*10")	#put a * in between the numbers
		temp = temp.replace("1026", "10*26")	#same
		temp = temp.replace("1010", "10*10")	#same
		temp = temp.replace("2626", "26*26")	#same
		total = eval(temp)	  #now we can evaluate it as a mathematical expression, total now contains the total amount of possible strings that can be generated by the regular expressions
		l = []
		while len(l) < total and len(l) < 65535:
			try:
				q = str(rstr.xeger(r"" + style + ""))	   #generate a string based on the regular expression
			except:
				print("regular expression in input is invalid")
				sys.exit(2)
			q = q.strip()		   #remove unnecessary '
			if q not in l:
				l.append(q)		 #add the string to the list of unique generated strings
		for i in range(0,len(l)):
			if i == 0:
				new_c += l[i]		   #add the element to string to be written
			elif i % 16 == 0:
				new_c += "\n\\or " + l[i]	   #add the element, a newline and a \or, to string to be written
			else:
				new_c += "\\or " + l[i]		 #add the element and a \or, to string to be written
		else:
			print("invalid input")

	f = open("Resources/page_numbering.tex", 'r')
	s = f.read()
	f.close()
	s = s.replace("\\makeatother", "")		   #remove the \makeatother
	s += "\\newcommand*{\\" + name + "}[1]{%\n\\expandafter\\@" + name + "\\csname c@#1\\endcsname\n}\n\n\\newcommand*{\\@" + name + "}[1]{%\n$\\ifcase#1\n"	 #create the command for the new style
	s += new_c
	s += "\n" + "\n\\else\\@ctrerr\\fi$\n}\n\\makeatother"	 #add the end of the command plus \makeatother
	f = open("Resources/page_numbering.tex", 'w')
	f.write(s)
	f.close()
def test_speed():
        with open('conf.yaml') as f:
            conf = yaml.safe_load(f)

        latency_list = []
        sys.stdout = open('temp.test.out.speed', 'w')
        for i in xrange(conf['test']['speed_test_size']):
            grep_cmd = ['grep', rstr.xeger(r'[a-z]{,4}[.][a-z]{1,3}')]
            c = client.LogQueryClient(grep_cmd)

            tick = time.time()
            c.query()
            tock = time.time()
            
            latency_list.append(tock - tick)
        sys.stdout = sys.__stdout__

        avg_latency = sum(latency_list) / len(latency_list)
        LOGGER.info('Average latency is ' + str(avg_latency)) 
def create_vm_and_install_old_extension():
    """Create vm and install a specific version of the extension, returning HTML results."""

    message = ""
    update_option = '--version {0} --no-auto-upgrade'.format(old_version)
    install_times.clear()
    for distname, image in images.iteritems():
        uid = rstr.xeger(r'[0-9a-f]{8}')
        vmname = distname.lower() + '-' + uid
        vmnames.append(vmname)
        dnsname = vmname
        vm_log_file = distname.lower() + "result.log"
        vm_html_file = distname.lower() + "result.html"
        log_open = open(vm_log_file, 'a+')
        html_open = open(vm_html_file, 'a+')
        print("\nCreate VM and Install Extension {0} v-{1} - {2}: {3} \n".format(extension, old_version, vmname, image))
        create_vm(resource_group, vmname, image, username, ssh_public, location, dnsname, size, nsg_uri)
        copy_to_vm(dnsname, username, ssh_private, location)
        delete_extension(extension, vmname, resource_group)
        run_command(resource_group, vmname, 'RunShellScript', 'python -u /tmp/oms_extension_run_script.py -preinstall')
        add_extension(extension, publisher, vmname, resource_group, private_settings, public_settings, update_option)
        run_command(resource_group, vmname, 'RunShellScript', 'python -u /home/scratch/oms_extension_run_script.py -postinstall')
        install_times.update({vmname: datetime.now()})
        run_command(resource_group, vmname, 'RunShellScript', 'python -u /home/scratch/oms_extension_run_script.py -injectlogs')
        copy_from_vm(dnsname, username, ssh_private, location, 'omsresults.*')
        write_log_command(log_open, "Status After Creating VM and Adding OMS Extension version: {0}".format(old_version))
        html_open.write('<h1 id="{0}"> VM: {0} <h1>'.format(distname))
        html_open.write("<h2> Install OMS Agent version: {0} </h2>".format(old_version))
        append_file('omsfiles/omsresults.log', log_open)
        append_file('omsfiles/omsresults.html', html_open)
        log_open.close()
        html_open.close()
        status = open('omsfiles/omsresults.status', 'r').read()
        if status == "Agent Found":
            message += """
                            <td><span style='background-color: #66ff99'>Install Success</span></td>"""
        elif status == "Onboarding Failed":
            message += """
                            <td><span style='background-color: red; color: white'>Onboarding Failed</span></td>"""
        elif status == "Agent Not Found":
            message += """
                            <td><span style='background-color: red; color: white'>Install Failed</span></td>"""
    return message
Beispiel #25
0
    def create(self, request, *args, **kwargs):
        serializer = ClientSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        client = serializer.validated_data['client']
        client.save()

        if client:
            delay = randrange(30)  # delay in seconds for real server simulation
            time.sleep(delay)
            is_car = False
            registration_plate = '-'
            if delay % 2 == 0:
                is_car = True
                registration_plate = xeger(r'[A-Z]{2} \d{4} [A-Z]{2}')

            if is_car:
                content = {
                    'is_car': True,
                    'registration_plate': registration_plate,
                    'will_be_in': delay
                }
            else:
                content = {
                    'is_car': False,
                    'no_car_msg': 'Not found any taxi in your area'
                }

            Order.objects.create(
                order_date=timezone.now(),
                registration_plate=registration_plate,
                client=client
            )
        else:
            content = {
                'is_error': True,
                # 'is_car': False,
                # 'no_car_msg': 'Not found any taxi in your area'
                'error': 'Oops'
            }

        return Response(content)
    def test_all_counters_detected(self):
        COUNTER_TYPES = (
            ('GOOGLE_ANALYTICS', re.compile(r'.*google-analytics\.com/ga\.js.*', re.I + re.S)),
            ('YA_METRICA', re.compile(r'.*mc\.yandex\.ru/metrika/watch\.js.*', re.I + re.S)),
            ('TOP_MAIL_RU', re.compile(r'.*top-fwz1\.mail\.ru/counter.*', re.I + re.S)),
            ('TOP_MAIL_RU', re.compile(r'.*top\.mail\.ru/jump\?from.*', re.I + re.S)),
            ('DOUBLECLICK',
             re.compile(r'.*//googleads\.g\.doubleclick\.net/pagead/viewthroughconversion.*', re.I + re.S)),
            ('VISUALDNA', re.compile(r'.*//a1\.vdna-assets\.com/analytics\.js.*', re.I + re.S)),
            ('LI_RU', re.compile(r'.*/counter\.yadro\.ru/hit.*', re.I + re.S)),
            ('RAMBLER_TOP100', re.compile(r'.*counter\.rambler\.ru/top100.*', re.I + re.S))
        )
        content = ""
        for counter_name, regexp in COUNTER_TYPES:
            content += rstr.xeger(regexp)

        counters = lib.get_counters(content)

        for counter_name, regexp in COUNTER_TYPES:
            self.assertTrue(counter_name in counters)
        self.assertEqual(len(COUNTER_TYPES), len(counters))
Beispiel #27
0
def get_all_urls(urllist, depth=0, prefix='', result=None):
    if result is None:
        result = []
    for entry in urllist:
        url = prefix + entry.regex.pattern.strip('^$')
        if hasattr(entry, 'url_patterns'):
            get_all_urls(entry.url_patterns, depth + 1,
                         prefix=(prefix if type(entry).__class__.__name__ == 'RegexURLResolver' else '') + url,
                         result=result)
        else:
            if not url.startswith('/'):
                url = '/' + url
            # TODO: переписать регулярку. Должны находиться значения и с вложенными скобками "(/(\w+)/)" и без
            fres = re.findall(r'\(.+?\)+', url)
            for fr in fres:
                value_for_replace = '123'
                if (re.findall('>(.+?)\)', fr) and
                    not set(re.findall('>(.+?)\)', fr)).intersection(['.*', '\d+', '.+', '[^/.]+'])):
                    value_for_replace = rstr.xeger(fr)
                url = url.replace(fr, value_for_replace)
            result.append(url)
    result.sort()
    return result
Beispiel #28
0
 def generate_value(self, avoided_value):
     if not self.REGEX:
         return "Example String Value"
     return rstr.xeger(self.REGEX)
Beispiel #29
0
]

# Target size for the dataset. Generation stops when either limit is reached.
target_num_rows  =    10_000_000
target_num_bytes = 1_000_000_000

# Construct pools of random strings abiding by the generator configuration.
random_strings = []
frequency_norm = 0
for _, frequency, _ in generator_config:
    frequency_norm += frequency
cumulative_frequency = 0.0
for num_unique, frequency, regex in generator_config:
    print('Creating random strings for /' + regex + '/...')
    cumulative_frequency += frequency / frequency_norm
    string_pool = [rstr.xeger(regex) for _ in range(num_unique)]
    random_strings.append((cumulative_frequency, string_pool))

# Construct the test data.
print('Constructing test data...')
data = []
total_len = 0
print()
while total_len < target_num_bytes and len(data) < target_num_rows:
    r = random.random()
    for cumulative_frequency, string_pool in random_strings:
        if r <= cumulative_frequency:
            s = random.choice(string_pool)
            total_len += len(s)
            data.append(s)
            break
Beispiel #30
0
def getRegexString(regexString):
    """
    根据正则表达式,获取随机值
    """
    return rstr.xeger(regexString)
Beispiel #31
0
#You must install rstr and Skype4Py

from Skype4Py import Skype
import sys
import rstr

message = rstr.xeger('[A-Z][a-z]{4} [A-Z][a-z]{3,6}yan  \d{4}')

client = Skype()
client.Attach()
user = "******" 
client.SendMessage(user, message)
Beispiel #32
0
def sock(remoteip, remoteport):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((remoteip, remoteport))
    return s, s.makefile('rw', bufsize=0)

def read_until(f, delim='\n'):
    data = ''
    while not data.endswith(delim):
        data += f.read(1)
    return data

s, f = sock(remoteip, remoteport)

print read_until(f, "regexes?\n")

count = 0
while True:
	print "[+] Iter:", count
	target = read_until(f, "\n").strip()
	print "[+] Target:", target

	ans = rstr.xeger(target)
	while '\n' in ans:
		ans = rstr.xeger(target)
	print "[+] Answer:", ans
	s.send(ans+"\n")
	count += 1
	
s.close()

#flag: flag{^regularly_express_yourself$}
Beispiel #33
0
    def generate_string(cls, size=None):
        if size is None:
            size = random.randint(cls._MIN_LEN_DEFACULT, cls._MAX_LEN_DEFACULT)

        return rstr.xeger(rf'.{size}')
Beispiel #34
0
from Skype4Py import Skype
import rstr
import time

client = Skype(Transport='x11')
client.Attach()
user = '******'

while (1):
    message = rstr.xeger(
        '[A-Z][a-z]{3,8} [A-Z][a-z]{3,8}yan (19\d\d|20[0-1][0-7])')
    client.SendMessage(user, message)
    time.sleep(600)
Beispiel #35
0
 def test_xeger(self):
     assert re.match(r'^foo[\d]{10}bar$', rstr.xeger('^foo[\d]{10}bar$'))
Beispiel #36
0
def checker(driver, code):
    while True:
        voucher = rstr.xeger(r'[a-z][A-Z]\d[A-Z]')
        input_coupon(driver, code, voucher)
Beispiel #37
0
def gen_regex(regex):
    return rstr.xeger(regex)
Beispiel #38
0
def generate_spz():
    return "{}{}{}".format(random.choice(okresy), SPZ_SEPARATOR, rstr.xeger(SPZ_SUFFIX_FORMAT))
Beispiel #39
0
import rstr

with open("hint.txt") as f:
    string=f.read();
string=string[1:-1]
with open("dictionary.txt",'w') as f:
    for i in range(10000):
       answer=rstr.xeger(r''+string)
       f.write(str(answer)+"\n")

Beispiel #40
0
 def generate_string_by_pattern(pattern):
     return rstr.xeger(pattern)
def generate_regex():
    regi = input("regex: ")
    gen = rstr.xeger(regi)
    return gen
Beispiel #42
0
def make_val_address():
    return lambda: rstr.xeger(r"^terravaloper[0-9a-z]{39}\Z")
Beispiel #43
0
 def save(self, *args, **kwargs):
     if not self.licence:
         self.licence = rstr.xeger(self.licence_validator.regex)
     super().save(*args, **kwargs)
Beispiel #44
0
def make_acc_address():
    return lambda: rstr.xeger(r"^terra[0-9a-z]{39}\Z")
Beispiel #45
0
                          include=random.choice(improperCharacters),
                          exclude='\n\t\r"'),
                rstr.rstr(string.printable,
                          include=random.choice(improperCharacters),
                          exclude='\n\t\r"'),
                random.choice(['pl', 'com', 'net', 'uk', 'gov', 'us']))
        else:
            return rstr.rstr(string.printable, exclude='\n\t\r"')

    def generateProperPhoneNumber(self):
        return rstr.xeger(self.phoneNumberReg)

    def generateWrongPhoneNumber(self):
        case = random.randint(1, 2)
        if case == 1:
            return rstr.xeger(random.choice(self.improperPhoneNumberRegs))
        else:
            return rstr.rstr(string.printable,
                             include=random.choice(string.ascii_letters),
                             exclude='\n\t\r"')

    def generateProperMobileNumber(self):
        return rstr.xeger(self.mobileNumberReg)

    def generateWrongMobileNumber(self):
        case = random.randint(1, 2)
        if case == 1:
            return rstr.xeger(random.choice(self.improperMobileNumberRegs))
        else:
            return rstr.rstr(string.printable,
                             include=random.choice(string.ascii_letters),
Beispiel #46
0
    def value_for_schema_element(schema_element,
                                 root_schema_element,
                                 fake=faker.Faker(),
                                 overrides={}):

        if "oneOf" in schema_element.keys():
            se = random.choice(schema_element["oneOf"])
        elif "allOf" in schema_element.keys():
            se = dict()
            for rs in schema_element['allOf']:
                se.update(rs)
        elif "anyOf" in schema_element.keys():
            se = collections.defaultdict(list)

            for d in (schema_element["anyOf"]):
                for key, value in d.items():
                    se[key].append(value)
        else:
            se = copy.copy(schema_element)

        if "$ref" in se.keys():
            se = JSONProvider._find_reference_in_schema(
                se['$ref'], root_schema_element)
        if "type" not in se.keys():
            element_type = "string"
        elif type(se['type']) == list:
            element_type = random.choice(se['type'])
        else:
            element_type = se["type"]

        if element_type == 'null':
            return None
        elif element_type == 'string':
            if se.get('pattern', None) is not None:
                return rstr.xeger(se['pattern'])
            elif se.get('enum', None) is not None:
                return random.choice(se['enum'])
            else:
                return fake.password(length=30,
                                     special_chars=True,
                                     digits=True,
                                     upper_case=True,
                                     lower_case=True)

        elif element_type == 'number':
            return round(
                random.uniform(se.get('minimum', -100000000),
                               se.get('maximum', 10000000)),
                random.randint(0, 5))

        elif element_type == 'integer':
            n = random.randint(se.get('minimum', 0),
                               se.get('maximum', 10000000))
            return n - (n % se.get('multipleOf', 1))

        elif element_type == 'boolean':
            return fake.boolean(chance_of_getting_true=50)

        elif element_type == 'array':
            array_value = list()
            for _ in range(
                    0,
                    random.randint(
                        0,
                        random.randint(se.get('minItems', 3),
                                       se.get('maxItems', 100)))):
                array_value.append(
                    JSONProvider.value_for_schema_element(
                        se.get(
                            'items', {
                                "type":
                                random.choice(
                                    ["string", "boolean", "number", "integer"])
                            }), root_schema_element, fake, overrides))
            # P TODO need to support 'unique items'
            return array_value

        elif element_type == 'object':
            object_value = dict()
            for k, v in se.get('properties', {}).items():
                if k in overrides.keys():
                    object_value[k] = overrides[k]()
                else:
                    object_value[k] = JSONProvider.value_for_schema_element(
                        v, root_schema_element, fake, overrides)
            return object_value

        else:
            raise ValueError(
                "Don't know have to create value for schema element type [{}]".
                format(se['type']))
Beispiel #47
0
def generate(regex):
    val = ""
    # Generate random strings until we find one the right length
    val = rstr.xeger(regex)

    return val
Beispiel #48
0
 def generateProperPhoneNumber(self):
     return rstr.xeger(self.phoneNumberReg)
Beispiel #49
0
def val_address():
    return rstr.xeger(r"^terravaloper[0-9a-z]{39}\Z")
Beispiel #50
0
 def generateProperMobileNumber(self):
     return rstr.xeger(self.mobileNumberReg)
Beispiel #51
0
def acc_address():
    return rstr.xeger(r"^terra[0-9a-z]{39}\Z")
def generate_flags(pattern):
    return [rstr.xeger(pattern) for a in range(1)]
Beispiel #53
0
 def generate_code():
     import rstr
     return rstr.xeger(SecretCodeManager.CODE_REGEX)
Beispiel #54
0
 def __init__(self, session: Session, crash_log: str):
     self.report_id: str = rstr.xeger(CODE_REGEX)
     self.session: Session = session
     self.crash_log: str = crash_log
Beispiel #55
0
import traceback
import sys
import json
import pprint
filename = sys.argv[1]

with open (filename, "r") as myfile:
	ws = re.compile(r'\s+')
	data=myfile.read()
	jsondata = json.loads(data)
	patterns = jsondata["patterns"]
	for pattern in patterns:
		if not pattern:
			pass
		else:
			regex = pattern["match"]
			for i in range(1):
				val = rstr.xeger(regex)
				print(val)
				#print(re.sub(ws, '', val))
				for ipattern in patterns:
					if not ipattern:
						pass
					else:
						compiledregex = re.compile(ipattern["match"])
						if compiledregex.match(val):
							print("first match: "+ipattern["match"])
							break
		print('\n')

Beispiel #56
0
import rstr

for i in range(10):
    print(rstr.xeger(r'[A-Z]{3}-\d{3}\.mp4'))
Beispiel #57
0
def gen_regex(regex):
    return rstr.xeger(regex)
        if crumble == 'h':
            digits = input("Number of last digits to change in " +
                           head[column] + ": ")
            regexeslist.append(0)
        if crumble == 's':
            regexeslist.append(0)
        modeslist.append(crumble)

##### iterate rows, check for each column the requested mode, and create list for each row to wright in the resultset #####

    uu = []
    for row in csv_f:
        for column in range(columns):
            if modeslist[column] == 'g':
                regtodo = regexeslist[column]
                res = rstr.xeger(str(regtodo))
                uu.append(res)
            if modeslist[column] == 's':
                res = crumble_string(str(row[column]))
                uu.append(res)
            if modeslist[column] == 'c':
                uu.append(str(row[column]))
                #change --- uu[column], uu[column + 1] = uu[column+1], uu[column]
            if modeslist[column] == 'l':
                uu.append(str(row[column]))
            if modeslist[column] == 'h':
                ##### in order to keep the original statistics relations between items in the data, we hashed the last 4 digits and took the 4 digits of the results
                digits = int(digits)
                word = str(row[column])
                dighash = word[-digits:]
                rest = word[:-digits]
Beispiel #59
0
 def gen(self):
     return rstr.xeger(self.expr)
Beispiel #60
0
from Skype4Py import Skype
import rstr
import time

client = Skype(Transport='x11')
client.Attach()
user = '******'

while (1):
    message = rstr.xeger('[A-Z][a-z]{3,8} [A-Z][a-z]{3,8}yan (19\d\d|20[0-1][0-7])\nPair: Ruben-Mary')
    client.SendMessage(user, message)
    time.sleep(600)