import pytest, netCDF4, os
from dqc_wrapper.test02_spatial_completeness import SpatialCompletenessTest
from dqc_wrapper.checker import create_parser
import dqc_wrapper.utils.grib_content as gcont
import gc

@pytest.fixture()
def ncfile(pytestconfig):
    return pytestconfig.getoption("ncfile")

@pytest.fixture()
def gribfile(pytestconfig):
    return pytestconfig.getoption("gribfile")


def initialize(file_path, type_format='netcdf'):
    args = create_parser(['--test', 'spatial_completeness', '--input',
                          file_path, '--type', type_format])
    return SpatialCompletenessTest(args)

""" UNIT TESTS """
def test_missing_values_netcdf(ncfile):
    gc.collect()
    ncitem = netCDF4.Dataset(ncfile)
    test = initialize(ncfile)
    datamiss, mk = test.missing_values_netcdf(ncitem, 'tas')
    assert (not datamiss and not mk)


def test_missing_values_grib(gribfile):
    gfile = gcont.grib_content(gribfile)
    msgs = gfile.return_all_msg()
    test = initialize(gribfile, type_format='grib')
    datamiss, mk = test.missing_values_grib(msgs)
    assert mk == 'OK'


""" INTEGRATION TESTS """
def test_main_nc(ncfile):
    test = initialize(ncfile)
    test.main()


def test_main_grib(gribfile):
    test = initialize(gribfile, type_format='grib')
    test.main()


def test_main_error():
    with pytest.raises(Exception):
        test = initialize(type_format=None)
        test.main()
