Best Python code snippet using hypothesis
test_criterion.py
Source:test_criterion.py
1# Copyright (C) 2018-2021 CS GROUP - France. All Rights Reserved.2#3# This file is part of the Prewikka program.4#5# SPDX-License-Identifier: BSD-2-Clause6#7# Redistribution and use in source and binary forms, with or without8# modification, are permitted provided that the following conditions are met:9#10# 1. Redistributions of source code must retain the above copyright notice, this11# list of conditions and the following disclaimer.12#13# 2. Redistributions in binary form must reproduce the above copyright notice,14# this list of conditions and the following disclaimer in the documentation15# and/or other materials provided with the distribution.16#17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND18# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDi19# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE20# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR21# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES22# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;23# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND24# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS26# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.27"""28Tests for `prewikka.dataprovider.Criterion()`.29"""30import copy31from prewikka.dataprovider import Criterion, CriterionOperator32def test_criterion_to_string():33 """34 Test `prewikka.dataprovider.Criterion.to_string()` method.35 """36 # empty criterion37 criterion = Criterion()38 assert criterion.to_string() == ''39 # simple criterion40 criterion = Criterion('alert.messageid', '=', 'fakemessageid')41 assert criterion.to_string() == "alert.messageid = 'fakemessageid'"42 criterion = Criterion('alert.messageid', '==', 'fakemessageid')43 assert criterion.to_string() == "alert.messageid = 'fakemessageid'"44 criterion = Criterion('alert.messageid', '!=', 'fakemessageid')45 assert criterion.to_string() == "alert.messageid != 'fakemessageid'"46 criterion = Criterion('alert.messageid', '>', 'fakemessageid')47 assert criterion.to_string() == "alert.messageid > 'fakemessageid'"48 criterion = Criterion('alert.messageid', '>=', 'fakemessageid')49 assert criterion.to_string() == "alert.messageid >= 'fakemessageid'"50 criterion = Criterion('alert.messageid', '<', 'fakemessageid')51 assert criterion.to_string() == "alert.messageid < 'fakemessageid'"52 criterion = Criterion('alert.messageid', '<=', 'fakemessageid')53 assert criterion.to_string() == "alert.messageid <= 'fakemessageid'"54 criterion = Criterion('alert.messageid', '<>*', 'fakemessageid')55 assert criterion.to_string() == "alert.messageid <>* 'fakemessageid'"56 # combined criterion57 criterion_1 = Criterion('alert.messageid', '=', 'fakemessageid1')58 criterion_2 = Criterion('alert.messageid', '=', 'fakemessageid2')59 criterion = Criterion(criterion_1, '||', criterion_2)60 assert criterion.to_string() == "alert.messageid = 'fakemessageid1' || alert.messageid = 'fakemessageid2'"61 criterion = Criterion(criterion_1, '&&', criterion_2)62 assert criterion.to_string() == "alert.messageid = 'fakemessageid1' && alert.messageid = 'fakemessageid2'"63def test_criterion_get_path():64 """65 Test `prewikka.dataprovider.Criterion.get_path()` method.66 """67 # empty criterion68 criterion = Criterion()69 results = set()70 assert criterion.get_paths() == results71 # simple criterion72 criterion = Criterion('alert.messageid', '=', 'fakemessageid')73 results = set()74 results.add('alert.messageid')75 assert criterion.get_paths() == results76 # combined criterion (with || operator)77 criterion_1 = Criterion('alert.messageid', '=', 'fakemessageid1')78 criterion_2 = Criterion('heartbeat.messageid', '=', 'fakemessageid2')79 criterion = Criterion(criterion_1, '||', criterion_2)80 results = set()81 results.add('alert.messageid')82 results.add('heartbeat.messageid')83 assert criterion.get_paths() == results84 # combined criterion (with && operator)85 criterion_1 = Criterion('alert.messageid', '=', 'fakemessageid1')86 criterion_2 = Criterion('heartbeat.messageid', '=', 'fakemessageid2')87 criterion = Criterion(criterion_1, '&&', criterion_2)88 results = set()89 results.add('alert.messageid')90 results.add('heartbeat.messageid')91 assert criterion.get_paths() == results92def test_criterion_flatten():93 """94 Test `prewikka.dataprovider.Criterion.flatten()` method.95 """96 criterion_1 = Criterion('alert.messageid', '=', 'fakemessageid1')97 criterion_2 = Criterion('alert.messageid', '=', 'fakemessageid2')98 criterion_3 = Criterion('alert.messageid', '=', 'fakemessageid3')99 criterion_4 = Criterion('alert.messageid', '=', 'fakemessageid4')100 criterion = ((criterion_1 & criterion_2) & criterion_3) | criterion_4101 flattened = criterion.flatten()102 assert flattened.operator == CriterionOperator.OR103 assert len(flattened.operands) == 2104 assert flattened.operands[0].operator == CriterionOperator.AND105 assert flattened.operands[0].operands == [criterion_1, criterion_2, criterion_3]106 assert flattened.operands[1] == criterion_4107 criterion = Criterion(None, '!', Criterion(None, '!', Criterion(None, '!', criterion_1)))108 flattened = criterion.flatten()109 assert flattened.operator == CriterionOperator.NOT110 assert len(flattened.operands) == 1111 assert flattened.operands[0] == criterion_1112def test_criterion_operations():113 """114 Test `prewikka.dataprovider.Criterion` operations.115 """116 criterion_0 = Criterion()117 criterion_1 = Criterion('alert.messageid', '=', 'fakemessageid1')118 criterion_2 = Criterion('heartbeat.messageid', '=', 'fakemessageid2')119 # __str__()120 assert str(criterion_1) == criterion_1.to_string()121 # __bool__() / __nonzero__()122 assert not criterion_0123 assert criterion_1124 # __copy__()125 criterion_copy = copy.copy(criterion_1)126 assert criterion_copy != criterion_1127 assert criterion_copy.to_string() == criterion_1.to_string()128 # __json__()129 assert criterion_1.__json__() == {'left': 'alert.messageid', 'operator': CriterionOperator.EQUAL, 'right': 'fakemessageid1'}130 # __iadd__()131 criterion_iadd = copy.copy(criterion_1)132 criterion_iadd += criterion_2133 assert criterion_iadd.to_string() == Criterion(criterion_1, '&&', criterion_2).to_string()134 # __ior__()135 criterion_ior = copy.copy(criterion_1)136 criterion_ior |= criterion_2137 assert criterion_ior.to_string() == Criterion(criterion_1, '||', criterion_2).to_string()138 # __iand__()139 criterion_iand = copy.copy(criterion_1)140 criterion_iand &= criterion_2141 assert criterion_iand.to_string() == Criterion(criterion_1, '&&', criterion_2).to_string()142 # __add__()143 criterion_add = criterion_1 + criterion_2144 assert criterion_add.to_string() == Criterion(criterion_1, '&&', criterion_2).to_string()145 # __or__()146 criterion_or = criterion_1 | criterion_2147 assert criterion_or.to_string() == Criterion(criterion_1, '||', criterion_2).to_string()148 # __and__()149 criterion_and = criterion_1 & criterion_2...
composite_loss.py
Source:composite_loss.py
...4# LICENSE file in the root directory of this source tree.5from fairseq import utils6from fairseq.criterions import LegacyFairseqCriterion, register_criterion7from torch import nn8@register_criterion("composite_loss")9class CompositeLoss(LegacyFairseqCriterion):10 """This is a composite loss that, given a list of model outputs and a list of targets,11 computes an average of losses for each output-target pair"""12 def __init__(self, args, task):13 super().__init__(args, task)14 self.underlying_criterion = args.underlying_criterion15 @staticmethod16 def add_args(parser):17 """Add criterion-specific arguments to the parser."""18 # fmt: off19 parser.add_argument('--underlying-criterion', type=str, metavar='VAL', required=True,20 help='underlying criterion to use for the composite loss')21 # fmt: on22 @staticmethod23 def build_underlying_criterion(args, task):24 saved_criterion = args.criterion25 args.criterion = args.underlying_criterion26 assert saved_criterion != args.underlying_criterion27 underlying_criterion = task.build_criterion(args)28 args.criterion = saved_criterion29 return underlying_criterion30 @classmethod31 def build_criterion(cls, args, task):32 underlying_criterion = CompositeLoss.build_underlying_criterion(args, task)33 class FakeModel(nn.Module):34 def __init__(self, model, net_out, target):35 super().__init__()36 self.model = model37 self.net_out = net_out38 self.target = target39 def forward(self, **unused):40 return self.net_out41 def get_normalized_probs(self, net_output, log_probs, sample=None):42 return self.model.get_normalized_probs(43 net_output, log_probs, sample=sample44 )45 def get_targets(self, *unused):46 return self.target47 @property48 def decoder(self):49 return self.model.decoder50 class _CompositeLoss(LegacyFairseqCriterion):51 def __init__(self, args, task, underlying_criterion):52 super().__init__(args, task)53 self.underlying_criterion = underlying_criterion54 def forward(self, model, sample, reduce=True):55 net_outputs = model(**sample["net_input"])56 targets = sample["target"]57 bsz = targets[0].size(0)58 loss = net_outputs[0][0].new(1 if reduce else bsz).float().zero_()59 sample_size = 060 logging_output = {}61 for o, t in zip(net_outputs[0], targets):62 m = FakeModel(model, (o, net_outputs[1]), t)63 sample["target"] = t64 l, ss, logging_output = self.underlying_criterion(m, sample, reduce)65 loss += l66 sample_size += ss67 loss.div_(len(targets))68 sample_size /= len(targets)69 logging_output["loss"] = utils.item(loss.data) if reduce else loss.data70 return loss, sample_size, logging_output71 @staticmethod72 def aggregate_logging_outputs(logging_outputs):73 return underlying_criterion.__class__.aggregate_logging_outputs(74 logging_outputs75 )76 @staticmethod77 def reduce_metrics(logging_outputs) -> None:78 underlying_criterion.__class__.reduce_metrics(logging_outputs)...
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!!