<commit_before># Copyright 2020 Google LLC
#
# 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.

"""Test suite for all auxiliary devices, covers basic functionality."""
import os
import json
import shutil
import time
import traceback
import sys
import subprocess

from mobly import asserts

import gazoo_device
from gazoo_device.base_classes import auxiliary_device
from functional_tests import gdm_test_base

# nlmodel does exist but nl_model is a typo, control_port_name never used
# qr_code has been deprecated for some devices.
DEPRECATED_PROPERTIES = ["nl_model", "mac_address", "control_port_name", "wireless_reg_dom",
                         "adb_serial", "qr_code", "default_device_name"]

# Allows the log process to catch up after device creation by using a time.sleep().
# Prevents having old device bootup events in the logs checked by _verify_no_unexpected_bootups().
LOG_CATCH_UP_DELAY = 3


class PowerSwitch:

    def __init__(self):
        self._is_on = False

    def turn_on_power(self):
        self._is_on = True

    def power_is_on(self):
        return self._is_on


def turn_everything_on(switch_list):
    for sw in switch_list:
        sw.turn_on_power()


class AuxiliaryDeviceCommonTestSuite(gdm_test_base.GDMTestBase):
    """Common test suite for all auxiliary devices."""

    @classmethod
    def is_applicable_to(cls, device_type, device_class, device_name):
        """Determine if this test suite can run on the given device."""
        return issubclass(device_class, auxiliary_device.AuxiliaryDevice)

    @classmethod
    def requires_pairing(cls):
        """Returns True if the device in the testbed must be paired to run this test suite."""
        return False

    @classmethod
    def required_test_config_variables(cls):
        """Returns a list of keys required to be present in the functional test config.

        Returns:
            list[str]: functional test config keys which are used by the test suite.
        """
        return ["shell_cmd", "expect", "known_logline", "custom_filters"]

    def test_1000_close_device(self):
        self.logger.info("Testing close device stops logging")
        log_file = self.device.log_file_name
        asserts.assert_true(os.path.exists(log_file),
                            "Cannot test close as device is not logging")
        self.device.close()
        time.sleep(1)
        size = os.stat(log_file).st_size
        time.sleep(.1)
        asserts.assert_true(size == os.stat(log_file).st_size,
                            "Log has updated after device is closed")

    def test_1001_logging(self):
        self._verify_logging()

    def test_1002_get_serial_number(self):
        try:
            asserts.assert_true(self.device.serial_number is not None,
                                "serial number should not be None")
        except Exception:
            traceback_message = traceback.format_exc()
            asserts.fail("Error happened during get serial number: " +
                         traceback_message)

    def test_1004_get_firmware_version(self):
        self._verify_firmware_version()

    def test_1008_reboot(self):
        """Reboot automatically verifies the reboot happens correctly.

        Note:
         Verifies device is_connected afer reboot.
        """
        time.sleep(LOG_CATCH_UP_DELAY)

        try:
            self.device.reboot()
        except Exception:
            traceback_message = traceback.format_exc()
            asserts.fail("Error happened during reboot: " + traceback_message)
        self.device.device_is_connected()

    def test_1011_send_and_expect(self):
        try:
            self.device.switchboard.send_and_expect(self.test_config["shell_cmd"],
                                                    self.test_config["expect"],
                                                    timeout=10)
        except Exception:
            traceback_message = traceback.format_exc()
            asserts.fail("Error happened during send and expect: " + traceback_message)

    def test_1012_shell(self):
        try:
            self.device.shell(self.test_config["shell_cmd"])
        except Exception:
            traceback_message = traceback.format_exc()
            asserts.fail("Error happened during shell command: " + traceback_message)

    def test_1016_do_and_expect_some_func_is_called(self):
        switch = PowerSwitch()<commit_msg>Make auxiliary_device_common_test_suite.py backwards-compatible (part 2)<commit_after># Copyright 2020 Google LLC
#
# 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.

"""Test suite for all auxiliary devices, covers basic functionality."""
import os
import json
import shutil
import time
import traceback
import sys
import subprocess

from mobly import asserts

import gazoo_device
from gazoo_device.base_classes import auxiliary_device
from functional_tests import gdm_test_base

# nlmodel does exist but nl_model is a typo, control_port_name never used
# qr_code has been deprecated for some devices.
DEPRECATED_PROPERTIES = ["nl_model", "mac_address", "control_port_name", "wireless_reg_dom",
                         "adb_serial", "qr_code", "default_device_name"]

# Allows the log process to catch up after device creation by using a time.sleep().
# Prevents having old device bootup events in the logs checked by _verify_no_unexpected_bootups().
LOG_CATCH_UP_DELAY = 3


class PowerSwitch:

    def __init__(self):
        self._is_on = False

    def turn_on_power(self):
        self._is_on = True

    def power_is_on(self):
        return self._is_on


def turn_everything_on(switch_list):
    for sw in switch_list:
        sw.turn_on_power()


class AuxiliaryDeviceCommonTestSuite(gdm_test_base.GDMTestBase):
    """Common test suite for all auxiliary devices."""

    @classmethod
    def is_applicable_to(cls, device_type, device_class, device_name):
        """Determine if this test suite can run on the given device."""
        return issubclass(device_class, auxiliary_device.AuxiliaryDevice)

    @classmethod
    def requires_pairing(cls):
        """Returns True if the device in the testbed must be paired to run this test suite."""
        return False

    @classmethod
    def required_test_config_variables(cls):
        """Returns a list of keys required to be present in the functional test config.

        Returns:
            list[str]: functional test config keys which are used by the test suite.
        """
        return ["shell_cmd", "expect", "known_logline", "custom_filters"]

    def test_1000_close_device(self):
        self.logger.info("Testing close device stops logging")
        log_file = self.device.log_file_name
        asserts.assert_true(os.path.exists(log_file),
                            "Cannot test close as device is not logging")
        self.device.close()
        time.sleep(1)
        size = os.stat(log_file).st_size
        time.sleep(.1)
        asserts.assert_true(size == os.stat(log_file).st_size,
                            "Log has updated after device is closed")

    def test_1001_logging(self):
        self._verify_logging()

    def test_1002_get_serial_number(self):
        try:
            asserts.assert_true(self.device.serial_number is not None,
                                "serial number should not be None")
        except Exception:
            traceback_message = traceback.format_exc()
            asserts.fail("Error happened during get serial number: " +
                         traceback_message)

    def test_1004_get_firmware_version(self):
        self._verify_firmware_version()

    def test_1008_reboot(self):
        """Reboot automatically verifies the reboot happens correctly.

        Note:
         Verifies device is_connected afer reboot.
        """
        time.sleep(LOG_CATCH_UP_DELAY)

        try:
            self.device.reboot()
        except Exception:
            traceback_message = traceback.format_exc()
            asserts.fail("Error happened during reboot: " + traceback_message)
        if hasattr(self.device, "device_is_connected"):
            self.device.device_is_connected()
        else:
            self.device.check_device_connected()

    def test_1011_send_and_expect(self):
        try:
            self.device.switchboard.send_and_expect(self.test_config["shell_cmd"],
                                                    self.test_config["expect"],
                                                    timeout=10)
        except Exception:
            traceback_message = traceback.format_exc()
            asserts.fail("Error happened during send and expect: " + traceback_message)

    def test_1012_shell(self):
        try:
            self.device.shell(self.test_config["shell_cmd"])
        except Exception:
            traceback_message = traceback.format_exc()
            asserts.fail("Error happened during shell command: " + traceback_message)

    def test_1016_do_and_expect_some_func_is_called(self):
        switch = PowerSwitch()
{'fraction_non_alphanumeric': 0.07450430602843981, 'fraction_numerical': 0.009112757861005407, 'mean_word_length': 2.7167845180498698, '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': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1569574', 'n_tokens_mistral': 2790, 'n_tokens_neox': 2649, 'n_words': 820}