<commit_before>/*
 * Copyright 2014-present Facebook, 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 com.facebook.testing.screenshot.internal;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import android.app.Instrumentation;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SdkSuppress;
import android.support.test.runner.AndroidJUnit4;
import android.test.MoreAsserts;
import android.util.JsonReader;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Locale;

import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;

/** Tests for {@link ScreenshotImpl} */
@RunWith(AndroidJUnit4.class)
public class ScreenshotImplTest {
  private AlbumImpl mAlbumImpl;
  private AlbumImpl mSecondAlbumImpl;
  private TextView mTextView;
  private ScreenshotImpl mScreenshot;
  private ScreenshotDirectories mScreenshotDirectories;

  @Rule public Timeout mTimeout = new Timeout(60000);

  @Before
  public void setUp() throws Exception {
    mScreenshotDirectories = new ScreenshotDirectories(getInstrumentation().getTargetContext());
    mAlbumImpl = AlbumImpl.create(getInstrumentation().getTargetContext(), "verify-in-test");
    mSecondAlbumImpl =
        AlbumImpl.create(getInstrumentation().getTargetContext(), "recorded-in-test");
    mTextView = new TextView(getInstrumentation().getTargetContext());
    mTextView.setText("foobar");

    // Unfortunately TextView needs a LayoutParams for onDraw
    mTextView.setLayoutParams(
        new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

    measureAndLayout();
    // For most of the tests, we send a null album to verify against
    mScreenshot = new ScreenshotImpl(mAlbumImpl);
  }

  @After
  public void tearDown() throws Exception {
    mAlbumImpl.cleanup();
    mSecondAlbumImpl.cleanup();
  }

  @Test
  public void testBasicFunctionalityHappyPath() throws Throwable {
    mScreenshot.snap(mTextView).setName("fooBar").record();
  }

  @Test
  public void testClassNameIsDetectedOnNonUiThread() throws Throwable {
    assertEquals(getClass().getName(), mScreenshot.snap(mTextView).getTestClass());
  }

  @Test
  public void testTestNameIsDetected() throws Throwable {
    assertEquals("testTestNameIsDetected", mScreenshot.snap(mTextView).getTestName());
  }

  @Test
  public void testRecordBuilderImplHasAHierarchyDumpFile() throws Throwable {
    RecordBuilderImpl rb = mScreenshot.snap(mTextView).setName("blahblah");
    rb.record();
    mScreenshot.flush();

    String fileName =
        new File(mScreenshotDirectories.get("verify-in-test"), "blahblah_dump.json")
            .getAbsolutePath();
    InputStream is = new FileInputStream(fileName);

    StringBuilder builder = new StringBuilder();
    byte[] buffer = new byte[8 * 1024];
    int read;
    while ((read = is.read(buffer)) != -1) {
      builder.append(new String(buffer, 0, read));
    }
    JSONObject result = new JSONObject(builder.toString());

    assertEquals(5, result.length());
    assertEquals("android.widget.TextView", result.getString("class"));
    assertEquals(0, result.getInt("left"));
    assertEquals(0, result.getInt("top"));
    assertEquals(200, result.getInt("width"));
    assertEquals(100, result.getInt("height"));

    File metadata = mAlbumImpl.getMetadataFile();
    String metadataContents = fileToString(metadata);

    MoreAsserts.assertContainsRegex("blahblah.*.json", metadataContents);
  }

  @Test
  public void testLargeViewThrowsWithDefaultMax() throws Throwable {
    measureAndLayout(200, 0xffff00);

    assertEquals(200, mTextView.getMeasuredWidth());
    assertEquals(0xffff00, mTextView.getMeasuredHeight());
    try {
      mScreenshot.snap(mTextView).setName("largeView").record();
      fail("expected exception");
    } catch (RuntimeException e) {
      MoreAsserts.assertContainsRegex(".*View too large.*", e.getMessage());
    }
  }

  @Test
  public void testLargeViewDoesntThrowWithCustomMax() throws Throwable {
    measureAndLayout(1440, 1000);

    assertEquals(1440, mTextView.getMeasuredWidth());
    assertEquals(1000, mTextView.getMeasuredHeight());
    mScreenshot.snap(mTextView).setMaxPixels(10733760L).setName("largeView").record();
  }<commit_msg>Fix tests<commit_after>/*
 * Copyright 2014-present Facebook, 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 com.facebook.testing.screenshot.internal;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import android.app.Instrumentation;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.SdkSuppress;
import android.support.test.runner.AndroidJUnit4;
import android.test.MoreAsserts;
import android.util.JsonReader;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Locale;

import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;

/** Tests for {@link ScreenshotImpl} */
@RunWith(AndroidJUnit4.class)
public class ScreenshotImplTest {
  private AlbumImpl mAlbumImpl;
  private AlbumImpl mSecondAlbumImpl;
  private TextView mTextView;
  private ScreenshotImpl mScreenshot;
  private ScreenshotDirectories mScreenshotDirectories;

  @Rule public Timeout mTimeout = new Timeout(60000);

  @Before
  public void setUp() throws Exception {
    mScreenshotDirectories = new ScreenshotDirectories(getInstrumentation().getTargetContext());
    mAlbumImpl = AlbumImpl.create(getInstrumentation().getTargetContext(), "verify-in-test");
    mSecondAlbumImpl =
        AlbumImpl.create(getInstrumentation().getTargetContext(), "recorded-in-test");
    mTextView = new TextView(getInstrumentation().getTargetContext());
    mTextView.setText("foobar");

    // Unfortunately TextView needs a LayoutParams for onDraw
    mTextView.setLayoutParams(
        new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

    measureAndLayout();
    // For most of the tests, we send a null album to verify against
    mScreenshot = new ScreenshotImpl(mAlbumImpl);
  }

  @After
  public void tearDown() throws Exception {
    mAlbumImpl.cleanup();
    mSecondAlbumImpl.cleanup();
  }

  @Test
  public void testBasicFunctionalityHappyPath() throws Throwable {
    mScreenshot.snap(mTextView).setName("fooBar").record();
  }

  @Test
  public void testClassNameIsDetectedOnNonUiThread() throws Throwable {
    assertEquals(getClass().getName(), mScreenshot.snap(mTextView).getTestClass());
  }

  @Test
  public void testTestNameIsDetected() throws Throwable {
    assertEquals("testTestNameIsDetected", mScreenshot.snap(mTextView).getTestName());
  }

  @Test
  public void testRecordBuilderImplHasAHierarchyDumpFile() throws Throwable {
    RecordBuilderImpl rb = mScreenshot.snap(mTextView).setName("blahblah");
    rb.record();
    mScreenshot.flush();

    String fileName =
        new File(mScreenshotDirectories.get("verify-in-test"), "blahblah_dump.json")
            .getAbsolutePath();
    InputStream is = new FileInputStream(fileName);

    StringBuilder builder = new StringBuilder();
    byte[] buffer = new byte[8 * 1024];
    int read;
    while ((read = is.read(buffer)) != -1) {
      builder.append(new String(buffer, 0, read));
    }
    JSONObject result = new JSONObject(builder.toString());

    assertEquals(2, result.length());
    JSONObject viewHierarchy = result.getJSONObject("viewHierarchy");
    assertEquals(5, viewHierarchy.length());
    assertEquals("android.widget.TextView", viewHierarchy.getString("class"));
    assertEquals(0, viewHierarchy.getInt("left"));
    assertEquals(0, viewHierarchy.getInt("top"));
    assertEquals(200, viewHierarchy.getInt("width"));
    assertEquals(100, viewHierarchy.getInt("height"));

    File metadata = mAlbumImpl.getMetadataFile();
    String metadataContents = fileToString(metadata);

    MoreAsserts.assertContainsRegex("blahblah.*.json", metadataContents);
  }

  @Test
  public void testLargeViewThrowsWithDefaultMax() throws Throwable {
    measureAndLayout(200, 0xffff00);

    assertEquals(200, mTextView.getMeasuredWidth());
    assertEquals(0xffff00, mTextView.getMeasuredHeight());
    try {
      mScreenshot.snap(mTextView).setName("largeView").record();
      fail("expected exception");
    } catch (RuntimeException e) {
      MoreAsserts.assertContainsRegex(".*View too large.*", e.getMessage());
    }
  }

  @Test
  public void testLargeViewDoesntThrowWithCustomMax() throws Throwable {
    measureAndLayout(1440, 1000);

    assertEquals(1440, mTextView.getMeasuredWidth());
    assertEquals(1000, mTextView.getMeasuredHeight());
    mScreenshot.snap(mTextView).setMaxPixels(10733760L).setName("largeView").record();
  }
{'fraction_non_alphanumeric': 0.10865628395508874, 'fraction_numerical': 0.012223831944947482, 'mean_word_length': 4.813157894736842, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '7155236', 'n_tokens_mistral': 3268, 'n_tokens_neox': 3102, 'n_words': 732}