def test_get_window_end(database):
    """ Tests get_window_end with subs """
    sess = database.session
    quart_sub = SubmissionFactory(submission_id=1,
                                  reporting_fiscal_year=2020,
                                  reporting_fiscal_period=6,
                                  d2_submission=False,
                                  is_quarter_format=True)
    month_sub = SubmissionFactory(submission_id=2,
                                  reporting_fiscal_year=2020,
                                  reporting_fiscal_period=10,
                                  d2_submission=False,
                                  is_quarter_format=False)
    fail_sub = SubmissionFactory(submission_id=3,
                                 reporting_fiscal_year=2020,
                                 reporting_fiscal_period=9,
                                 d2_submission=False,
                                 is_quarter_format=False)
    d2_sub = SubmissionFactory(submission_id=4,
                               reporting_fiscal_year=2020,
                               reporting_fiscal_period=6,
                               d2_submission=True,
                               is_quarter_format=False)
    q2 = QuarterlyRevalidationThresholdFactory(quarter=2, year=2020)
    q4 = QuarterlyRevalidationThresholdFactory(quarter=4, year=2020)
    sess.add_all([quart_sub, month_sub, fail_sub, d2_sub, q2, q4])

    # Pass cases
    assert get_window_end(quart_sub) == q2.window_end.date()
    assert get_window_end(month_sub) == q4.window_end.date()
    # Fail cases
    assert get_window_end(fail_sub) is None
    assert get_window_end(d2_sub) is None
def test_certify_dabs_submission_quarterly_revalidation_multiple_thresholds(database):
    """ Tests that a DABS submission is not affected by a different quarterly revalidation threshold than the one that
        matches its reporting_start_date.
    """
    with Flask('test-app').app_context():
        now = datetime.datetime.utcnow()
        earlier = now - datetime.timedelta(days=1)
        sess = database.session

        user = UserFactory()
        cgac = CGACFactory(cgac_code='001', agency_name='CGAC Agency')
        submission = SubmissionFactory(created_at=earlier, updated_at=earlier, cgac_code=cgac.cgac_code,
                                       reporting_fiscal_period=3, reporting_fiscal_year=2017,
                                       reporting_start_date='2016-10-01', is_quarter_format=True, publishable=True,
                                       publish_status_id=PUBLISH_STATUS_DICT['unpublished'], d2_submission=False,
                                       number_of_errors=0, number_of_warnings=200, certifying_user_id=None)
        quarter_reval = QuarterlyRevalidationThresholdFactory(year=2017, quarter=1, window_start=earlier)
        quarter_reval_2 = QuarterlyRevalidationThresholdFactory(year=2017, quarter=2,
                                                                window_start=now + datetime.timedelta(days=10))
        sess.add_all([user, cgac, submission, quarter_reval, quarter_reval_2])
        sess.commit()

        job = JobFactory(submission_id=submission.submission_id, last_validated=now,
                         job_type_id=JOB_TYPE_DICT['csv_record_validation'])
        sess.add(job)
        sess.commit()

        g.user = user
        file_handler = fileHandler.FileHandler({}, is_local=True)
        response = certify_dabs_submission(submission, file_handler)
        assert response.status_code == 200
def test_get_latest_certification_period(database):
    """ Tests the get_latest_certification_period function to make sure it returns the correct quarter and year """
    sess = database.session

    # Revalidation date
    today = datetime.datetime.today()
    reval1 = QuarterlyRevalidationThresholdFactory(quarter=1, year=2016, window_start=today - datetime.timedelta(1))
    reval2 = QuarterlyRevalidationThresholdFactory(quarter=2, year=2016, window_start=today)
    reval3 = QuarterlyRevalidationThresholdFactory(quarter=3, year=2017, window_start=today + datetime.timedelta(1))
    sess.add_all([reval1, reval2, reval3])
    sess.commit()

    results = get_latest_certification_period()
    assert results['quarter'] == 2
    assert results['year'] == 2016
def test_certify_dabs_submission_quarterly_revalidation_too_early(database):
    """ Tests that a DABS submission that was last validated before the window start cannot be certified. """
    with Flask('test-app').app_context():
        now = datetime.datetime.utcnow()
        earlier = now - datetime.timedelta(days=1)
        sess = database.session

        user = UserFactory()
        cgac = CGACFactory(cgac_code='001', agency_name='CGAC Agency')
        submission = SubmissionFactory(created_at=earlier, updated_at=earlier, cgac_code=cgac.cgac_code,
                                       reporting_fiscal_period=3, reporting_fiscal_year=2017, is_quarter_format=True,
                                       publishable=True, publish_status_id=PUBLISH_STATUS_DICT['unpublished'],
                                       d2_submission=False, number_of_errors=0, number_of_warnings=200,
                                       certifying_user_id=None)
        quarter_reval = QuarterlyRevalidationThresholdFactory(year=2017, quarter=1, window_start=now)
        sess.add_all([user, cgac, submission, quarter_reval])
        sess.commit()

        job = JobFactory(submission_id=submission.submission_id, last_validated=earlier,
                         job_type_id=JOB_TYPE_DICT['csv_record_validation'])
        sess.add(job)
        sess.commit()

        g.user = user
        file_handler = fileHandler.FileHandler({}, is_local=True)
        response = certify_dabs_submission(submission, file_handler)
        response_json = json.loads(response.data.decode('UTF-8'))
        assert response.status_code == 400
        assert response_json['message'] == "This submission was last validated or its D files generated before the " \
                                           "start of the submission window ({}). Please revalidate before " \
                                           "certifying.".\
            format(quarter_reval.window_start.strftime('%m/%d/%Y'))
def test_certify_dabs_submission(database, monkeypatch):
    """ Tests the certify_dabs_submission function """
    with Flask('test-app').app_context():
        now = datetime.datetime.utcnow()
        sess = database.session

        user = UserFactory()
        cgac = CGACFactory(cgac_code='001', agency_name='CGAC Agency')
        submission = SubmissionFactory(created_at=now, updated_at=now, cgac_code=cgac.cgac_code,
                                       reporting_fiscal_period=3, reporting_fiscal_year=2017, is_quarter_format=True,
                                       publishable=True, publish_status_id=PUBLISH_STATUS_DICT['unpublished'],
                                       d2_submission=False, number_of_errors=0, number_of_warnings=200,
                                       certifying_user_id=None)
        quarter_reval = QuarterlyRevalidationThresholdFactory(year=2017, quarter=1,
                                                              window_start=now - datetime.timedelta(days=1))
        sess.add_all([user, cgac, submission, quarter_reval])
        sess.commit()

        comment = CommentFactory(file_type_id=FILE_TYPE_DICT['appropriations'], comment='Test',
                                 submission_id=submission.submission_id)
        job_1 = JobFactory(submission_id=submission.submission_id, last_validated=now,
                           job_type_id=JOB_TYPE_DICT['csv_record_validation'])
        job_2 = JobFactory(submission_id=submission.submission_id, last_validated=now + datetime.timedelta(days=1),
                           job_type_id=JOB_TYPE_DICT['csv_record_validation'])
        sess.add_all([job_1, job_2, comment])
        sess.commit()

        flex_field = FlexField(file_type_id=FILE_TYPE_DICT['appropriations'], header='flex_test', job_id=job_1.job_id,
                               submission_id=submission.submission_id, row_number=2, cell=None)
        sess.add(flex_field)
        sess.commit()

        g.user = user
        file_handler = fileHandler.FileHandler({}, is_local=True)
        monkeypatch.setattr(file_handler, 'move_certified_files', Mock(return_value=True))
        monkeypatch.setattr(fileHandler.GlobalDB, 'db', Mock(return_value=database))

        certify_dabs_submission(submission, file_handler)

        sess.refresh(submission)
        certify_history = sess.query(CertifyHistory).filter_by(submission_id=submission.submission_id).one_or_none()
        assert certify_history is not None
        assert submission.certifying_user_id == user.user_id
        assert submission.publish_status_id == PUBLISH_STATUS_DICT['published']

        # Make sure certified comments are created
        certified_comment = sess.query(CertifiedComment).filter_by(submission_id=submission.submission_id).one_or_none()
        assert certified_comment is not None

        # Make sure certified flex fields are created
        certified_flex = sess.query(CertifiedFlexField).filter_by(submission_id=submission.submission_id).one_or_none()
        assert certified_flex is not None