Open leo-frison opened 6 years ago
Hola Pega acá el archivo de test así lo miro
import unittest import os import time import threading
from selenium import webdriver
from app import create_app, db from app.models import Product, Order, OrderProduct
basedir = os.path.abspath(os.path.dirname(file))
from werkzeug.serving import make_server
class Ordering(unittest.TestCase):
def setUp(self):
self.app = create_app()
self.app.config.update(
SQLALCHEMY_DATABASE_URI='sqlite:///' + os.path.join(basedir, 'test.db'),
SQLALCHEMY_TRACK_MODIFICATIONS=False,
TESTING=True
)
self.app_context = self.app.app_context()
self.app_context.push()
self.baseURL = 'http://localhost:5000'
db.session.commit()
db.drop_all()
db.create_all()
self.t = threading.Thread(target=self.app.run)
self.t.start()
time.sleep(1)
self.driver = webdriver.Firefox()
def test_title(self):
driver = self.driver
driver.get(self.baseURL)
add_product_button = driver.find_element_by_xpath('/html/body/main/div[1]/div/button')
add_product_button.click()
modal = driver.find_element_by_id('modal')
assert modal.is_displayed(), "El modal no esta visible"
def tearDown(self):
self.driver.get('http://localhost:5000/shutdown')
db.session.remove()
db.drop_all()
self.driver.close()
self.app_context.pop()
if name == "main": unittest.main()
No te abre la aplicación al correr el test?
Hola, a mi el test de integración me tira el siguiente error (la aplicación me abre y se queda cargando, y después me tira este error): ============================= test session starts ============================= platform win32 -- Python 3.6.5, pytest-3.5.1, py-1.5.3, pluggy-0.6.0 rootdir: C:\Users\Luciano\Documents\projectGIT\orderingg\test, inifile: collected 1 item
test_e2e.py DevTools listening on ws://127.0.0.1:12994/devtools/browser/4ecf53d9-a59a-4cfe-bdd4-d70db78dbab9 F [100%]
================================== FAILURES =================================== _____ Ordering.testtitle ____
self =
def tearDown(self):
self.driver.get('http://localhost:5000/shutdown')
test_e2e.py:50:
c:\python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py:326: in get self.execute(Command.GET, {'url': url}) c:\python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py:314: in execute self.error_handler.check_response(response)
self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x051C9B10> response = {'sessionId': '51f97a8501074d8b88e888d9cebd7f10', 'status': 21, 'value': {'message': 'timeout\n (Session info: chrome...ver info: chromedriver=2.38.552522 (437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Windows NT 10.0.17134 x86_64)'}}
def check_response(self, response):
"""
Checks that a JSON response from the WebDriver does not have an error.
:Args:
- response - The JSON response from the WebDriver server as a dictionary
object.
:Raises: If the response contains an error message.
"""
status = response.get('status', None)
if status is None or status == ErrorCode.SUCCESS:
return
value = None
message = response.get("message", "")
screen = response.get("screen", "")
stacktrace = None
if isinstance(status, int):
value_json = response.get('value', None)
if value_json and isinstance(value_json, basestring):
import json
try:
value = json.loads(value_json)
if len(value.keys()) == 1:
value = value['value']
status = value.get('error', None)
if status is None:
status = value["status"]
message = value["value"]
if not isinstance(message, basestring):
value = message
message = message.get('message')
else:
message = value.get('message', None)
except ValueError:
pass
exception_class = ErrorInResponseException
if status in ErrorCode.NO_SUCH_ELEMENT:
exception_class = NoSuchElementException
elif status in ErrorCode.NO_SUCH_FRAME:
exception_class = NoSuchFrameException
elif status in ErrorCode.NO_SUCH_WINDOW:
exception_class = NoSuchWindowException
elif status in ErrorCode.STALE_ELEMENT_REFERENCE:
exception_class = StaleElementReferenceException
elif status in ErrorCode.ELEMENT_NOT_VISIBLE:
exception_class = ElementNotVisibleException
elif status in ErrorCode.INVALID_ELEMENT_STATE:
exception_class = InvalidElementStateException
elif status in ErrorCode.INVALID_SELECTOR \
or status in ErrorCode.INVALID_XPATH_SELECTOR \
or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER:
exception_class = InvalidSelectorException
elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE:
exception_class = ElementNotSelectableException
elif status in ErrorCode.ELEMENT_NOT_INTERACTABLE:
exception_class = ElementNotInteractableException
elif status in ErrorCode.INVALID_COOKIE_DOMAIN:
exception_class = InvalidCookieDomainException
elif status in ErrorCode.UNABLE_TO_SET_COOKIE:
exception_class = UnableToSetCookieException
elif status in ErrorCode.TIMEOUT:
exception_class = TimeoutException
elif status in ErrorCode.SCRIPT_TIMEOUT:
exception_class = TimeoutException
elif status in ErrorCode.UNKNOWN_ERROR:
exception_class = WebDriverException
elif status in ErrorCode.UNEXPECTED_ALERT_OPEN:
exception_class = UnexpectedAlertPresentException
elif status in ErrorCode.NO_ALERT_OPEN:
exception_class = NoAlertPresentException
elif status in ErrorCode.IME_NOT_AVAILABLE:
exception_class = ImeNotAvailableException
elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED:
exception_class = ImeActivationFailedException
elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS:
exception_class = MoveTargetOutOfBoundsException
elif status in ErrorCode.JAVASCRIPT_ERROR:
exception_class = JavascriptException
elif status in ErrorCode.SESSION_NOT_CREATED:
exception_class = SessionNotCreatedException
elif status in ErrorCode.INVALID_ARGUMENT:
exception_class = InvalidArgumentException
elif status in ErrorCode.NO_SUCH_COOKIE:
exception_class = NoSuchCookieException
elif status in ErrorCode.UNABLE_TO_CAPTURE_SCREEN:
exception_class = ScreenshotException
elif status in ErrorCode.ELEMENT_CLICK_INTERCEPTED:
exception_class = ElementClickInterceptedException
elif status in ErrorCode.INSECURE_CERTIFICATE:
exception_class = InsecureCertificateException
elif status in ErrorCode.INVALID_COORDINATES:
exception_class = InvalidCoordinatesException
elif status in ErrorCode.INVALID_SESSION_ID:
exception_class = InvalidSessionIdException
elif status in ErrorCode.UNKNOWN_METHOD:
exception_class = UnknownMethodException
else:
exception_class = WebDriverException
if value == '' or value is None:
value = response['value']
if isinstance(value, basestring):
if exception_class == ErrorInResponseException:
raise exception_class(response, value)
raise exception_class(value)
if message == "" and 'message' in value:
message = value['message']
screen = None
if 'screen' in value:
screen = value['screen']
stacktrace = None
if 'stackTrace' in value and value['stackTrace']:
stacktrace = []
try:
for frame in value['stackTrace']:
line = self._value_or_default(frame, 'lineNumber', '')
file = self._value_or_default(frame, 'fileName', '<anonymous>')
if line:
file = "%s:%s" % (file, line)
meth = self._value_or_default(frame, 'methodName', '<anonymous>')
if 'className' in frame:
meth = "%s.%s" % (frame['className'], meth)
msg = " at %s (%s)"
msg = msg % (meth, file)
stacktrace.append(msg)
except TypeError:
pass
if exception_class == ErrorInResponseException:
raise exception_class(response, message)
elif exception_class == UnexpectedAlertPresentException:
alert_text = None
if 'data' in value:
alert_text = value['data'].get('text')
elif 'alert' in value:
alert_text = value['alert'].get('text')
raise exception_class(message, screen, stacktrace, alert_text)
raise exception_class(message, screen, stacktrace)
E selenium.common.exceptions.TimeoutException: Message: timeout E (Session info: chrome=66.0.3359.181) E (Driver info: chromedriver=2.38.552522 (437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Windows NT 10.0.17134 x86_64)
c:\python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py:242: TimeoutException ========================= 1 failed in 310.17 seconds ==========================
Actualizaste el routes.py?
sisi, te paso lo que dice en el routes. from sqlalchemy import and_
from app import db from app.models import Product, Order, OrderProduct from flask import request, jsonify, render_template, abort, current_app
from flask import Blueprint rest = Blueprint('rest', name, template_folder='templates')
@rest.route("/") def hello(): return render_template('orders.html')
@rest.route("/product", methods=['GET', 'POST']) def products(): """ Endpoint para obtener todos los productos o crear uno nuevo :return: """ if request.method == 'POST':
# Ejemplo: {'name': 'Tenedor', 'price': 50}
p = Product(name=request.get_json()['name'], price=request.get_json()['price'])
db.session.add(p)
db.session.commit()
return jsonify(p.serialize)
else:
# Obtiene todos los productos disponibles
p = Product.query.all()
return jsonify([i.serialize for i in p])
@rest.route("/order", methods=['GET']) def orders(): """ Obtiene todas las ordenes """
orders = Order.query.all()
return jsonify([order.serialize for order in orders])
@rest.route("/order/pk
Si no se encuentra la orden, se responde con un 404
"""
# obtenemos las ordenes
order = Order.query.get(pk)
# Si la orden no existe, levantamos el error
if (not order):
return jsonify({ 'error': 'not-found' }), 404
return jsonify(order.serialize)
@rest.route("/order/
order = Order.query.get(pk)
# Si la orden no existe, levantamos el error
if (not order):
return jsonify({ 'error': '<order {}> not found'.format(pk) }), 404
product_data = request.get_json()
product = product_data['product']
product_exists = any([
p.product.id == product['id'] for p in order.products
])
# Si el producto existe en la orden levantamos el error
if (product_exists):
return jsonify({
'error': '<product {}> exists in <order {}>. Use PUT method'
.format(product['id'], pk)
}), 400
orderProduct = OrderProduct(quantity=product_data['quantity'])
orderProduct.product = Product.query.get(product['id'])
order.products.append(orderProduct)
db.session.add(order)
db.session.commit()
return jsonify(order.serialize), 201
@rest.route("/order/
order_product = OrderProduct.query.filter(and_(OrderProduct.order_id==pk_order, OrderProduct.product_id==pk_product)).all()[0]
if (not order_product):
return jsonify({ 'error': 'not-found' }), 404
order_product_json = order_product.serialize
if request.method == 'PUT':
new_quantity = request.get_json().get('quantity', False)
if (new_quantity):
order_product.quantity = int(new_quantity)
order_product_json = order_product.serialize
if request.method == 'GET':
return jsonify(order_product_json)
if request.method == 'DELETE':
db.session.delete(order_product)
db.session.commit()
return jsonify(order_product_json)
@rest.route('/shutdown') def server_shutdown(): if not current_app.testing: abort(404) shutdown = request.environ.get('werkzeug.server.shutdown') if not shutdown: abort(500)
shutdown()
return 'Shutting down...'
Es raro porque el error que te da es que no tenes la ruta /shutdown
. Podes hacer un branch y pushearlo así lo reviso mejor
te paso el link: https://github.com/luchoCap/orderingg/tree/test_unidad/%231
La aplicacion ? ... yo ejecuto el testeo desde la terminal y se ejecuta .. se abre el host y queda corriendo indefinidamente .. no me muestra ningun error .. veo lo que te pase en la captura ..
@leo-frison , si te bajaste el codigo ayer o antes de ayer no te va a andar porque hicimos un arreglo para los que usan windows que tenian un problema al ejecutar el e2e. Hace un checkout del anteultimo commit
@RodrigoJacznik alguna novedad del problema?
@luchoCap Recien lo pude probar, fíjate que en el test no tenes productos cargados, entonces falla al querer abrir el modal. Si el test parece que se colgó, abrí la consola de chrome (F12).
Hola, me sigue tirando el mismo error que antes incluso con los productos cargados. El modal lo abre pero después de eso es que se queda esperando.
ahora si funciona :)
Solucione el inconveniente anterior .. logre abrir el host .. el problema es que me queda asi : https://user-images.githubusercontent.com/38389932/40585488-01766c28-618a-11e8-8d9e-575b4dbfd34d.png lo interrumpo con el ctrl -c ... no me devuelve nada concreto ... que deberia hacer ?