Best Python code snippet using avocado_python
test_readconfig.py
Source:test_readconfig.py  
1#!/usr/bin/env python3 2import unittest3import os4from selfdrive.car.tesla.readconfig import read_config_file, CarSettings5class CarSettingsTestClass():6  forcePedalOverCC = None7  fix1916 = None8  def __init__(self):9    pass10class ReadConfigTests(unittest.TestCase):11  test_config_file = "./test_config_file.cfg"12  def setUp(self):13    self.delete_test_config_file()14  def tearDown(self):15    self.delete_test_config_file()16  # Tests to make sure defaults are set when the config file is missing17  def test_defaults_missing_file(self):18    # First time proves that data is set locally19    cs = CarSettings(20        optional_config_file_path=self.test_config_file)21    self.check_defaults(cs)22    self.assertEqual(cs.did_write_file, True)23    # Run a second time to make sure it was saved and read correctly24    cs = CarSettings(25        optional_config_file_path=self.test_config_file)26    self.check_defaults(cs)27    self.assertEqual(cs.did_write_file, False)28  # Tests to make sure defaults are set when the config file is not missing29  def test_defaults_empty_file(self):30    config_file_path = "./test_config_file2.cfg"31    self.create_empty_config_file(config_file_path)32    cs = CarSettings(optional_config_file_path=config_file_path)33    self.check_defaults(cs)34    os.remove(config_file_path)35  # Tests to make sure existing parameters in config file are not overriden when loading defaults36  def test_defaults_non_overriding(self):37    config_file_path = "./test_config_file2.cfg"38    self.create_empty_config_file(39        config_file_path, test_parameter_string="force_pedal_over_cc = True")40    cs = CarSettings(optional_config_file_path=config_file_path)41    # Should still be true, even though the defaut is False42    self.assertEqual(cs.forcePedalOverCC, True)43    os.remove(config_file_path)44  # Tests to make sure empty (default) radar vin is correctly stored and read back45  def test_empty_radar_vin(self):46    self.delete_test_config_file()47    # first pass creates config file48    cs = CarSettings(49        optional_config_file_path=self.test_config_file)50    self.assertEqual(cs.radarVIN, "                 ")51    # second pass actually reads the file52    cs = CarSettings(53        optional_config_file_path=self.test_config_file)54    self.assertEqual(cs.radarVIN, "                 ")55  # Test to make sure old radarVIN entries are converted to the new format (with double quotes for empty string)56  def test_update_empty_radar_vin(self):57    config_file_path = "./test_config_file2.cfg"58    self.create_empty_config_file(59        config_file_path, test_parameter_string="radar_vin =                 ")60    cs = CarSettings(optional_config_file_path=config_file_path)61    # Should be the correct all spaces VIN62    self.assertEqual(cs.radarVIN, "                 ")63    os.remove(config_file_path)64  # Test to make sure radarVIN is read correctly65  def test_radar_vin_with_data(self):66    config_file_path = "./test_config_file2.cfg"67    self.create_empty_config_file(68        config_file_path,69        test_parameter_string="radar_vin = 12345678901234567")70    cs = CarSettings(optional_config_file_path=config_file_path)71    self.assertEqual(cs.radarVIN, "12345678901234567")72    os.remove(config_file_path)73  def test_comments(self):74    expected_comment = "set this setting to false if you do not want op to autoupdate every time you reboot and there is a change on the repo"75    config_file_path = "./test_config_file2.cfg"76    self.create_empty_config_file(77        config_file_path, test_parameter_string="force_pedal_over_cc = True")78    cs = CarSettings(optional_config_file_path=config_file_path)79    # Should still be true, even though the defaut is False80    self.assertEqual(cs.forcePedalOverCC, True)81    # Make sure comment was added:82    fd = open(config_file_path, "r")83    contents = fd.read()84    fd.close()85    self.assertNotEqual(contents.find(expected_comment), -1)86    os.remove(config_file_path)87  def test_comment_update(self):88    config_file_path = "./test_config_file3.cfg"89    old_comment = "# do_auto_update - old description (default: true)"90    old_entry = "do_auto_update = False"91    self.create_empty_config_file(config_file_path,92                                  test_parameter_string= old_comment + "\n" + old_entry)93    expected_comment = "set this setting to false if you do not want op to autoupdate every time you reboot and there is a change on the repo."94    cs = CarSettings(optional_config_file_path=config_file_path)95    # Make sure setting didn't change96    self.assertEqual(cs.doAutoUpdate, False)97    # Make sure comment was updated:98    fd = open(config_file_path, "r")99    contents = fd.read()100    fd.close()101    self.assertTrue(contents.find(expected_comment) != -1)102    # File should have changed (to update comment)103    self.assertEqual(cs.did_write_file, True)104    # Next time we read, file shouldn't change anymore:105    cs = CarSettings(optional_config_file_path=config_file_path)106    self.assertEqual(cs.did_write_file, False)107    # Now remove a config option to cause an update:108    fd = open(config_file_path, "r")109    contents = fd.read()110    fd.close()111    new_contents = contents.replace("limit_battery_max = 80", "")112    fd = open(config_file_path, "w")113    fd.write(new_contents)114    fd.close()115    cs = CarSettings(optional_config_file_path=config_file_path)116    another_comment = 'if you use an aftermarket tesla bosch radar that already has a coded vin, you will have to enter that vin'117    # Make sure other comments were written:118    fd = open(config_file_path, "r")119    contents = fd.read()120    fd.close()121    self.assertTrue(contents.find(another_comment) != -1)122    os.remove(config_file_path)123  def test_float_parsing(self):124    config_file_path = "./test_config_file2.cfg"125    self.create_empty_config_file(config_file_path,126                                  test_parameter_string="radar_offset = 3.14")127    cs = CarSettings(optional_config_file_path=config_file_path)128    self.assertEqual(cs.radarOffset, 3.14)129    os.remove(config_file_path)130  # Make sure existing calls to CarSettings. read_config_file131  # continue to work with no changes132  def test_readconfig_no_arguments(self):133    config_file_path = "./test_config_file2.cfg"134    self.create_empty_config_file(135        config_file_path, test_parameter_string="force_pedal_over_cc = True")136    #cs = CarSettings(optional_config_file_path = config_file_path)137    cs = CarSettingsTestClass()138    try:139      read_config_file(cs)140    except IOError:141      pass    # IOError is expected if running pytest outside of EON environment142    # Make sure calling read_config_files directly works as expected143    read_config_file(cs, config_path=config_file_path)144    self.assertEqual(cs.forcePedalOverCC, True)145    read_config_file(cs, config_path=self.test_config_file)146    self.assertEqual(cs.forcePedalOverCC, False)147    # check for defaults148    self.assertEqual(cs.fix1916, True)149    os.remove(config_file_path)150  # Test get_value interface:151  def test_get_value(self):152    config_file_path = "./test_config_file3.cfg"153    cs = CarSettings(optional_config_file_path=config_file_path)154    value = cs.get_value("userHandle")155    self.assertEqual(value, 'your_tinkla_username')156    value = cs.get_value("doAutoUpdate")157    self.assertEqual(value, True)158    os.remove(config_file_path)159  def check_defaults(self, cs):160    self.assertEqual(cs.userHandle, 'your_tinkla_username')161    self.assertEqual(cs.forceFingerprintTesla, False)162    self.assertEqual(cs.forcePedalOverCC, False)163    self.assertEqual(cs.enableHSO, True)164    self.assertEqual(cs.enableALCA, True)165    self.assertEqual(cs.enableDasEmulation, False)166    self.assertEqual(cs.enableRadarEmulation, False)167    self.assertEqual(cs.enableDriverMonitor, True)168    self.assertEqual(cs.enableShowCar, True)169    self.assertEqual(cs.enableShowLogo, True)170    self.assertEqual(cs.hasNoctuaFan, False)171    self.assertEqual(cs.limitBatteryMinMax, True)172    self.assertEqual(cs.limitBattery_Min, 60)173    self.assertEqual(cs.limitBattery_Max, 80)174    self.assertEqual(cs.blockUploadWhileTethering, False)175    self.assertEqual(cs.tetherIP, "127.0.0.")176    self.assertEqual(cs.useTeslaGPS, False)177    self.assertEqual(cs.useTeslaMapData, False)178    self.assertEqual(cs.hasTeslaIcIntegration, False)179    self.assertEqual(cs.useTeslaRadar, False)180    self.assertEqual(cs.useWithoutHarness, False)181    self.assertEqual(cs.radarVIN, "                 ")182    self.assertEqual(cs.enableLdw, True)183    self.assertEqual(cs.radarOffset, 0)184    self.assertEqual(cs.radarEpasType, 0)185    self.assertEqual(cs.radarPosition, 0)186    self.assertEqual(cs.doAutoUpdate, True)187    self.assertEqual(cs.fix1916, True)188    self.assertEqual(cs.get_value("userHandle"), 'your_tinkla_username')189    self.assertEqual(cs.get_value("doAutoUpdate"), True)190    self.assertEqual(cs.shouldLogCanErrors, False)191    self.assertEqual(cs.shouldLogProcessCommErrors, False)192  # Helper methods193  def delete_test_config_file(self):194    if os.path.exists(self.test_config_file):195      os.remove(self.test_config_file)196  def create_empty_config_file(self, file_name, test_parameter_string=""):197    if os.path.exists(file_name):198      os.remove(file_name)199    fp = open(file_name, "a")200    fp.write("[OP_CONFIG]\n")201    fp.write(test_parameter_string + "\n")202    fp.close()203# Allow running the tests directly via unittests when pytest is not available204if __name__ == '__main__':...cli_config_test.py
Source:cli_config_test.py  
1# Copyright 2017 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#     http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Tests for cli_config."""16from __future__ import absolute_import17from __future__ import division18from __future__ import print_function19import json20import os21import shutil22import tempfile23from tensorflow.python.debug.cli import cli_config24from tensorflow.python.framework import test_util25from tensorflow.python.platform import gfile26from tensorflow.python.platform import googletest27class CLIConfigTest(test_util.TensorFlowTestCase):28  def setUp(self):29    self._tmp_dir = tempfile.mkdtemp()30    self._tmp_config_path = os.path.join(self._tmp_dir, ".tfdbg_config")31    self.assertFalse(gfile.Exists(self._tmp_config_path))32    super(CLIConfigTest, self).setUp()33  def tearDown(self):34    shutil.rmtree(self._tmp_dir)35    super(CLIConfigTest, self).tearDown()36  def testConstructCLIConfigWithoutFile(self):37    config = cli_config.CLIConfig(config_file_path=self._tmp_config_path)38    self.assertEqual(20, config.get("graph_recursion_depth"))39    self.assertEqual(True, config.get("mouse_mode"))40    with self.assertRaises(KeyError):41      config.get("property_that_should_not_exist")42    self.assertTrue(gfile.Exists(self._tmp_config_path))43  def testCLIConfigForwardCompatibilityTest(self):44    config = cli_config.CLIConfig(config_file_path=self._tmp_config_path)45    with open(self._tmp_config_path, "rt") as f:46      config_json = json.load(f)47    # Remove a field to simulate forward compatibility test.48    del config_json["graph_recursion_depth"]49    with open(self._tmp_config_path, "wt") as f:50      json.dump(config_json, f)51    config = cli_config.CLIConfig(config_file_path=self._tmp_config_path)52    self.assertEqual(20, config.get("graph_recursion_depth"))53  def testModifyConfigValue(self):54    config = cli_config.CLIConfig(config_file_path=self._tmp_config_path)55    config.set("graph_recursion_depth", 9)56    config.set("mouse_mode", False)57    self.assertEqual(9, config.get("graph_recursion_depth"))58    self.assertEqual(False, config.get("mouse_mode"))59  def testModifyConfigValueWithTypeCasting(self):60    config = cli_config.CLIConfig(config_file_path=self._tmp_config_path)61    config.set("graph_recursion_depth", "18")62    config.set("mouse_mode", "false")63    self.assertEqual(18, config.get("graph_recursion_depth"))64    self.assertEqual(False, config.get("mouse_mode"))65  def testModifyConfigValueWithTypeCastingFailure(self):66    config = cli_config.CLIConfig(config_file_path=self._tmp_config_path)67    with self.assertRaises(ValueError):68      config.set("mouse_mode", "maybe")69  def testLoadFromModifiedConfigFile(self):70    config = cli_config.CLIConfig(config_file_path=self._tmp_config_path)71    config.set("graph_recursion_depth", 9)72    config.set("mouse_mode", False)73    config2 = cli_config.CLIConfig(config_file_path=self._tmp_config_path)74    self.assertEqual(9, config2.get("graph_recursion_depth"))75    self.assertEqual(False, config2.get("mouse_mode"))76  def testSummarizeFromConfig(self):77    config = cli_config.CLIConfig(config_file_path=self._tmp_config_path)78    output = config.summarize()79    self.assertEqual(80        ["Command-line configuration:",81         "",82         "  graph_recursion_depth: %d" % config.get("graph_recursion_depth"),83         "  mouse_mode: %s" % config.get("mouse_mode")], output.lines)84  def testSummarizeFromConfigWithHighlight(self):85    config = cli_config.CLIConfig(config_file_path=self._tmp_config_path)86    output = config.summarize(highlight="mouse_mode")87    self.assertEqual(88        ["Command-line configuration:",89         "",90         "  graph_recursion_depth: %d" % config.get("graph_recursion_depth"),91         "  mouse_mode: %s" % config.get("mouse_mode")], output.lines)92    self.assertEqual((2, 12, ["underline", "bold"]),93                     output.font_attr_segs[3][0])94    self.assertEqual((14, 18, "bold"), output.font_attr_segs[3][1])95  def testSetCallback(self):96    config = cli_config.CLIConfig(config_file_path=self._tmp_config_path)97    test_value = {"graph_recursion_depth": -1}98    def callback(config):99      test_value["graph_recursion_depth"] = config.get("graph_recursion_depth")100    config.set_callback("graph_recursion_depth", callback)101    config.set("graph_recursion_depth", config.get("graph_recursion_depth") - 1)102    self.assertEqual(test_value["graph_recursion_depth"],103                     config.get("graph_recursion_depth"))104  def testSetCallbackInvalidPropertyName(self):105    config = cli_config.CLIConfig(config_file_path=self._tmp_config_path)106    with self.assertRaises(KeyError):107      config.set_callback("nonexistent_property_name", print)108  def testSetCallbackNotCallable(self):109    config = cli_config.CLIConfig(config_file_path=self._tmp_config_path)110    with self.assertRaises(TypeError):111      config.set_callback("graph_recursion_depth", 1)112if __name__ == "__main__":...configuration.py
Source:configuration.py  
...13            self.config_file_path = config_file_path14        except Exception as error:15            utilities.show_exception_info(error)16            raise error17    def set_config_file_path(self, config_file_path):18        """19        Setter function for config_file_path20        """21        try:22            if type(config_file_path) is not str:23                raise Exception("Class Config_Manager- " +24                                "set_config_file_path(..): " +25                                "config_file_path not of type str")26            self.config_file_path = config_file_path27        except Exception as error:28            utilities.show_exception_info(error)29            raise error30    def read_config(self):31        """32        Reads config file specified by self.config_file_path33        """34        try:35            config_dict = None36            if not os.path.exists(self.config_file_path):37                raise Exception("Class Config_Manager- read_config(..): " +38                                self.config_file_path + " does not exist")...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
