2016-05-13 5 views
2

Я новичок в web.py. Я следовал ex52 LPTHW, и мне приходилось выполнять nosetests во всех тестах в папке тестов. Но я получаю 1 неудачный тест из-за ошибки утверждения. Я пробовал читать разные ошибки утверждения и почему они происходят, но я не могу это выяснить. Я попытался расширить ошибки, которые сервер мог бы отобразить, например, 500 Internal, 400, но все еще не прошел тест. Я создал другой код только как упоминалось в книге: http://learnpythonthehardway.org/book/ex52.htmlPython-Assertion error при выполнении nosetests

Вот мой отслеживающий:

C:\lpthw\gothonweb>cd tests 

C:\lpthw\gothonweb\tests>nosetests 
Traceback (most recent call last): 
    File "C:\Python27\lib\site-packages\web\application.py", line 239, in process 
    return self.handle() 
    File "C:\Python27\lib\site-packages\web\application.py", line 230, in handle 
    return self._delegate(fn, self.fvars, args) 
    File "C:\Python27\lib\site-packages\web\application.py", line 420, in _delegate 
    return handle_class(cls) 
    File "C:\Python27\lib\site-packages\web\application.py", line 396, in handle_class 
    return tocall(*args) 
    File "C:\lpthw\gothonweb\bin\app.py", line 29, in GET 
    return render.hello_form() 
    File "C:\Python27\lib\site-packages\web\template.py", line 1017, in __getattr__ 
    t = self._template(name) 
    File "C:\Python27\lib\site-packages\web\template.py", line 1014, in _template 
    return self._load_template(name) 
    File "C:\Python27\lib\site-packages\web\template.py", line 1001, in _load_template 
    raise AttributeError, "No template named " + name 
AttributeError: No template named hello_form 

F... 
====================================================================== 
FAIL: tests.app_tests.test_index 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "C:\Python27\lib\site-packages\nose\case.py", line 197, in runTest 
    self.test(*self.arg) 
    File "C:\lpthw\gothonweb\tests\app_tests.py", line 12, in test_index 
    assert_response(resp) 
    File "C:\lpthw\gothonweb\tests\tools.py", line 5, in assert_response 
    assert status in resp.status, "Expected response %r not in %r" % (status , resp.status) 
AssertionError: Expected response '200' not in '500 Internal Server Error' 

---------------------------------------------------------------------- 
Ran 4 tests in 0.562s 

FAILED (failures=1) 

Мои тесты Код: app_tests.py

from nose.tools import * 
from bin.app import app 
from tests.tools import assert_response 

def test_index(): 
    #check that we get a 404 on the/URL 
    resp = app.request("/") 
    assert_response(resp, status= "404") 

    #test our first GET request to /hello 
    resp = app.request("/hello") 
    assert_response(resp) 

    #make sure default values work for the form 
    resp = app.request("/hello" , method="POST") 
    assert_response(resp , contains="Nobody") 

    #test that we get expected values 
    data = {'name':'Tejas','greet':'Ola!'} 
    resp = app.request("/hello " , method= "POST", data=data) 
    assert_response(resp , contains="Zed") 

tools.py:

from nose.tools import * 
import re 

def assert_response(resp, contains=None, matches=None, headers=None, status= "200"): 
    assert status in resp.status, "Expected response %r not in %r" % (status , resp.status) 

    if status == "200": 
     assert resp.data , "Response data is empty." 

    if contains: 
     assert contains in resp.data, "Response does not contain %r" % contains 

    if matches: 
     reg = re.compile(matches) 
     assert reg.matches(resp.data), "Response does not match %r" % matches 

    if headers: 
     assert_equal(resp.headers , headers) 

app.py code:

import web 
from gothonweb import map 

urls = (
     '/game' , 'GameEngine' , 
     '/' , 'Index', 
     ) 

app = web.application(urls, globals()) 
#little hack so that debug mode works with sessions 
if web.config.get('_session') is None: 
    store= web.session.DiskStore('sessions') 
    session= web.session.Session(app, store, initializer={'room':None}) 
    web.config._session = session 
else: 
    session= web.config._session 

render = web.template.render('templates/', base="layout") 

class Index(object): 
    def GET(self): 
     #this is used to "setup" the session with starting values 
     session.room= map.START 
     web.seeother("/game") 

class GameEngine(object): 
    def GET(self): 
     if session.room: 
      return render.show_room(room= session.room) 
     else: 
      #why is there here? do you need it? 
      return render.you_died() 

    def POST(self): 
     form= web.input(action=None) 

     if session.room and form.action: 
      session.room= session.room.go(form.action) 
     else: 
      session.room= None   


if __name__ == "__main__" : 
    app.run() 

После идти вперед с тренировкой теперь она дает мне 2 ошибки импорта: структура

PS C:\lpthw\gothonweb\tests> nosetests 
EE 
====================================================================== 
ERROR: Failure: SyntaxError (invalid syntax (app.py, line 2)) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "C:\Python27\lib\site-packages\nose\loader.py", line 418, in loadTestsFromName 
    addr.filename, addr.module) 
    File "C:\Python27\lib\site-packages\nose\importer.py", line 47, in importFromPath 
    return self.importFromDir(dir_path, fqname) 
    File "C:\Python27\lib\site-packages\nose\importer.py", line 94, in importFromDir 
    mod = load_module(part_fqname, fh, filename, desc) 
    File "C:\lpthw\gothonweb\tests\app_tests.py", line 2, in <module> 
    from bin.app import app 
    File "C:\lpthw\gothonweb\bin\app.py", line 2 
    from gothonweb import map.py 
          ^
SyntaxError: invalid syntax 

====================================================================== 
ERROR: Failure: ImportError (cannot import name map) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "C:\Python27\lib\site-packages\nose\loader.py", line 418, in loadTestsFromName 
    addr.filename, addr.module) 
    File "C:\Python27\lib\site-packages\nose\importer.py", line 47, in importFromPath 
    return self.importFromDir(dir_path, fqname) 
    File "C:\Python27\lib\site-packages\nose\importer.py", line 94, in importFromDir 
    mod = load_module(part_fqname, fh, filename, desc) 
    File "C:\lpthw\gothonweb\tests\map_tests.py", line 2, in <module> 
    from gothonweb import map 
ImportError: cannot import name map 

---------------------------------------------------------------------- 
Ran 2 tests in 0.002s 

FAILED (errors=2) 

каталога:

C:/lpthw/ 
    gothonweb/ 
    bin build dist doc sessions Gothonweb templates tests map.py app.py 
tests/ 
map_tests.py 
app_tests.py 
__init__.py 
tools.py 

Что я должен сделать, чтобы исправить ошибку? Спасибо за предложения.

+0

AssertionError не является вашей проблемой, это AttributeError, которую вы должны исследовать. –

+0

В частности, ваша ошибка указана в строке 29 в app.py, код, который вы не предоставили. –

+0

Я обновил его с помощью кода app.py, но я думаю, что нам пришлось изменить app.py вперед в упражнении, которое у меня есть, так что это не то же самое приложение app.py, как и раньше, поскольку нам пришлось добавить несколько вещей. –

ответ

0

Для этой ошибки,

"AttributeError: No template named hello_form"

использовать абсолютный путь и посмотреть, что работает, а

"render = web.template.render('templates/', base="layout")

попробовать:

"render = web.template.render('C:/lpthw/gothonweb/bin/templates', base="layout") 
0

Удивительно, но ваш тест имеет не имеет ничего общего с app.py.

from nose.tools import * 
from bin.app import app 
from tests.tools import assert_response 

def test_index(): 
    #check that we get a 404 on the/URL 
    resp = app.request("/") 
    assert_response(resp, status= "404") 

    #test our first GET request to /hello 
    resp = app.request("/hello") 
    assert_response(resp) 

    #make sure default values work for the form 
    resp = app.request("/hello" , method="POST") 
    assert_response(resp , contains="Nobody") 

    #test that we get expected values 
    data = {'name':'Tejas','greet':'Ola!'} 
    resp = app.request("/hello " , method= "POST", data=data) 
    assert_response(resp , contains="Zed") 

App.py

import web 
from gothonweb import map 

urls = (
     '/game' , 'GameEngine' , 
     '/' , 'Index', 
     ) 

app = web.application(urls, globals()) 
#little hack so that debug mode works with sessions 
if web.config.get('_session') is None: 
    store= web.session.DiskStore('sessions') 
    session= web.session.Session(app, store, initializer={'room':None}) 
    web.config._session = session 
else: 
    session= web.config._session 

render = web.template.render('templates/', base="layout") 

class Index(object): 
    def GET(self): 
     #this is used to "setup" the session with starting values 
     session.room= map.START 
     web.seeother("/game") 

class GameEngine(object): 
    def GET(self): 
     if session.room: 
      return render.show_room(room= session.room) 
     else: 
      #why is there here? do you need it? 
      return render.you_died() 

    def POST(self): 
     form= web.input(action=None) 

     if session.room and form.action: 
      session.room= session.room.go(form.action) 
     else: 
      session.room= None   


if __name__ == "__main__" : 
    app.run() 

Вы можете видеть, как они не связаны

Ваш первый тест говорит, что вы должны получить 404 на URL '/', но это будет только если «/» не существует. Ваш код app.py ясно показывает, что '/' вызывает GET в классе Index.

Второй тест, resp = app.request("/hello") теперь, даст вам 404 ошибку, потому что URL не существует на app.py

То же самое касается третьего теста, как «/ привет» не существует в ваш кортеж URL-адресов в приложении.ру

И пятое испытание, а

Хотя тесты являются недействительными, основной проблемой вы хотя пытается выполнить автоматический тест внутри каталога тестов; это неверно.

C:\lpthw\gothonweb\tests> nosetests 

Это не то, что нужно сделать, вы должны быть каталогом ниже для всех ваших импорта работать, например, в app_tests вы пытаетесь импортировать бен/app.py, но это не в «тестах» каталог

ли это вместо

C:\lpthw\gothonweb> nosetests 

Таким образом, все файлы, которые вам нужно будет импортировать
Назад к app_tests.py. Я выписываю очень простой тест, который на самом деле, связанный с app.py

from bin.app import app 
from test.tools import assert_response 

def test_index(): 
    #check that we get a 303 on the/url 
    #this is because web.seeother() will always send the browser this http code 
    resp = app.request("/") 
    assert_response(resp, status= "303") 

def test_game(): 
    #check that we get a 200 on /game 
    resp = app.request("/game") 
    assert_response(resp, status = '200') 

    #check that we have response data on a form sumbit 
    resp = app.request("/game", method = 'POST') 
    aseert_response(resp.data) 
0

В assertion_error вы получаете, потому что ваш RAN nosetests в этом каталоге

/gothroweb/тест

вы должны запустить его в /gothroweb

bin docs gothonweb templates tests 

./bin: 
app.py app.pyc __init__.py __init__.pyc 

./docs: 

./gothonweb: 
__init__.py __init__.pyc 

./templates: 
hello_form.html index.html layout.html 

./tests: 
app_tests.py __init__.py test.html tools.pyc 
app_tests.pyc __init__.pyc tools.py 

cheers