package org.commcare.fixtures.test;

import org.commcare.core.parse.ParseUtils;
import org.commcare.test.utilities.CaseTestUtils;
import org.commcare.util.mocks.MockDataUtils;
import org.commcare.util.mocks.MockUserDataSandbox;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.javarosa.xpath.parser.XPathSyntaxException;
import org.junit.Before;
import org.junit.Test;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;

/**
 * @author Phillip Mates (pmates@dimagi.com)
 */
public class StorageBackedFixtureTest {
    private MockUserDataSandbox sandbox;

    @Before
    public void setUp() {
        sandbox = MockDataUtils.getStaticStorage();
    }

    @Test
    public void queryIndexedLookup() throws XPathSyntaxException, UnfullfilledRequirementsException,
            XmlPullParserException, IOException, InvalidStructureException {
        ParseUtils.parseIntoSandbox(getClass().getResourceAsStream("/indexed-fixture.xml"), sandbox);

        EvaluationContext ec =
                MockDataUtils.buildContextWithInstance(sandbox, "products", CaseTestUtils.FIXTURE_INSTANCE_PRODUCT);
        CaseTestUtils.xpathEvalAndAssert(ec, "instance('products')/products/product[@id = 'a6d16035b98f6f962a6538bd927cefb3']/name", "CU");
    }

    @Test(expected = InvalidStructureException.class)
    public void errorOnSchemaAfterFixtureTest() throws XPathSyntaxException, UnfullfilledRequirementsException,
            XmlPullParserException, IOException, InvalidStructureException {
        ParseUtils.parseIntoSandbox(getClass().getResourceAsStream("/schema-after-indexed-fixture.xml"), sandbox, true);
    }
}

@@ -580,16 +580,62 @@
 ption;%0A%0A
+import static org.junit.Assert.assertEquals;%0A%0A
 /**%0A * @
@@ -1436,16 +1436,459 @@
 , %22CU%22);
+%0A%0A        // ensure that the entire fixture is stored in the normal storage.%0A        // This is to ensure if we ever change the indexed data model, we can%0A        // perform offline data migrations%0A        assertEquals(1, sandbox.getUserFixtureStorage().getNumRecords());%0A%0A        // make sure the fixture is stored in the indexed fixture storage%0A        assertEquals(4, sandbox.getIndexedFixtureStorage(%22commtrack:products%22).getNumRecords());
 %0A    %7D%0A%0A

check storage for fixture commits