Best Python code snippet using localstack_python
test_exceptions.py
Source:test_exceptions.py  
1import textwrap2from jsonschema import Draft4Validator, exceptions3from jsonschema.compat import PY34from jsonschema.tests.compat import mock, unittest5class TestBestMatch(unittest.TestCase):6    def best_match(self, errors):7        errors = list(errors)8        best = exceptions.best_match(errors)9        reversed_best = exceptions.best_match(reversed(errors))10        msg = "Didn't return a consistent best match!\nGot: {0}\n\nThen: {1}"11        self.assertEqual(12            best, reversed_best, msg=msg.format(best, reversed_best),13        )14        return best15    def test_shallower_errors_are_better_matches(self):16        validator = Draft4Validator(17            {18                "properties": {19                    "foo": {20                        "minProperties": 2,21                        "properties": {"bar": {"type": "object"}},22                    },23                },24            },25        )26        best = self.best_match(validator.iter_errors({"foo": {"bar": []}}))27        self.assertEqual(best.validator, "minProperties")28    def test_oneOf_and_anyOf_are_weak_matches(self):29        """30        A property you *must* match is probably better than one you have to31        match a part of.32        """33        validator = Draft4Validator(34            {35                "minProperties": 2,36                "anyOf": [{"type": "string"}, {"type": "number"}],37                "oneOf": [{"type": "string"}, {"type": "number"}],38            }39        )40        best = self.best_match(validator.iter_errors({}))41        self.assertEqual(best.validator, "minProperties")42    def test_if_the_most_relevant_error_is_anyOf_it_is_traversed(self):43        """44        If the most relevant error is an anyOf, then we traverse its context45        and select the otherwise *least* relevant error, since in this case46        that means the most specific, deep, error inside the instance.47        I.e. since only one of the schemas must match, we look for the most48        relevant one.49        """50        validator = Draft4Validator(51            {52                "properties": {53                    "foo": {54                        "anyOf": [55                            {"type": "string"},56                            {"properties": {"bar": {"type": "array"}}},57                        ],58                    },59                },60            },61        )62        best = self.best_match(validator.iter_errors({"foo": {"bar": 12}}))63        self.assertEqual(best.validator_value, "array")64    def test_if_the_most_relevant_error_is_oneOf_it_is_traversed(self):65        """66        If the most relevant error is an oneOf, then we traverse its context67        and select the otherwise *least* relevant error, since in this case68        that means the most specific, deep, error inside the instance.69        I.e. since only one of the schemas must match, we look for the most70        relevant one.71        """72        validator = Draft4Validator(73            {74                "properties": {75                    "foo": {76                        "oneOf": [77                            {"type": "string"},78                            {"properties": {"bar": {"type": "array"}}},79                        ],80                    },81                },82            },83        )84        best = self.best_match(validator.iter_errors({"foo": {"bar": 12}}))85        self.assertEqual(best.validator_value, "array")86    def test_if_the_most_relevant_error_is_allOf_it_is_traversed(self):87        """88        Now, if the error is allOf, we traverse but select the *most* relevant89        error from the context, because all schemas here must match anyways.90        """91        validator = Draft4Validator(92            {93                "properties": {94                    "foo": {95                        "allOf": [96                            {"type": "string"},97                            {"properties": {"bar": {"type": "array"}}},98                        ],99                    },100                },101            },102        )103        best = self.best_match(validator.iter_errors({"foo": {"bar": 12}}))104        self.assertEqual(best.validator_value, "string")105    def test_nested_context_for_oneOf(self):106        validator = Draft4Validator(107            {108                "properties": {109                    "foo": {110                        "oneOf": [111                            {"type": "string"},112                            {113                                "oneOf": [114                                    {"type": "string"},115                                    {116                                        "properties": {117                                            "bar": {"type": "array"},118                                        },119                                    },120                                ],121                            },122                        ],123                    },124                },125            },126        )127        best = self.best_match(validator.iter_errors({"foo": {"bar": 12}}))128        self.assertEqual(best.validator_value, "array")129    def test_one_error(self):130        validator = Draft4Validator({"minProperties": 2})131        error, = validator.iter_errors({})132        self.assertEqual(133            exceptions.best_match(validator.iter_errors({})).validator,134            "minProperties",135        )136    def test_no_errors(self):137        validator = Draft4Validator({})138        self.assertIsNone(exceptions.best_match(validator.iter_errors({})))139class TestByRelevance(unittest.TestCase):140    def test_short_paths_are_better_matches(self):141        shallow = exceptions.ValidationError("Oh no!", path=["baz"])142        deep = exceptions.ValidationError("Oh yes!", path=["foo", "bar"])143        match = max([shallow, deep], key=exceptions.relevance)144        self.assertIs(match, shallow)145        match = max([deep, shallow], key=exceptions.relevance)146        self.assertIs(match, shallow)147    def test_global_errors_are_even_better_matches(self):148        shallow = exceptions.ValidationError("Oh no!", path=[])149        deep = exceptions.ValidationError("Oh yes!", path=["foo"])150        errors = sorted([shallow, deep], key=exceptions.relevance)151        self.assertEqual(152            [list(error.path) for error in errors],153            [["foo"], []],154        )155        errors = sorted([deep, shallow], key=exceptions.relevance)156        self.assertEqual(157            [list(error.path) for error in errors],158            [["foo"], []],159        )160    def test_weak_validators_are_lower_priority(self):161        weak = exceptions.ValidationError("Oh no!", path=[], validator="a")162        normal = exceptions.ValidationError("Oh yes!", path=[], validator="b")163        best_match = exceptions.by_relevance(weak="a")164        match = max([weak, normal], key=best_match)165        self.assertIs(match, normal)166        match = max([normal, weak], key=best_match)167        self.assertIs(match, normal)168    def test_strong_validators_are_higher_priority(self):169        weak = exceptions.ValidationError("Oh no!", path=[], validator="a")170        normal = exceptions.ValidationError("Oh yes!", path=[], validator="b")171        strong = exceptions.ValidationError("Oh fine!", path=[], validator="c")172        best_match = exceptions.by_relevance(weak="a", strong="c")173        match = max([weak, normal, strong], key=best_match)174        self.assertIs(match, strong)175        match = max([strong, normal, weak], key=best_match)176        self.assertIs(match, strong)177class TestErrorTree(unittest.TestCase):178    def test_it_knows_how_many_total_errors_it_contains(self):179        errors = [mock.MagicMock() for _ in range(8)]180        tree = exceptions.ErrorTree(errors)181        self.assertEqual(tree.total_errors, 8)182    def test_it_contains_an_item_if_the_item_had_an_error(self):183        errors = [exceptions.ValidationError("a message", path=["bar"])]184        tree = exceptions.ErrorTree(errors)185        self.assertIn("bar", tree)186    def test_it_does_not_contain_an_item_if_the_item_had_no_error(self):187        errors = [exceptions.ValidationError("a message", path=["bar"])]188        tree = exceptions.ErrorTree(errors)189        self.assertNotIn("foo", tree)190    def test_validators_that_failed_appear_in_errors_dict(self):191        error = exceptions.ValidationError("a message", validator="foo")192        tree = exceptions.ErrorTree([error])193        self.assertEqual(tree.errors, {"foo": error})194    def test_it_creates_a_child_tree_for_each_nested_path(self):195        errors = [196            exceptions.ValidationError("a bar message", path=["bar"]),197            exceptions.ValidationError("a bar -> 0 message", path=["bar", 0]),198        ]199        tree = exceptions.ErrorTree(errors)200        self.assertIn(0, tree["bar"])201        self.assertNotIn(1, tree["bar"])202    def test_children_have_their_errors_dicts_built(self):203        e1, e2 = (204            exceptions.ValidationError("1", validator="foo", path=["bar", 0]),205            exceptions.ValidationError("2", validator="quux", path=["bar", 0]),206        )207        tree = exceptions.ErrorTree([e1, e2])208        self.assertEqual(tree["bar"][0].errors, {"foo": e1, "quux": e2})209    def test_regression_multiple_errors_with_instance(self):210        e1, e2 = (211            exceptions.ValidationError(212                "1",213                validator="foo",214                path=["bar", "bar2"],215                instance="i1"),216            exceptions.ValidationError(217                "2",218                validator="quux",219                path=["foobar", 2],220                instance="i2"),221        )222        # Will raise an exception if the bug is still there.223        exceptions.ErrorTree([e1, e2])224    def test_it_does_not_contain_subtrees_that_are_not_in_the_instance(self):225        error = exceptions.ValidationError("123", validator="foo", instance=[])226        tree = exceptions.ErrorTree([error])227        with self.assertRaises(IndexError):228            tree[0]229    def test_if_its_in_the_tree_anyhow_it_does_not_raise_an_error(self):230        """231        If a validator is dumb (like :validator:`required` in draft 3) and232        refers to a path that isn't in the instance, the tree still properly233        returns a subtree for that path.234        """235        error = exceptions.ValidationError(236            "a message", validator="foo", instance={}, path=["foo"],237        )238        tree = exceptions.ErrorTree([error])239        self.assertIsInstance(tree["foo"], exceptions.ErrorTree)240class TestErrorInitReprStr(unittest.TestCase):241    def make_error(self, **kwargs):242        defaults = dict(243            message=u"hello",244            validator=u"type",245            validator_value=u"string",246            instance=5,247            schema={u"type": u"string"},248        )249        defaults.update(kwargs)250        return exceptions.ValidationError(**defaults)251    def assertShows(self, expected, **kwargs):252        if PY3:253            expected = expected.replace("u'", "'")254        expected = textwrap.dedent(expected).rstrip("\n")255        error = self.make_error(**kwargs)256        message_line, _, rest = str(error).partition("\n")257        self.assertEqual(message_line, error.message)258        self.assertEqual(rest, expected)259    def test_it_calls_super_and_sets_args(self):260        error = self.make_error()261        self.assertGreater(len(error.args), 1)262    def test_repr(self):263        self.assertEqual(264            repr(exceptions.ValidationError(message="Hello!")),265            "<ValidationError: %r>" % "Hello!",266        )267    def test_unset_error(self):268        error = exceptions.ValidationError("message")269        self.assertEqual(str(error), "message")270        kwargs = {271            "validator": "type",272            "validator_value": "string",273            "instance": 5,274            "schema": {"type": "string"},275        }276        # Just the message should show if any of the attributes are unset277        for attr in kwargs:278            k = dict(kwargs)279            del k[attr]280            error = exceptions.ValidationError("message", **k)281            self.assertEqual(str(error), "message")282    def test_empty_paths(self):283        self.assertShows(284            """285            Failed validating u'type' in schema:286                {u'type': u'string'}287            On instance:288                5289            """,290            path=[],291            schema_path=[],292        )293    def test_one_item_paths(self):294        self.assertShows(295            """296            Failed validating u'type' in schema:297                {u'type': u'string'}298            On instance[0]:299                5300            """,301            path=[0],302            schema_path=["items"],303        )304    def test_multiple_item_paths(self):305        self.assertShows(306            """307            Failed validating u'type' in schema[u'items'][0]:308                {u'type': u'string'}309            On instance[0][u'a']:310                5311            """,312            path=[0, u"a"],313            schema_path=[u"items", 0, 1],314        )315    def test_uses_pprint(self):316        with mock.patch("pprint.pformat") as pformat:317            str(self.make_error())318            self.assertEqual(pformat.call_count, 2)  # schema + instance319    def test_str_works_with_instances_having_overriden_eq_operator(self):320        """321        Check for https://github.com/Julian/jsonschema/issues/164 which322        rendered exceptions unusable when a `ValidationError` involved323        instances with an `__eq__` method that returned truthy values.324        """325        instance = mock.MagicMock()326        error = exceptions.ValidationError(327            "a message",328            validator="foo",329            instance=instance,330            validator_value="some",331            schema="schema",332        )333        str(error)...scene_exceptions.py
Source:scene_exceptions.py  
...56        "scene_exceptions_refresh",57        {'last_refreshed': int(time.mktime(datetime.datetime.today().timetuple()))},58        {'list': exList}59    )60def get_scene_exceptions(indexer_id, season=-1):61    """62    Given a indexer_id, return a list of all the scene exceptions.63    """64    exceptionsList = []65    if indexer_id not in exceptionsCache or season not in exceptionsCache[indexer_id]:66        cache_db_con = db.DBConnection('cache.db')67        exceptions = cache_db_con.select("SELECT show_name FROM scene_exceptions WHERE indexer_id = ? and season = ?",68                                         [indexer_id, season])69        if exceptions:70            exceptionsList = list({cur_exception[b"show_name"] for cur_exception in exceptions})71            if indexer_id not in exceptionsCache:72                exceptionsCache[indexer_id] = {}73            exceptionsCache[indexer_id][season] = exceptionsList74    else:75        exceptionsList = exceptionsCache[indexer_id][season]76    # Add generic exceptions regardless of the season if there is no exception for season77    if season != -1 and not exceptionsList:78        exceptionsList += get_scene_exceptions(indexer_id, season=-1)79    return list({exception for exception in exceptionsList})80def get_all_scene_exceptions(indexer_id):81    """82    Get all scene exceptions for a show ID83    :param indexer_id: ID to check84    :return: dict of exceptions85    """86    exceptionsDict = {}87    cache_db_con = db.DBConnection('cache.db')88    exceptions = cache_db_con.select("SELECT show_name,season,custom FROM scene_exceptions WHERE indexer_id = ?", [indexer_id])89    if exceptions:90        for cur_exception in exceptions:91            if not cur_exception[b"season"] in exceptionsDict:92                exceptionsDict[cur_exception[b"season"]] = []93            exceptionsDict[cur_exception[b"season"]].append({94                "show_name": cur_exception[b"show_name"],95                "custom": bool(cur_exception[b"custom"])96            })97    return exceptionsDict98def get_scene_seasons(indexer_id):99    """100    return a list of season numbers that have scene exceptions101    """102    exceptionsSeasonList = []103    if indexer_id not in exceptionsSeasonCache:104        cache_db_con = db.DBConnection('cache.db')105        sql_results = cache_db_con.select("SELECT DISTINCT(season) as season FROM scene_exceptions WHERE indexer_id = ?",106                                          [indexer_id])107        if sql_results:108            exceptionsSeasonList = list({int(x[b"season"]) for x in sql_results})109            if indexer_id not in exceptionsSeasonCache:110                exceptionsSeasonCache[indexer_id] = {}111            exceptionsSeasonCache[indexer_id] = exceptionsSeasonList112    else:113        exceptionsSeasonList = exceptionsSeasonCache[indexer_id]114    return exceptionsSeasonList115def get_scene_exception_by_name(show_name):116    return get_scene_exception_by_name_multiple(show_name)[0]117def get_scene_exception_by_name_multiple(show_name):118    """119    Given a show name, return the indexerid of the exception, None if no exception120    is present.121    """122    # try the obvious case first123    cache_db_con = db.DBConnection('cache.db')124    exception_result = cache_db_con.select(125        "SELECT indexer_id, season FROM scene_exceptions WHERE LOWER(show_name) = ? ORDER BY season ASC",126        [show_name.lower()])127    if exception_result:128        return [(int(x[b"indexer_id"]), int(x[b"season"])) for x in exception_result]129    out = []130    all_exception_results = cache_db_con.select("SELECT show_name, indexer_id, season FROM scene_exceptions")131    for cur_exception in all_exception_results:132        cur_exception_name = cur_exception[b"show_name"]133        cur_indexer_id = int(cur_exception[b"indexer_id"])134        if show_name.lower() in (135                cur_exception_name.lower(),136                sickbeard.helpers.sanitizeSceneName(cur_exception_name).lower().replace('.', ' ')):137            logger.log("Scene exception lookup got indexer id {0}, using that".format138                       (cur_indexer_id), logger.DEBUG)139            out.append((cur_indexer_id, int(cur_exception[b"season"])))140    if out:141        return out142    return [(None, None)]143def retrieve_exceptions():  # pylint:disable=too-many-locals, too-many-branches144    """145    Looks up the exceptions on github, parses them into a dict, and inserts them into the146    scene_exceptions table in cache.db. Also clears the scene name cache.147    """148    do_refresh = False149    for indexer in sickbeard.indexerApi().indexers:150        if shouldRefresh(sickbeard.indexerApi(indexer).name):151            do_refresh = True152    if do_refresh:153        loc = sickbeard.indexerApi(INDEXER_TVDB).config['scene_loc']154        logger.log("Checking for scene exception updates from {0}".format(loc))155        session = sickbeard.indexerApi(INDEXER_TVDB).session156        proxy = sickbeard.PROXY_SETTING157        if proxy and sickbeard.PROXY_INDEXERS:158            session.proxies = {159                "http": proxy,160                "https": proxy,161            }162        try:163            jdata = helpers.getURL(loc, session=session, returns='json')164        except Exception:165            jdata = None166        if not jdata:167            # When jdata is None, trouble connecting to github, or reading file failed168            logger.log("Check scene exceptions update failed. Unable to update from {0}".format(loc), logger.DEBUG)169        else:170            for indexer in sickbeard.indexerApi().indexers:171                try:172                    setLastRefresh(sickbeard.indexerApi(indexer).name)173                    for indexer_id in jdata[sickbeard.indexerApi(indexer).config['xem_origin']]:174                        alias_list = [175                            {scene_exception: int(scene_season)}176                            for scene_season in jdata[sickbeard.indexerApi(indexer).config['xem_origin']][indexer_id]177                            for scene_exception in jdata[sickbeard.indexerApi(indexer).config['xem_origin']][indexer_id][scene_season]178                        ]179                        exception_dict[indexer_id] = alias_list180                except Exception:181                    continue182    # XEM scene exceptions183    _xem_exceptions_fetcher()184    for xem_ex in xem_exception_dict:185        if xem_ex in exception_dict:186            exception_dict[xem_ex] += exception_dict[xem_ex]187        else:188            exception_dict[xem_ex] = xem_exception_dict[xem_ex]189    # AniDB scene exceptions190    _anidb_exceptions_fetcher()191    for anidb_ex in anidb_exception_dict:192        if anidb_ex in exception_dict:193            exception_dict[anidb_ex] += anidb_exception_dict[anidb_ex]194        else:195            exception_dict[anidb_ex] = anidb_exception_dict[anidb_ex]196    queries = []197    cache_db_con = db.DBConnection('cache.db')198    for cur_indexer_id in exception_dict:199        sql_ex = cache_db_con.select("SELECT show_name FROM scene_exceptions WHERE indexer_id = ?;", [cur_indexer_id])200        existing_exceptions = [x[b"show_name"] for x in sql_ex]201        if cur_indexer_id not in exception_dict:202            continue203        for cur_exception_dict in exception_dict[cur_indexer_id]:204            for ex in six.iteritems(cur_exception_dict):205                cur_exception, curSeason = ex206                if cur_exception not in existing_exceptions:207                    queries.append(208                        ["INSERT OR IGNORE INTO scene_exceptions (indexer_id, show_name, season) VALUES (?,?,?);",209                         [cur_indexer_id, cur_exception, curSeason]])210    if queries:211        cache_db_con.mass_action(queries)212        logger.log("Updated scene exceptions", logger.DEBUG)213    # cleanup214    exception_dict.clear()215    anidb_exception_dict.clear()216    xem_exception_dict.clear()217def update_scene_exceptions(indexer_id, scene_exceptions):218    """219    Given a indexer_id, and a list of all show scene exceptions, update the db.220    """221    cache_db_con = db.DBConnection('cache.db')222    cache_db_con.action('DELETE FROM scene_exceptions WHERE indexer_id=? and custom=1', [indexer_id])223    logger.log("Updating scene exceptions", logger.INFO)224    for season in scene_exceptions:225        for cur_exception in scene_exceptions[season]:226            cache_db_con.action("INSERT INTO scene_exceptions (indexer_id, show_name, season, custom) VALUES (?,?,?,?)",227                                [indexer_id, cur_exception["show_name"], season, cur_exception["custom"]])228    rebuild_exception_cache(indexer_id)229def _anidb_exceptions_fetcher():230    if shouldRefresh('anidb'):231        logger.log("Checking for scene exception updates for AniDB")...translations.ts
Source:translations.ts  
1/*2 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one3 * or more contributor license agreements. Licensed under the Elastic License;4 * you may not use this file except in compliance with the Elastic License.5 */6import { i18n } from '@kbn/i18n';7export const DETECTION_LIST = i18n.translate(8  'xpack.securitySolution.exceptions.detectionListLabel',9  {10    defaultMessage: 'Detection list',11  }12);13export const ENDPOINT_LIST = i18n.translate('xpack.securitySolution.exceptions.endpointListLabel', {14  defaultMessage: 'Endpoint list',15});16export const EDIT = i18n.translate('xpack.securitySolution.exceptions.editButtonLabel', {17  defaultMessage: 'Edit',18});19export const REMOVE = i18n.translate('xpack.securitySolution.exceptions.removeButtonLabel', {20  defaultMessage: 'Remove',21});22export const COMMENTS_SHOW = (comments: number) =>23  i18n.translate('xpack.securitySolution.exceptions.showCommentsLabel', {24    values: { comments },25    defaultMessage: 'Show ({comments}) {comments, plural, =1 {Comment} other {Comments}}',26  });27export const COMMENTS_HIDE = (comments: number) =>28  i18n.translate('xpack.securitySolution.exceptions.hideCommentsLabel', {29    values: { comments },30    defaultMessage: 'Hide ({comments}) {comments, plural, =1 {Comment} other {Comments}}',31  });32export const DATE_CREATED = i18n.translate('xpack.securitySolution.exceptions.dateCreatedLabel', {33  defaultMessage: 'Date created',34});35export const CREATED_BY = i18n.translate('xpack.securitySolution.exceptions.createdByLabel', {36  defaultMessage: 'Created by',37});38export const COMMENT = i18n.translate('xpack.securitySolution.exceptions.commentLabel', {39  defaultMessage: 'Comment',40});41export const COMMENT_EVENT = i18n.translate('xpack.securitySolution.exceptions.commentEventLabel', {42  defaultMessage: 'added a comment',43});44export const OPERATING_SYSTEM = i18n.translate(45  'xpack.securitySolution.exceptions.operatingSystemLabel',46  {47    defaultMessage: 'OS',48  }49);50export const SEARCH_DEFAULT = i18n.translate(51  'xpack.securitySolution.exceptions.viewer.searchDefaultPlaceholder',52  {53    defaultMessage: 'Search field (ex: host.name)',54  }55);56export const ADD_EXCEPTION_LABEL = i18n.translate(57  'xpack.securitySolution.exceptions.viewer.addExceptionLabel',58  {59    defaultMessage: 'Add new exception',60  }61);62export const ADD_TO_ENDPOINT_LIST = i18n.translate(63  'xpack.securitySolution.exceptions.viewer.addToEndpointListLabel',64  {65    defaultMessage: 'Add to endpoint list',66  }67);68export const ADD_TO_DETECTIONS_LIST = i18n.translate(69  'xpack.securitySolution.exceptions.viewer.addToDetectionsListLabel',70  {71    defaultMessage: 'Add to detections list',72  }73);74export const EXCEPTION_EMPTY_PROMPT_TITLE = i18n.translate(75  'xpack.securitySolution.exceptions.viewer.emptyPromptTitle',76  {77    defaultMessage: 'You have no exceptions',78  }79);80export const EXCEPTION_EMPTY_PROMPT_BODY = i18n.translate(81  'xpack.securitySolution.exceptions.viewer.emptyPromptBody',82  {83    defaultMessage:84      'You can add an exception to fine tune the rule so that it suppresses alerts that meet specified conditions. Exceptions leverage detection accuracy, which can help reduce the number of false positives.',85  }86);87export const FETCH_LIST_ERROR = i18n.translate(88  'xpack.securitySolution.exceptions.viewer.fetchingListError',89  {90    defaultMessage: 'Error fetching exceptions',91  }92);93export const DELETE_EXCEPTION_ERROR = i18n.translate(94  'xpack.securitySolution.exceptions.viewer.deleteExceptionError',95  {96    defaultMessage: 'Error deleting exception',97  }98);99export const ITEMS_PER_PAGE = (items: number) =>100  i18n.translate('xpack.securitySolution.exceptions.exceptionsPaginationLabel', {101    values: { items },102    defaultMessage: 'Items per page: {items}',103  });104export const NUMBER_OF_ITEMS = (items: number) =>105  i18n.translate('xpack.securitySolution.exceptions.paginationNumberOfItemsLabel', {106    values: { items },107    defaultMessage: '{items} items',108  });109export const REFRESH = i18n.translate('xpack.securitySolution.exceptions.utilityRefreshLabel', {110  defaultMessage: 'Refresh',111});112export const SHOWING_EXCEPTIONS = (items: number) =>113  i18n.translate('xpack.securitySolution.exceptions.utilityNumberExceptionsLabel', {114    values: { items },115    defaultMessage: 'Showing {items} {items, plural, =1 {exception} other {exceptions}}',...jsx-boolean-value.js
Source:jsx-boolean-value.js  
1/**2 * @fileoverview Enforce boolean attributes notation in JSX3 * @author Yannick Croissant4 */5'use strict';6const docsUrl = require('../util/docsUrl');7// ------------------------------------------------------------------------------8// Rule Definition9// ------------------------------------------------------------------------------10const exceptionsSchema = {11  type: 'array',12  items: {type: 'string', minLength: 1},13  uniqueItems: true14};15const ALWAYS = 'always';16const NEVER = 'never';17const errorData = new WeakMap();18function getErrorData(exceptions) {19  if (!errorData.has(exceptions)) {20    const exceptionProps = Array.from(exceptions, name => `\`${name}\``).join(', ');21    const exceptionsMessage = exceptions.size > 0 ? ` for the following props: ${exceptionProps}` : '';22    errorData.set(exceptions, {exceptionsMessage});23  }24  return errorData.get(exceptions);25}26function isAlways(configuration, exceptions, propName) {27  const isException = exceptions.has(propName);28  if (configuration === ALWAYS) {29    return !isException;30  }31  return isException;32}33function isNever(configuration, exceptions, propName) {34  const isException = exceptions.has(propName);35  if (configuration === NEVER) {36    return !isException;37  }38  return isException;39}40module.exports = {41  meta: {42    docs: {43      description: 'Enforce boolean attributes notation in JSX',44      category: 'Stylistic Issues',45      recommended: false,46      url: docsUrl('jsx-boolean-value')47    },48    fixable: 'code',49    schema: {50      anyOf: [{51        type: 'array',52        items: [{enum: [ALWAYS, NEVER]}],53        additionalItems: false54      }, {55        type: 'array',56        items: [{57          enum: [ALWAYS]58        }, {59          type: 'object',60          additionalProperties: false,61          properties: {62            [NEVER]: exceptionsSchema63          }64        }],65        additionalItems: false66      }, {67        type: 'array',68        items: [{69          enum: [NEVER]70        }, {71          type: 'object',72          additionalProperties: false,73          properties: {74            [ALWAYS]: exceptionsSchema75          }76        }],77        additionalItems: false78      }]79    }80  },81  create(context) {82    const configuration = context.options[0] || NEVER;83    const configObject = context.options[1] || {};84    const exceptions = new Set((configuration === ALWAYS ? configObject[NEVER] : configObject[ALWAYS]) || []);85    const NEVER_MESSAGE = 'Value must be omitted for boolean attributes{{exceptionsMessage}}';86    const ALWAYS_MESSAGE = 'Value must be set for boolean attributes{{exceptionsMessage}}';87    return {88      JSXAttribute(node) {89        const propName = node.name && node.name.name;90        const value = node.value;91        if (isAlways(configuration, exceptions, propName) && value === null) {92          const data = getErrorData(exceptions);93          context.report({94            node,95            message: ALWAYS_MESSAGE,96            data,97            fix(fixer) {98              return fixer.insertTextAfter(node, '={true}');99            }100          });101        }102        if (isNever(configuration, exceptions, propName) && value && value.type === 'JSXExpressionContainer' && value.expression.value === true) {103          const data = getErrorData(exceptions);104          context.report({105            node,106            message: NEVER_MESSAGE,107            data,108            fix(fixer) {109              return fixer.removeRange([node.name.range[1], value.range[1]]);110            }111          });112        }113      }114    };115  }...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!!
