<commit_before>import json
import os
import sys

from ..taxbrain.compute import MockCompute
from django.core.files.uploadedfile import SimpleUploadedFile

NUM_BUDGET_YEARS = int(os.environ.get("NUM_BUDGET_YEARS", "10"))

def get_dropq_compute_from_module(module_import_path, num_times_to_wait=None):
    module_views = sys.modules[module_import_path]
    module_views.dropq_compute = MockCompute(
        num_times_to_wait=num_times_to_wait
    )
    return module_views.dropq_compute

def do_micro_sim(client, data, tb_dropq_compute=None, dyn_dropq_compute=None,
                 compute_count=None):
    '''do the proper sequence of HTTP calls to run a microsim'''
    #Monkey patch to mock out running of compute jobs
    if tb_dropq_compute is None:
        tb_dropq_compute = get_dropq_compute_from_module(
            'webapp.apps.taxbrain.views',
            num_times_to_wait=0
        )
    if dyn_dropq_compute is None:
        dyn_dropq_compute = get_dropq_compute_from_module(
            'webapp.apps.dynamic.views',
            num_times_to_wait=1
        )

    response = client.post('/taxbrain/', data)
    # Check that redirect happens
    assert response.status_code == 302
    idx = response.url[:-1].rfind('/')
    assert response.url[:idx].endswith("taxbrain")
    print('compute_count', tb_dropq_compute.count, compute_count)
    if compute_count is not None:
        assert tb_dropq_compute.count == compute_count
    # return response
    return {"response": response,
            "tb_dropq_compute": tb_dropq_compute,
            "dyn_dropq_compute": dyn_dropq_compute,
            "pk": response.url[idx+1:-1]}

def do_micro_sim_from_file(client, start_year, reform_text, assumptions_text=None):
    # Monkey patch to mock out running of compute jobs
    import sys
    from webapp.apps.taxbrain import views
    webapp_views = sys.modules['webapp.apps.taxbrain.views']
    webapp_views.dropq_compute = MockCompute()

    tc_file = SimpleUploadedFile("test_reform.json", reform_text)
    data = {u'docfile': tc_file,
            u'has_errors': [u'False'],
            u'start_year': start_year, 'csrfmiddlewaretoken':'abc123'}

    if assumptions_text:
        tc_file2 = SimpleUploadedFile("test_assumptions.json",
                                      assumptions_text)
        data['assumpfile'] = tc_file2

    response = client.post('/taxbrain/file/', data)
    # Check that redirect happens
    assert response.status_code == 302
    return response


def check_posted_params(mock_compute, params_to_check, start_year):
    """
    Make sure posted params match expected results
    user_mods: parameters that are actually passed to taxcalc
    params_to_check: gives truth value for parameters that we want to check
                     (formatted as taxcalc dict style reform)
    """
    last_posted = mock_compute.last_posted
    user_mods = json.loads(last_posted["user_mods"])
    assert last_posted["first_budget_year"] == start_year
    for year in params_to_check:
        for param in params_to_check[year]:
            assert user_mods[str(year)][param] == params_to_check[year][param]


def get_post_data(start_year, _ID_BenefitSurtax_Switches=True, quick_calc=False):
    data = {u'has_errors': [u'False'],
            u'start_year': unicode(start_year),
            'csrfmiddlewaretoken':'abc123'}
    if _ID_BenefitSurtax_Switches:
        switches = {u'ID_BenefitSurtax_Switch_0': [u'True'],
                    u'ID_BenefitSurtax_Switch_1': [u'True'],<commit_msg>Refactor do_micro_sim_from_file<commit_after>import json
import os
import sys

from ..taxbrain.compute import MockCompute
from django.core.files.uploadedfile import SimpleUploadedFile

NUM_BUDGET_YEARS = int(os.environ.get("NUM_BUDGET_YEARS", "10"))

def get_dropq_compute_from_module(module_import_path, num_times_to_wait=None):
    module_views = sys.modules[module_import_path]
    module_views.dropq_compute = MockCompute(
        num_times_to_wait=num_times_to_wait
    )
    return module_views.dropq_compute

def do_micro_sim(client, data, tb_dropq_compute=None, dyn_dropq_compute=None,
                 compute_count=None, post_url='/taxbrain/'):
    '''do the proper sequence of HTTP calls to run a microsim'''
    #Monkey patch to mock out running of compute jobs
    if tb_dropq_compute is None:
        tb_dropq_compute = get_dropq_compute_from_module(
            'webapp.apps.taxbrain.views',
            num_times_to_wait=0
        )
    if dyn_dropq_compute is None:
        dyn_dropq_compute = get_dropq_compute_from_module(
            'webapp.apps.dynamic.views',
            num_times_to_wait=1
        )

    response = client.post(post_url, data)
    # Check that redirect happens
    assert response.status_code == 302
    idx = response.url[:-1].rfind('/')
    assert response.url[:idx].endswith("taxbrain")

    # Check for good response
    response2 = client.get(response.url)
    # TODO: check compute count once NUM_BUDGET_YEARS env variable issue is
    # resolved
    assert response2.status_code == 200
    if compute_count is not None:
        assert tb_dropq_compute.count == compute_count
    # return response
    return {"response": response,
            "tb_dropq_compute": tb_dropq_compute,
            "dyn_dropq_compute": dyn_dropq_compute,
            "pk": response.url[idx+1:-1]}

def do_micro_sim_from_file(client, start_year, reform_text, assumptions_text=None, **kwargs):
    tc_file = SimpleUploadedFile("test_reform.json", reform_text)
    data = {u'docfile': tc_file,
            u'has_errors': [u'False'],
            u'start_year': start_year, 'csrfmiddlewaretoken':'abc123'}

    if assumptions_text:
        tc_file2 = SimpleUploadedFile("test_assumptions.json",
                                      assumptions_text)
        data['assumpfile'] = tc_file2

    post_url = '/taxbrain/file/'

    return do_micro_sim(client, data, post_url=post_url, **kwargs)

def check_posted_params(mock_compute, params_to_check, start_year):
    """
    Make sure posted params match expected results
    user_mods: parameters that are actually passed to taxcalc
    params_to_check: gives truth value for parameters that we want to check
                     (formatted as taxcalc dict style reform)
    """
    last_posted = mock_compute.last_posted
    user_mods = json.loads(last_posted["user_mods"])
    assert last_posted["first_budget_year"] == start_year
    for year in params_to_check:
        for param in params_to_check[year]:
            assert user_mods[str(year)][param] == params_to_check[year][param]


def get_post_data(start_year, _ID_BenefitSurtax_Switches=True, quick_calc=False):
    data = {u'has_errors': [u'False'],
            u'start_year': unicode(start_year),
            'csrfmiddlewaretoken':'abc123'}
    if _ID_BenefitSurtax_Switches:
        switches = {u'ID_BenefitSurtax_Switch_0': [u'True'],
                    u'ID_BenefitSurtax_Switch_1': [u'True'],
{'fraction_non_alphanumeric': 0.09131499351865188, 'fraction_numerical': 0.0069134379951029815, 'mean_word_length': 3.3949367088607594, 'pattern_counts': {'":': 8, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4311285', 'n_tokens_mistral': 2260, 'n_tokens_neox': 2188, 'n_words': 455}