<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.auraframework.http;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.auraframework.Aura;
import org.auraframework.def.ApplicationDef;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.ControllerDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.Definition;
import org.auraframework.def.NamespaceDef;
import org.auraframework.def.StyleDef;
import org.auraframework.service.ContextService;
import org.auraframework.system.AuraContext;
import org.auraframework.system.AuraContext.Access;
import org.auraframework.system.AuraContext.Format;
import org.auraframework.system.AuraContext.Mode;
import org.auraframework.system.Source;
import org.auraframework.test.WebDriverTestCase;
import org.auraframework.test.WebDriverUtil.BrowserType;
import org.auraframework.test.annotation.FreshBrowserInstance;
import org.auraframework.test.annotation.TestLabels;
import org.auraframework.test.annotation.ThreadHostileTest;
import org.auraframework.test.controller.TestLoggingAdapterController;
import org.auraframework.util.AuraTextUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;

/**
 * Tests for AppCache functionality by watching the requests received at the server and verifying that the updated
 * content is being used by the browser. AppCache only works for WebKit browsers.
 * 
 * @since 0.0.224
 */
@FreshBrowserInstance
@ThreadHostileTest("TestLoggingAdapter not thread-safe")
public class AppCacheResourcesUITest extends WebDriverTestCase {

    private final static String COOKIE_NAME = "%s_%s_%s_lm";
    private final static String TOKEN = "@@@TOKEN@@@";

    private static final String AURA = "aura";

    private enum Status {
        UNCACHED, IDLE, CHECKING, DOWNLOADING, UPDATEREADY, OBSOLETE;
    }

    private String appName;
    private String namespace;
    private String cmpName;

    public AppCacheResourcesUITest(String name) {
        super(name);
        timeoutInSecs = 60;
    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
        namespace = "appCacheResourcesUITest" + getAuraTestingUtil().getNonce();
        appName = "cacheapplication";
        cmpName = "cachecomponent";

        DefDescriptor<ComponentDef> cmpDesc = createDef(ComponentDef.class, String.format("%s:%s", namespace, cmpName),
                "<aura:component>" 
                		+ "<aura:attribute name='output' type='String'/>"
                        + "<div class='clickableme' onclick='{!c.cssalert}'>@@@TOKEN@@@</div>"
                        + "<div class='attroutput'>{!v.output}</div>" 
        		+"</aura:component>");

        createDef(
                ControllerDef.class, String.format("%s://%s.%s", DefDescriptor.JAVASCRIPT_PREFIX, namespace, cmpName),
                "{ cssalert:function(c){"
                        + "function getStyle(elem, style){"
                        + "var val = '';"
                        + "if(document.defaultView && document.defaultView.getComputedStyle){"
                        + "val = document.defaultView.getComputedStyle(elem, '').getPropertyValue(style);"
                        + "} else if(elem.currentStyle){"
                        + "style = style.replace(/\\-(\\w)/g, function (s, ch){"
                        + "return ch.toUpperCase();"
                        + "});"
                        + "val = elem.currentStyle[style];"
                        + "}"
                        + "return val;"
                        + "};"
                        + "var style = getStyle(c.getElement(),'background-image');"
                        + "c.getValue('v.output').setValue('@@@TOKEN@@@'"
                        + "+ style.substring(style.lastIndexOf('?')+1,style.lastIndexOf(')'))"
                        + "+ ($A.test ? $A.test.dummyFunction() : '@@@TOKEN@@@'));"
                        + "}}");

        createDef(
                ApplicationDef.class,
                String.format("%s:%s", namespace, appName),
                String.format("<aura:application useAppcache='true' render='client' preload='%s'"
                        + " securityProvider='java://org.auraframework.java.securityProvider.LaxSecurityProvider'>"
                        + "<%s:%s/>" + "</aura:application>", namespace, namespace, cmpDesc.getName()));
    }

    /**
     * Opening cached app will only query server for the manifest and the component load.
     */
    @TargetBrowsers({  BrowserType.GOOGLECHROME,  BrowserType.SAFARI,   BrowserType.IPAD, BrowserType.IPHONE })
    @TestLabels("auraSanity")
    public void testNoChanges() throws Exception {
        List<Request> logs = loadMonitorAndValidateApp(TOKEN, TOKEN, "", TOKEN);
        assertRequests(getExpectedInitialRequests(), logs);
        assertAppCacheStatus(Status.IDLE);

        // only expect a fetch for the manifest and the initAsync component load
        logs = loadMonitorAndValidateApp(TOKEN, TOKEN, "", TOKEN);
        List<Request> expected = Lists.newArrayList(new Request(
                "/auraResource", null, null, "manifest", 200));
        assertRequests(expected, logs);
        assertAppCacheStatus(Status.IDLE);
    }

    /**
     * Opening cached app that had a prior cache error will reload the app.
     */
    @TargetBrowsers({ BrowserType.GOOGLECHROME, BrowserType.SAFARI,  BrowserType.IPAD, BrowserType.IPHONE })
    @TestLabels("auraSanity")
    public void testCacheError() throws Exception {
    	//debug for flapper:
    	System.out.println("testCacheError,loadMonitorAndValidateApp, TS:"+System.currentTimeMillis());
        List<Request> logs = loadMonitorAndValidateApp(TOKEN, TOKEN, "", TOKEN);
        assertRequests(getExpectedInitialRequests(), logs);
        assertAppCacheStatus(Status.IDLE);
        Date expiry = new Date(System.currentTimeMillis() + 60000);
        String cookieName = getManifestCookieName();
        getDriver().manage().addCookie(
                new Cookie(cookieName, "error", null, "/", expiry));
        //debug for flapper:
        System.out.println("testCacheError,add error cookie, loadMonitorAndValidateApp again, TS:"+System.currentTimeMillis());
        logs = loadMonitorAndValidateApp(TOKEN, TOKEN, "", TOKEN);
        List<Request> expectedChange = Lists.newArrayList();
        expectedChange.add(new Request("/auraResource", null, null, "manifest", 404)); // reset
        expectedChange.add(new Request("/aura", namespace + ":" + appName, null, "HTML", 302)); // hard refresh
        switch (getBrowserType()) {
        case GOOGLECHROME:
            expectedChange.add(new Request(3, "/auraResource", null, null, "manifest", 200));
            expectedChange.add(new Request(2, "/aura", namespace + ":" + appName, null, "HTML", 200));
            break;
        case SAFARI:
        case IPAD:
        case IPHONE:
        default:
            expectedChange.add(new Request("/auraResource", null, null, "manifest", 200));
            expectedChange.add(new Request("/aura", namespace + ":" + appName, null, "HTML", 200));
            expectedChange.add(new Request("/auraResource", null, null, "css", 200));<commit_msg>removing aurasanity label from appcache tests @rev rjayaramappa@ @bug W-1796398@<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.auraframework.http;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.auraframework.Aura;
import org.auraframework.def.ApplicationDef;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.ControllerDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.Definition;
import org.auraframework.def.NamespaceDef;
import org.auraframework.def.StyleDef;
import org.auraframework.service.ContextService;
import org.auraframework.system.AuraContext;
import org.auraframework.system.AuraContext.Access;
import org.auraframework.system.AuraContext.Format;
import org.auraframework.system.AuraContext.Mode;
import org.auraframework.system.Source;
import org.auraframework.test.WebDriverTestCase;
import org.auraframework.test.WebDriverUtil.BrowserType;
import org.auraframework.test.annotation.FreshBrowserInstance;
import org.auraframework.test.annotation.TestLabels;
import org.auraframework.test.annotation.ThreadHostileTest;
import org.auraframework.test.controller.TestLoggingAdapterController;
import org.auraframework.util.AuraTextUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;

/**
 * Tests for AppCache functionality by watching the requests received at the server and verifying that the updated
 * content is being used by the browser. AppCache only works for WebKit browsers.
 * 
 * @since 0.0.224
 */
@FreshBrowserInstance
@ThreadHostileTest("TestLoggingAdapter not thread-safe")
public class AppCacheResourcesUITest extends WebDriverTestCase {

    private final static String COOKIE_NAME = "%s_%s_%s_lm";
    private final static String TOKEN = "@@@<PASSWORD>@@@";

    private static final String AURA = "aura";

    private enum Status {
        UNCACHED, IDLE, CHECKING, DOWNLOADING, UPDATEREADY, OBSOLETE;
    }

    private String appName;
    private String namespace;
    private String cmpName;

    public AppCacheResourcesUITest(String name) {
        super(name);
        timeoutInSecs = 60;
    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
        namespace = "appCacheResourcesUITest" + getAuraTestingUtil().getNonce();
        appName = "cacheapplication";
        cmpName = "cachecomponent";

        DefDescriptor<ComponentDef> cmpDesc = createDef(ComponentDef.class, String.format("%s:%s", namespace, cmpName),
                "<aura:component>" 
                		+ "<aura:attribute name='output' type='String'/>"
                        + "<div class='clickableme' onclick='{!c.cssalert}'>@@@TOKEN@@@</div>"
                        + "<div class='attroutput'>{!v.output}</div>" 
        		+"</aura:component>");

        createDef(
                ControllerDef.class, String.format("%s://%s.%s", DefDescriptor.JAVASCRIPT_PREFIX, namespace, cmpName),
                "{ cssalert:function(c){"
                        + "function getStyle(elem, style){"
                        + "var val = '';"
                        + "if(document.defaultView && document.defaultView.getComputedStyle){"
                        + "val = document.defaultView.getComputedStyle(elem, '').getPropertyValue(style);"
                        + "} else if(elem.currentStyle){"
                        + "style = style.replace(/\\-(\\w)/g, function (s, ch){"
                        + "return ch.toUpperCase();"
                        + "});"
                        + "val = elem.currentStyle[style];"
                        + "}"
                        + "return val;"
                        + "};"
                        + "var style = getStyle(c.getElement(),'background-image');"
                        + "c.getValue('v.output').setValue('@@@TOKEN@@@'"
                        + "+ style.substring(style.lastIndexOf('?')+1,style.lastIndexOf(')'))"
                        + "+ ($A.test ? $A.test.dummyFunction() : '@@@TOKEN@@@'));"
                        + "}}");

        createDef(
                ApplicationDef.class,
                String.format("%s:%s", namespace, appName),
                String.format("<aura:application useAppcache='true' render='client' preload='%s'"
                        + " securityProvider='java://org.auraframework.java.securityProvider.LaxSecurityProvider'>"
                        + "<%s:%s/>" + "</aura:application>", namespace, namespace, cmpDesc.getName()));
    }

    /**
     * Opening cached app will only query server for the manifest and the component load.
     */
    @TargetBrowsers({  BrowserType.GOOGLECHROME,  BrowserType.SAFARI,   BrowserType.IPAD, BrowserType.IPHONE })
    public void testNoChanges() throws Exception {
        List<Request> logs = loadMonitorAndValidateApp(TOKEN, TOKEN, "", TOKEN);
        assertRequests(getExpectedInitialRequests(), logs);
        assertAppCacheStatus(Status.IDLE);

        // only expect a fetch for the manifest and the initAsync component load
        logs = loadMonitorAndValidateApp(TOKEN, TOKEN, "", TOKEN);
        List<Request> expected = Lists.newArrayList(new Request(
                "/auraResource", null, null, "manifest", 200));
        assertRequests(expected, logs);
        assertAppCacheStatus(Status.IDLE);
    }

    /**
     * Opening cached app that had a prior cache error will reload the app.
     */
    @TargetBrowsers({ BrowserType.GOOGLECHROME, BrowserType.SAFARI,  BrowserType.IPAD, BrowserType.IPHONE })
    public void testCacheError() throws Exception {
    	//debug for flapper:
    	System.out.println("testCacheError,loadMonitorAndValidateApp, TS:"+System.currentTimeMillis());
        List<Request> logs = loadMonitorAndValidateApp(TOKEN, TOKEN, "", TOKEN);
        assertRequests(getExpectedInitialRequests(), logs);
        assertAppCacheStatus(Status.IDLE);
        Date expiry = new Date(System.currentTimeMillis() + 60000);
        String cookieName = getManifestCookieName();
        getDriver().manage().addCookie(
                new Cookie(cookieName, "error", null, "/", expiry));
        //debug for flapper:
        System.out.println("testCacheError,add error cookie, loadMonitorAndValidateApp again, TS:"+System.currentTimeMillis());
        logs = loadMonitorAndValidateApp(TOKEN, TOKEN, "", TOKEN);
        List<Request> expectedChange = Lists.newArrayList();
        expectedChange.add(new Request("/auraResource", null, null, "manifest", 404)); // reset
        expectedChange.add(new Request("/aura", namespace + ":" + appName, null, "HTML", 302)); // hard refresh
        switch (getBrowserType()) {
        case GOOGLECHROME:
            expectedChange.add(new Request(3, "/auraResource", null, null, "manifest", 200));
            expectedChange.add(new Request(2, "/aura", namespace + ":" + appName, null, "HTML", 200));
            break;
        case SAFARI:
        case IPAD:
        case IPHONE:
        default:
            expectedChange.add(new Request("/auraResource", null, null, "manifest", 200));
            expectedChange.add(new Request("/aura", namespace + ":" + appName, null, "HTML", 200));
            expectedChange.add(new Request("/auraResource", null, null, "css", 200));
{'fraction_non_alphanumeric': 0.12373237694781103, 'fraction_numerical': 0.006245362354687114, 'mean_word_length': 2.9398294762484776, 'pattern_counts': {'":': 6, '<': 34, '<?xml version=': 0, '>': 34, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6890406', 'n_tokens_mistral': 4662, 'n_tokens_neox': 4370, 'n_words': 1022}