def test_get_source_code(client_fixture_with_runner: fixture) -> None: # check invalid task page = client_fixture_with_runner.get("/task/99/source_code") assert page.status_code == 200 # there should be a log assert ( TaskLog.query.filter_by(status_id=7, error=1, task_id=99) .filter(TaskLog.message.like("%Failed to get source code%")) # type: ignore[union-attr] .first() is not None ) # check valid task _, t_id = create_demo_task() # change source type to code Task.query.filter_by(id=t_id).update( {"source_type_id": 4, "source_code": "something cool"} ) db.session.commit() page = client_fixture_with_runner.get( url_for("task_bp.task_get_source_code", task_id=t_id), follow_redirects=False ) assert page.status_code == 200 assert "something cool" in page.get_data(as_text=True)
def test_schedule(client_fixture: fixture) -> None: p_id, t_id = create_demo_task() page = client_fixture.get(f"/api/add/{t_id}") assert page.json == {"message": "Scheduler: task job added!"} assert page.status_code == 200 # check that status is now enabled t = Task.query.get(t_id) assert t.enabled == 1 p_id, t_id = create_demo_task(2021) page = client_fixture.get(f"/api/add/{t_id}") assert page.json == {"message": "Scheduler: task job added!"} assert page.status_code == 200 # check that status is now enabled t = Task.query.get(t_id) assert t.enabled == 1 # add a maintenance task atlas_scheduler.add_job( func=demo_task, trigger="interval", hours=1, id="job_sync", name="job_sync", replace_existing=True, ) page = client_fixture.get(f"/api/schedule") assert {"case": "now", "count": 0} in page.json assert page.status_code == 200
def travis_setup(request: pytest.fixture) -> None: """Set up Chrome's cookies file and directory on Travis. Appropriately doesn't load teardown() this dir already exists, preventing it from getting to the teardown function which would otherwise risk deleting someone's ~/.config/google-chrome directory (if they had the TRAVIS=true environment set for some reason). """ def teardown() -> None: """Remove the cookies directory.""" os.remove(cookies_dest) try: os.removedirs(cookies_dest_dir) except OSError: # Directory wasn't empty, expected at '~' pass # Where the cookies file should be cookies_dest_dir = os.path.expanduser('~/.config/google-chrome/Default') cookies_dest = os.path.join(cookies_dest_dir, 'Cookies') # Where the test cookies file is cookies_dir = os.path.dirname(os.path.abspath(__file__)) cookies_path = os.path.join(cookies_dir, 'Cookies') if all([os.getenv('TRAVIS') == 'true', sys.platform.startswith('linux'), not os.path.isfile(cookies_dest)]): os.makedirs(cookies_dest_dir) shutil.copy(cookies_path, cookies_dest_dir) # Only teardown if running on travis request.addfinalizer(teardown)
def test_details(client_fixture: fixture) -> None: p_id, t_id = create_demo_task() page = client_fixture.get(f"/api/add/{t_id}") assert page.json == {"message": "Scheduler: task job added!"} assert page.status_code == 200 # check that status is now enabled t = Task.query.get(t_id) assert t.enabled == 1 # job with no args atlas_scheduler.add_job( func=demo_task, trigger="interval", seconds=10, id="test job 3", name="test job 3", replace_existing=True, ) page = client_fixture.get(f"/api/details") job = atlas_scheduler.get_job(f"{p_id}-{t.id}-cron") text = page.json[0] del text["next_run_time"] assert text == { "name": job.name, "job_id": job.id, "id": job.args[0], } assert page.status_code == 200
def test_login( client: fixture, mock_verification_code_email: fixture, clear_db: fixture, insert_test_user: fixture, ): # 尝试登录 post_data = {"email": TEST_EMAIL, "password": TEST_PASSWORD} r = client.post(LOGIN_URL, data=post_data) assert r.status_code == 200 response_data = json.loads(r.get_data()) assert len(response_data.get("data", {}).get("token")) > 0 # 密码错误 post_data = {"email": TEST_EMAIL, "password": ""} r = client.post(LOGIN_URL, data=post_data) assert r.status_code == 400 response_data = json.loads(r.get_data()) assert "Invalid email or password" in response_data.get("message", "") # 用户不存在 post_data = {"email": "wrong_user", "password": TEST_PASSWORD} r = client.post(LOGIN_URL, data=post_data) assert r.status_code == 400 response_data = json.loads(r.get_data()) assert "User not exists" in response_data.get("message", "") # 空用户名 post_data = {"email": "", "password": TEST_PASSWORD} r = client.post(LOGIN_URL, data=post_data) assert r.status_code == 400 response_data = json.loads(r.get_data()) assert "User not exists" in response_data.get("message", "")
def test_pause_resume(client_fixture: fixture) -> None: # add a job p_id, t_id = create_demo_task() page = client_fixture.get(f"/api/add/{t_id}") assert page.json == {"message": "Scheduler: task job added!"} assert page.status_code == 200 # pause page = client_fixture.get(f"/api/pause") assert page.json == {"message": "Scheduler: all jobs paused!"} assert page.status_code == 200 assert atlas_scheduler.state == 2 assert atlas_scheduler.running == True page = client_fixture.get(f"/api/resume") assert page.json == {"message": "Scheduler: all jobs resumed!"} assert page.status_code == 200 assert atlas_scheduler.state == 1 assert atlas_scheduler.running == True # resume with scheduler already enabled page = client_fixture.get(f"/api/resume") assert page.json == {"message": "Scheduler: all jobs resumed!"} assert page.status_code == 200 assert atlas_scheduler.state == 1 assert atlas_scheduler.running == True
def test_next(client_fixture: fixture) -> None: username = "******" password = "" page = client_fixture.post( "/login?next=https://nothing?asdf=asdf", data={ "user": username, "password": password }, ) assert page.status_code == 400 # check a valid next page = client_fixture.post("/login?next=https://localhost/", data={ "user": username, "password": password }) assert page.status_code == 302 # check an invalid next page = client_fixture.post("/login?next=https://google.com/", data={ "user": username, "password": password }) assert page.status_code == 400
def test_enable_disable_project(client_fixture: fixture) -> None: p_id, t_id = create_demo_task() page = client_fixture.get( url_for("project_bp.enable_all_project_tasks", project_id=p_id), follow_redirects=True, ) assert page.status_code == 200 # check redirect assert request.path == url_for("project_bp.one_project", project_id=p_id) # will still show disabled, scheduler is offline # sleep to let executor run time.sleep(1) assert Task.query.filter_by(id=t_id).first().enabled == 0 # manual enable Task.query.filter_by(id=t_id).update({"enabled": 1}) db.session.commit() assert Task.query.filter_by(id=t_id).first().enabled == 1 page = client_fixture.get( url_for("project_bp.disable_all_project_tasks", project_id=p_id), follow_redirects=True, ) assert page.status_code == 200 # check logs for scheduler offline error # check that task was rescheduled # assert TaskLog.query.filter_by(task_id=t_id, error=1, status_id=7).filter(TaskLog.message.like("%Failed to schedule task.%")).first() is not None # type: ignore[union-attr] # check that task is disabled.. will fail with scheduler offline assert Task.query.filter_by(id=t_id).first().enabled == 1 # check redirect assert request.path == url_for("project_bp.one_project", project_id=p_id)
def test_delete_all(client_fixture: fixture) -> None: page = client_fixture.get(f"/api/delete") assert page.json == {"message": "Scheduler: all jobs deleted!"} assert page.status_code == 200 # one maintenance job should be left assert len(atlas_scheduler.get_jobs()) == 0 # add a job with no args from .conftest import demo_task atlas_scheduler.add_job( func=demo_task, trigger="interval", seconds=10, id="test job 2", name="test job 2", replace_existing=True, ) # add a job and try again p_id, t_id = create_demo_task() page = client_fixture.get(f"/api/add/{t_id}") assert page.json == {"message": "Scheduler: task job added!"} assert page.status_code == 200 page = client_fixture.get(f"/api/delete") assert page.json == {"message": "Scheduler: all jobs deleted!"} assert page.status_code == 200 # one job should be left assert len(atlas_scheduler.get_jobs()) == 1
def test_job_missed(event_fixture: fixture, caplog: fixture) -> None: # grace time is 30 seconds, so attempt to run 40 seconds ago # get a task ID.. task isnt' used p_id, t_id = create_demo_task() # create an interval task (only interval and cron can capture # a missed job and add to logs. one-off jobs disappear after run.) atlas_scheduler.add_job( func=demo_task, trigger="date", id=f"{p_id}-{t_id}-ooff", name="test job 2", args=[str(t_id)], run_date=datetime.now() - timedelta(minutes=1), replace_existing=True, ) # wait for logs to be added by background process time.sleep(1) # check that log was added log = TaskLog.query.filter_by(task_id=t_id, status_id=6, error=1).first() assert "Job missed. Scheduled for:" in log.message # check logs assert "was missed by 0:01" in caplog.text for record in caplog.records: assert record.levelname not in ["CRITICAL", "ERROR"] caplog.clear() # check without id atlas_scheduler.add_job( func=demo_task, trigger="date", id="asdf", name="test job 2", args=[str(t_id)], run_date=datetime.now() - timedelta(minutes=1), replace_existing=True, ) time.sleep(1) assert "was missed by 0:01" in caplog.text caplog.clear() # task that does not exists p_id, t_id = (9, 9) atlas_scheduler.add_job( func=demo_task, trigger="date", id=f"{p_id}-{t_id}-ooff", name="test job 2", args=[str(t_id)], run_date=datetime.now() - timedelta(minutes=1), replace_existing=True, ) # wait for logs to be added by background process time.sleep(1) # check that log was added log = TaskLog.query.filter_by(task_id=t_id, status_id=6, error=1).first() assert "Job missed. Scheduled for:" in log.message
def selenium(selenium: fixture) -> WebDriver: """Override the base Selenium settings. :param selenium: Fixture for running an instantiation of Selenium webdriver. """ selenium.delete_all_cookies() selenium.maximize_window() return selenium
def login(client_fixture: fixture, username: str, password: str) -> Response: # 302 becuase tests autologin. assert client_fixture.get("/login").status_code == 302 return client_fixture.post( url_for("auth_bp.login"), data=dict(user=username, password=password), follow_redirects=True, )
def test_working_check(self, caplog: pytest.fixture, complete_family_dict: dict): caplog.set_level(logging.INFO) all_samples = {"HG00607", "HG00619", "HG00623", "HG00657"} check_samples_in_mt( sample_names=all_samples, family_structures=complete_family_dict, mat=self.mt, )
def test_job_error(event_fixture: fixture, caplog: fixture) -> None: # get a dummy task id p_id, t_id = create_demo_task() # add a task that will fail atlas_scheduler.add_job( func=bad_demo_task, trigger="date", id=f"{p_id}-{t_id}-ooff", name="test job 2", replace_existing=True, ) time.sleep(1) # verify failure log = ( TaskLog.query.filter_by(task_id=t_id, status_id=6, error=1).filter( TaskLog.message.like("%Job error. Scheduled for:%") ) # type: ignore[attr-defined,union-attr] .first()) assert log is not None assert "raised an exception" in caplog.text caplog.clear() # try with invalid job p_id, t_id = (9, 9) atlas_scheduler.add_job( func=bad_demo_task, trigger="date", id=f"{p_id}-{t_id}-ooff", name="test job 2", replace_existing=True, ) time.sleep(1) # verify failure log = ( TaskLog.query.filter_by(task_id=t_id, status_id=6, error=1).filter( TaskLog.message.like("%Job error. Scheduled for:%") ) # type: ignore[attr-defined,union-attr] .first()) assert log is None # test job without id atlas_scheduler.add_job( func=bad_demo_task, trigger="date", id="ooff", name="test job 2", replace_existing=True, ) time.sleep(1)
def test_mountain_project_api_exception(self, app: pytest.fixture) -> None: """Confirms the correct response status and safe error message of MPAPIException.""" monkeypatch = MonkeyPatch() monkeypatch.setattr(requests, "get", self.mock_get_response) client = app.test_client() app.config[ "MPV_DEV"] = False # dev_env to False so a mocked request will be made. response = client.post("/data") assert response.status == "403 FORBIDDEN" assert MPAPIException.msg in response.data.decode("utf-8")
def test_tasks_home(client_fixture: fixture) -> None: # check with no tasks page = client_fixture.get("/task", follow_redirects=True) assert page.status_code == 200 # no projects exists so go to new project assert request.path == url_for("project_bp.new_project") # add a task create_demo_task() page = client_fixture.get("/task", follow_redirects=False) assert page.status_code == 200
def test_request_exception(self, app: pytest.fixture) -> None: """Confirms the correct response status and safe error message of RequestException.""" monkeypatch = MonkeyPatch() monkeypatch.setattr(requests, "get", self.raise_http_error) client = app.test_client() app.config[ "MPV_DEV"] = False # dev_env to False so a mocked request will be made. response = client.post("/data") assert response.status == "400 BAD REQUEST" assert RequestException.msg in response.data.decode("utf-8")
def test_token_test(client: fixture, login_client: fixture): # 未登录用户无法访问 r = client.get(TOKEN_TEST_URL) assert r.status_code == 401 response_data = json.loads(r.get_data()) assert "Unauthorized" in response_data.get("message", "") # 带token可以访问 r = login_client.get(TOKEN_TEST_URL, headers=login_client.headers) assert r.status_code == 200 response_data = json.loads(r.get_data()) assert "token verified" in response_data.get("message", "")
def test_task_status(client_fixture: fixture) -> None: # test invalid task page = client_fixture.get( url_for("task_controls_bp.task_status", task_id=99)) assert page.status_code == 200 assert json.loads(page.get_data(as_text=True)) == {} _, t_id = create_demo_task() page = client_fixture.get( url_for("task_controls_bp.task_status", task_id=t_id)) assert page.status_code == 200 assert json.loads(page.get_data(as_text=True))["status"] == ""
def test_jobs(client_fixture: fixture) -> None: p_id, t_id = create_demo_task() page = client_fixture.get(f"/api/add/{t_id}") assert page.json == {"message": "Scheduler: task job added!"} assert page.status_code == 200 # check that status is now enabled t = Task.query.get(t_id) assert t.enabled == 1 # job should be in list page = client_fixture.get(f"/api/jobs") assert page.json == [t_id, t_id, t_id] # we have 3 schedules assert page.status_code == 200
def test_greeting(capsys: pytest.fixture): """Test out the function by capturing its output with capsys.""" greeting('Person') out, err = capsys.readouterr() assert out == 'Hi, Person\n' assert err == '' # Any previous outputs are captured, no matter how many print # calls there are. greeting('John') greeting('Mark') out, err = capsys.readouterr() assert out == 'Hi, John\nHi, Mark\n' assert err == ''
def login_client(app: fixture, client: fixture, insert_test_user: fixture): """test login client""" with app.app_context(): data = { "email": TEST_EMAIL, "password": TEST_PASSWORD, } res = client.post(LOGIN_URL, data=data) access_token = json.loads(res.get_data()).get("data", {}).get("token") assert len(access_token) > 0 headers = {"Authorization": "Bearer " + access_token} client.token = access_token client.headers = headers return client
def test_one_task(client_fixture: fixture) -> None: # check invalid task page = client_fixture.get("/task/99", follow_redirects=True) assert page.status_code == 200 # no projects exists so go to new project assert request.path == url_for("task_bp.all_tasks") assert "Task does not exist." in page.get_data(as_text=True) # check valid task _, t_id = create_demo_task() page = client_fixture.get( url_for("task_bp.one_task", task_id=t_id), follow_redirects=False ) assert page.status_code == 200
def test_new_task_get(client_fixture: fixture) -> None: # test with invalid project page = client_fixture.get(url_for("task_edit_bp.task_new_get", project_id=99), follow_redirects=True) assert page.status_code == 200 assert request.path == url_for("project_bp.new_project_form") assert "Project does not exist" in page.get_data(as_text=True) # try with valid project p_id, _ = create_demo_task() page = client_fixture.get(url_for("task_edit_bp.task_new_get", project_id=p_id), follow_redirects=False) assert page.status_code == 200
def test_edit_task_get(client_fixture: fixture) -> None: # test with invalid project page = client_fixture.get(url_for("task_edit_bp.task_edit_get", task_id=99), follow_redirects=True) assert page.status_code == 200 assert request.path == url_for("task_bp.all_tasks") assert "Task does not exist" in page.get_data(as_text=True) # try with valid project _, t_id = create_demo_task() page = client_fixture.get(url_for("task_edit_bp.task_edit_get", task_id=t_id), follow_redirects=False) assert page.status_code == 200
def test_orphaned_delete(client_fixture: fixture) -> None: response = client_fixture.get("/dash/orphans/delete", follow_redirects=True) assert response.status_code == 200 assert "Failed to delete orphans. Scheduler offline." in response.get_data( as_text=True)
def test_table_tasks_files(client_fixture: fixture) -> None: from web.model import Task task = Task.query.first() if task: assert (client_fixture.get("/table/task/" + str(task.id) + "/files").status_code == 200)
def test_kill(client_fixture: fixture) -> None: page = client_fixture.get(f"/api/kill") assert page.json == {"message": "Scheduler: scheduler killed!"} assert page.status_code == 200 assert atlas_scheduler.state == 0 assert atlas_scheduler.running == False
def test_my_tasks(client_fixture: fixture) -> None: # remove everyting db.session.query(Task).delete(synchronize_session=False) db.session.commit() db.session.query(Project).delete(synchronize_session=False) db.session.commit() # check with no tasks page = client_fixture.get("/task/mine", follow_redirects=True) assert page.status_code == 200 # no projects exists so go to new project assert request.path == url_for("project_bp.new_project") # add a task create_demo_task() page = client_fixture.get("/task/mine", follow_redirects=False) assert page.status_code == 200
def test_booking(self, ride_factory: fixture, service: fixture) -> None: """Input valid ride information for an asap ride, then check for a success state. This test is part of the smoke testing battery. Test failure should result in immediate remediation efforts as it is a main feature for the application. """ ride: Ride = ride_factory.build() self.booking.visit() if self.booking.agency_select_modal.loaded: self.booking.agency_select_modal.select_agency(AGENCY) if self.booking.service_select_modal.loaded: service_id = service['service_id'] self.booking.service_select_modal.select_service_by_id(service_id) self.booking.pick_up_time_modal.submit_pickup_time() self.booking.fill_ride_form(ride) self.booking.ride_details_modal.submit_ride() assert (self.booking.ride_overview_modal.drop_off == ride.dropoff['address'] and self.booking.ride_overview_modal.pick_up == ride.pickup['address'])
async def test_select_user(tables: fixture, sa_engine: fixture) -> None: async with sa_engine.acquire() as conn: res = await select_user_by_id(conn, 1) assert res.id == 1