Exemple #1
0
 def test_index(self, mock_get_rate, mock_calculate_usd):
     self.assertEqual(
         index('headers', amount=''),
         ('HTTP/1.1 400 Amount parameter not found\n\n',
          json.dumps({'Error': 'Amount parameter not found.'})))
     mock_get_rate.return_value = None
     self.assertEqual(
         index('headers', amount='88'),
         ('HTTP/1.1 500 Bad currency rates service\n\n',
          json.dumps({'Error': 'Bad currency rates service.'})))
     mock_get_rate.return_value = 42
     mock_calculate_usd.return_value = ''
     self.assertEqual(index('headers', amount='88'),
                      ('HTTP/1.1 400 Amount should be float\n\n',
                       json.dumps({'Error': 'Amount should be float.'})))
     mock_get_rate.return_value = 42
     mock_calculate_usd.return_value = '4'
     self.assertEqual(index('headers', amount='88'),
                      ('headers',
                       json.dumps({
                           'Currency': 'USD',
                           u'Amount': '88',
                           'Rate': '42',
                           'Result': '4'
                       })))
Exemple #2
0
 def test_store_basic(self):
     request = self.factory.get('/', HTTP_HOST = 'test1.example.com')
     self.mw.process_request(request)
     response = views.index(request)
     self.assertEqual(response.status_code, 200)
     self.assertContains(response, 'test1 store p1')
     self.assertNotContains(response, 'test2 store p1')
 def __init__(self, port):
     self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.websocket = ("127.0.0.1", port)
     self.urls = {
         "/": views.index(),
         "/about": "about page",
     }
Exemple #4
0
 def test_store_basic(self):
     request = self.factory.get('/', HTTP_HOST='test1.example.com')
     self.mw.process_request(request)
     response = views.index(request)
     self.assertEqual(response.status_code, 200)
     self.assertContains(response, 'test1 store p1')
     self.assertNotContains(response, 'test2 store p1')
def delete_file(filename):
	try:
		path = os.path.join(app.config['UPLOAD_FOLDER'],filename)
		os.remove(path)
		return views.index()
	except:
		return 'File does not exist'
Exemple #6
0
class Routes:
    """
    Dict with all routes
    """
    site_routes = {
        '/': index(),
        '/my_view': my_view(),
    }
Exemple #7
0
def page_not_found(e):
    """
    If this request was for the API, return JSON 404 error.  Otherwise render the angular app.
    """
    if request.path.startswith('/api/'):
        response = {'error': "Page Not Found", 'error_code': HTTP_STATUS.NOT_FOUND}
        return output_json(response, HTTP_STATUS.NOT_FOUND)
    return views.index()
Exemple #8
0
def handle_requests(request):
    '''Handles ajax requests directed to this learn/ajax/
    If not post, then goes to index page'''

    if request.method == 'POST':
        return handle_ajax_action(request)

    return views.index(request)
def app(environ, start_response):
        data = index(environ)
        print("inputs6 ----------------- ", environ['wsgi.input'].read())
        
        start_response("200 OK", [
            ("Content-Type", "text/html"),
            ("Content-Length", str(len(data)))
        ])        
        return iter([data])
Exemple #10
0
def handle_requests(request):
    '''Handles ajax requests directed to this learn/ajax/
    If not post, then goes to index page'''
    
    if request.method == 'POST':
        return handle_ajax_action(request)

    return views.index(request)

     
Exemple #11
0
 def test_index_page_returns_correct_url(self):
     request = HttpRequest()
     request.method = 'GET'
     response = index(request)
     expected_html = render_to_string('index.djhtml')
     # convert response.content bytes to python unicode string
     self.assertEqual(response.content.decode(),expected_html)
     
    
     self.assertIn(b'<title>Programski prevodioci</title>',response.content)
     self.assertTrue(response.content.strip().endswith(b'</html>'))
Exemple #12
0
def page_not_found(e):
    """
    If this request was for the API, return JSON 404 error.  Otherwise render the angular app.
    """
    if request.path.startswith('/api/'):
        response = {
            'error': "Page Not Found",
            'error_code': HTTP_STATUS.NOT_FOUND
        }
        return output_json(response, HTTP_STATUS.NOT_FOUND)
    return views.index()
Exemple #13
0
    def test_index(self):
        """ Test Index (input nothing)"""
        resolver = resolve('/')
        self.assertEqual(resolver.view_name, 'annotate.views.index')
        resolver = resolve('/annotate/')
        self.assertEqual(resolver.view_name, 'annotate.views.index')

        request = self.factory.get('/annotate/')
        request.META['REMOTE_USER'] = '******'
        response = views.index(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.charset, 'utf-8')

        self.checkContext(response.content, AnnotateTests.basicSettingDict)
Exemple #14
0
	def test_index(self):
		""" Test Index (input nothing)"""
		resolver = resolve('/')
		self.assertEqual(resolver.view_name, 'annotate.views.index')
		resolver = resolve('/annotate/')
		self.assertEqual(resolver.view_name, 'annotate.views.index')

		request = self.factory.get('/annotate/')
		request.META['REMOTE_USER'] = '******'
		response = views.index(request)
		self.assertEqual(response.status_code, 200)
		self.assertEqual(response.charset, 'utf-8')

		self.checkContext(response.content, AnnotateTests.basicSettingDict)
Exemple #15
0
 def test_al_ir_al_home_deberia_abrir_index(self):
     """
     Prueba que es sitio este arriba y corrindo
     cuando se va a la raiz
     """
     self.assertEqual(index({}).status_code, 200)
Exemple #16
0
 def rt(**arg):
     return views.index(**arg)
Exemple #17
0
 def test_al_ir_al_home_deberia_saludar(self):
     """
     Prueba que al ir al home se vea el mensaje
     'hola mundo'
     """
     self.assertIn('hola mundo' ,index({}).content)
Exemple #18
0
def index():
    print 'routed works'
    return v.index("static/index.html")
Exemple #19
0
def index():
    return views.index(xrange(10))
Exemple #20
0
    request = client_connection.recv(1024).decode()

    print(request)

    route = extract_route(request)

    filepath = CUR_DIR / route

    print("\n route: ", route)
    print("filepath: ", filepath, "\n")

    # se GET /templates/assets/css/getit.css HTTP/1.1
    if filepath.is_file():
        response = build_response() + read_file(filepath)
    # se GET / HTTP/1.1 ou POST / HTTP/1.1
    elif route == '':
        response = index(request)
    else:
        response = build_response()

    #serve para devolver a pagina html
    #envia as respostas
    # O código 200 é um dos possíveis códigos de status resposta.
    #Ele diz para o navegador que a requisição foi processada com sucesso.

    client_connection.sendall(response)

    client_connection.close()

server_socket.close()
def find_s_mc_lobs_do_r_z_c(request,
                            obj,
                            dest=None,
                            use_year=True,
                            item_id=None):
    ''' locate a merch centre, district office, struct, region, zone or club to edit its chairs, its officers (where applicable for either) or its details
    'obj' is the type of object to find: merch centre, district office, struct, region, zone or club
    'dest' is an optional destination for the URL. If blank, the object is the destination - ie. the edit page for an object
         otherwise the destination is inserted between the object type and the specific id of the item to edit
    'item_id' is an optional id for the obj. If supplied, only the year is chosen. 
    'use_year' is an optional instruction, if dest is true, use_year governs whether the year is inserted between the dest and the specific id
    '''

    print 'starting find_s_mc_lobs_do_r_z_c'
    # a list of obj, dest pairs this function can process
    pairs = [('struct', None), ('merch_centre', None), ('brightsight', None),
             ('dist_office', None), ('region', None), ('zone', None),
             ('struct', 'regionlist'), ('struct', 'zonelist'), ('club', None),
             ('member', None), ('club', 'officers'), ('struct', 'officers'),
             ('struct', 'chairs'), ('struct', 'mentors'), ('region', 'chair'),
             ('zone', 'chair')]
    if (obj, dest) not in pairs:
        # not a valid pairing, return a tailored error message
        return HttpResponse("/%s%s is an invalid location" %
                            (obj, dest and '/%s' % dest or ''))

    # if 'list' is in dest, do not use year
    if dest and ('list' in dest):
        use_year = False

    print 'looked up'
    # If user is a club user, redirect to suitable page for club objects, permission denied for others
    p = request.user.get_profile()
    if p.is_club:
        if obj == 'club':
            if not dest:
                # if club itself, go straight there
                return redirect('/%s/%s/' % (obj, p.club_id))
            elif not use_year:
                return redirect('/%s/%s/%s/' % (obj, dest, p.club_id))
            else:
                # ensure item_id is set the only club user can access
                item_id = int(p.club_id)
        else:
            # not a club, deny permission for anything else
            return render_to_response(
                'md_directory/not_auth.html', {
                    'response':
                    'You do not have the necessary permission to access the requested area'
                })

    print 'in find_s_mc_lobs_do_r_z_c'

    #create form to list item
    class Form(forms.Form):
        def __init__(self, *args, **kwargs):
            # inherit from parent Form
            super(Form, self).__init__(*args, **kwargs)
            # if item_id is not supplied, provide a selection dropdown
            self.no_entries = False
            if not item_id:
                # build a list of (item id, item) for the type of obj being found
                # determine if object should be filtered by district
                if p.is_dist:
                    source = get_model(obj).objects.filter(
                        struct=p.struct).filter(struct__in_use_b=1)
                else:
                    try:
                        # don't do struct in_use filtering for clubs to avoid
                        # needing a complicated query for the club_merge table
                        if obj == 'club':
                            raise Exception
                        if obj == 'struct':
                            source = get_model(obj).objects.filter(in_use_b=1)
                        else:
                            source = get_model(obj).objects.filter(
                                struct__in_use_b=1)
                            print 'used struct lookup'
                    except Exception as e:
                        source = get_model(obj).objects.all()
                        print 'no struct lookup'
                items = [(s.id, s) for s in source]
                if not items:
                    self.no_entries = True
                else:
                    self.fields[obj] = forms.ChoiceField(choices=items,
                                                         initial=items[0][0],
                                                         label=get_label(obj))
                    self.item = ''
                    self.label = ''
            else:
                # item id is supplied, use the name of the item instead of the dropdown
                self.item = get_model(obj).objects.get(pk=int(item_id))
                self.label = get_label(obj)
            # if there is a dest and a use_year, add a dropdown to pick the year of interest, as it is not the base object which will be edited
            if dest and use_year:
                (yl, initial) = get_years()
                # use the current year as the initial choice, as get_years will look one year into the future
                self.fields['year'] = forms.ChoiceField(
                    choices=yl,
                    initial=yl[initial][0],
                    label='Year of interest')

    if request.method == 'POST':
        form = Form(request.POST)
        if form.is_valid():
            # redirect to the specific destination page if use_year is True, the object's details page otherwise
            if not item_id:
                item_id = form.cleaned_data[obj]
            if dest:
                if use_year:
                    year_str = '%s/' % form.cleaned_data['year']
                else:
                    year_str = ''
                return redirect('/%s/%s/%s%s/' %
                                (obj, dest, year_str, item_id))
            else:
                return redirect('/%s/%s/' % (obj, item_id))
    else:
        # no POST, use an initial form
        form = Form()
    # determine if there are no entries, redirecting back to main page with a blurb if so
    if form.no_entries:
        return index(request, 'There are no %ss available' % get_label(obj),
                     '')
    return render_to_response(
        'md_directory/find_s_mc_lobs_do_r_z_c.html', {
            'form': form,
            'dest': dest,
            'type': obj,
            'item_id': item_id,
            'title': get_label(obj),
            'item': form.item,
            'label': form.label
        })
Exemple #22
0
def index_handler():
    return index()
def pg():
    index()
    return "k"
Exemple #24
0
 def test_al_ir_al_home_deberia_saludar(self):
     """
     Prueba que al ir al home se vea el mensaje
     'hola mundo'
     """
     self.assertIn('hola mundo', index({}).content)
Exemple #25
0
def index(news_item_id=0, title=None, page=1, drafts=False, tag='', recently_modified=False, year=0):
  return views.index(news_item_id, page, drafts, tag, recently_modified, year)
 def testSimple(self, mock_render, mock_Question):
     mock_request = Mock()
     result = index(mock_request)
     mock_render.assert_called_with(mock_request, 'polls/index.html', {'latest_question_list': mock_Question.objects.order_by('-pub_date')[:5]})
     self.assertEqual(result, mock_render())
Exemple #27
0
#!C:\Program Files\Python37\python.exe
print("Content-type:text/html\n\n")
# import win_unicode_console
# win_unicode_console.enable()

import views

html = views.head() + views.index() + views.footer()
#html=views.home()
#html= views.sody()
# ttml= views.head()
# ztml=views.home
print(html)
# print(ttml)
# print(ztml)
def handler(req):
    v.index(req)
Exemple #29
0
 def test_al_ir_al_home_deberia_abrir_index(self):
     """
     Prueba que es sitio este arriba y corrindo
     cuando se va a la raiz
     """
     self.assertEqual(index({}).status_code, 200)
Exemple #30
0
 def test_home_page_returns_correct_html(self):
     request = HttpRequest()
     response = index(request)
     self.assertIn(b'<title>Welcome to my blog</title>', response.content)
Exemple #31
0
    def test_index_1(self):
        """Test that index renders properly"""

        with app.test_request_context():
            self.assertEqual(index() is not None, True)
# </body>
# </html>
# '''

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((SERVER_HOST, SERVER_PORT))
server_socket.listen()

print(
    f'Servidor escutando em (ctrl+click): http://{SERVER_HOST}:{SERVER_PORT}')
while True:
    client_connection, client_address = server_socket.accept()

    request = client_connection.recv(1024).decode()

    route = extract_route(request)
    filepath = CUR_DIR / route
    if filepath.is_file():
        Respsota = build_response() + read_file(filepath)
    elif route == '':
        Resposta = index(request)
    else:
        Resposta = bytes()

    client_connection.sendall(Respostsa)

    client_connection.close()

server_socket.close()
Exemple #33
0
 def index():
     return views.index()
Exemple #34
0
def test_index():
    import views
    assert views.index() == 'Hello world'
Exemple #35
0
 def test_index(self):
     request = self.factory.get('/')
     response = views.index(request)
     self.assertEqual(response.status_code, 200)
    def test_index(self, mock_datetime, mock_render_template, mock_request):

        result = views.index()
        mock_request.assert_not_called()
        mock_datetime.datetime.now.assert_called_with()
        self.assertEqual(result, mock_render_template())