prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
|---|---|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
<|fim_middle|>
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
return attn_type
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
<|fim_middle|>
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
<|fim_middle|>
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
<|fim_middle|>
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = SEModule
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
<|fim_middle|>
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = EffectiveSEModule
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
<|fim_middle|>
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = EcaModule
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
<|fim_middle|>
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = partial(EcaModule, use_mlp=True)
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
<|fim_middle|>
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = CecaModule
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
<|fim_middle|>
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = GatherExcite
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
<|fim_middle|>
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = GlobalContext
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
<|fim_middle|>
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
<|fim_middle|>
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = CbamModule
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
<|fim_middle|>
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = LightCbamModule
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
<|fim_middle|>
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = SelectiveKernel
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
<|fim_middle|>
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = SplitAttn
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
<|fim_middle|>
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
return LambdaLayer
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
<|fim_middle|>
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
return BottleneckAttn
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
<|fim_middle|>
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
return HaloAttn
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
<|fim_middle|>
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = NonLocalAttn
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
<|fim_middle|>
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = BatNonLocalAttn
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
<|fim_middle|>
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
assert False, "Invalid attn module (%s)" % attn_type
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
<|fim_middle|>
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
if attn_type:
module_cls = SEModule
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
<|fim_middle|>
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = SEModule
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
<|fim_middle|>
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
module_cls = attn_type
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
<|fim_middle|>
return None
<|fim▁end|>
|
return module_cls(channels, **kwargs)
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def <|fim_middle|>(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
get_attn
|
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import GlobalContext
from .halo_attn import HaloAttn
from .lambda_layer import LambdaLayer
from .non_local_attn import NonLocalAttn, BatNonLocalAttn
from .selective_kernel import SelectiveKernel
from .split_attn import SplitAttn
from .squeeze_excite import SEModule, EffectiveSEModule
def get_attn(attn_type):
if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing network architecture blocks in addition to existing convolutions.
if attn_type == 'se':
module_cls = SEModule
elif attn_type == 'ese':
module_cls = EffectiveSEModule
elif attn_type == 'eca':
module_cls = EcaModule
elif attn_type == 'ecam':
module_cls = partial(EcaModule, use_mlp=True)
elif attn_type == 'ceca':
module_cls = CecaModule
elif attn_type == 'ge':
module_cls = GatherExcite
elif attn_type == 'gc':
module_cls = GlobalContext
elif attn_type == 'gca':
module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False)
elif attn_type == 'cbam':
module_cls = CbamModule
elif attn_type == 'lcbam':
module_cls = LightCbamModule
# Attention / attention-like modules w/ significant params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'sk':
module_cls = SelectiveKernel
elif attn_type == 'splat':
module_cls = SplitAttn
# Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
return LambdaLayer
elif attn_type == 'bottleneck':
return BottleneckAttn
elif attn_type == 'halo':
return HaloAttn
elif attn_type == 'nl':
module_cls = NonLocalAttn
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
module_cls = attn_type
return module_cls
def <|fim_middle|>(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
<|fim▁end|>
|
create_attn
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}<|fim▁hole|>
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)<|fim▁end|>
| |
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
<|fim_middle|>
<|fim▁end|>
|
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
<|fim_middle|>
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
<|fim_middle|>
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
<|fim_middle|>
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
<|fim_middle|>
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
if 'peter@example.com' in filterstr:
return result.items()
return []
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
<|fim_middle|>
<|fim▁end|>
|
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
<|fim_middle|>
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
<|fim_middle|>
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
return result.items()
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
<|fim_middle|>
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
return result.items()
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
<|fim_middle|>
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
<|fim_middle|>
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
return result.items()
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
<|fim_middle|>
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
if 'peter@example.com' in filterstr:
return result.items()
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
<|fim_middle|>
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
return result.items()
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def <|fim_middle|>(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
test_exists
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def <|fim_middle|>(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
search_s
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def <|fim_middle|>(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
test_employee
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def <|fim_middle|>(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
search_s
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def <|fim_middle|>(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
test_ingroup
|
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>import json
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
class TestAPI(TestCase):
@mock.patch('ldap.initialize')
def test_exists(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:exists')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
# check that 400 Bad Request errors are proper JSON
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(
json.loads(response.content),
{'error': "missing key 'mail'"}
)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
# if 'hgaccountenabled=TRUE' in filterstr:
# return []
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
# response = self.client.get(url, {'mail': 'peter@example.com',
# 'hgaccountenabled': ''})
# self.assertEqual(response.status_code, 200)
# self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'gender': 'male'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
@mock.patch('ldap.initialize')
def test_employee(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:employee')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123',
'mail': 'peter@mozilla.com',
'sn': u'B\xe3ngtsson'},
}
def search_s(base, scope, filterstr, *args, **kwargs):
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'never@heard.of.com'})
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
self.assertEqual(json.loads(response.content), False)
@mock.patch('ldap.initialize')
def test_ingroup(self, mocked_initialize):
connection = mock.MagicMock()
mocked_initialize.return_value = connection
url = reverse('api:in-group')
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': ''})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com'})
self.assertEqual(response.status_code, 400)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': ''})
self.assertEqual(response.status_code, 400)
result = {
'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'},
}
def <|fim_middle|>(base, scope, filterstr, *args, **kwargs):
if 'ou=groups' in base:
if (
'peter@example.com' in filterstr and
'cn=CrashStats' in filterstr
):
return result.items()
else:
# basic lookup
if 'peter@example.com' in filterstr:
return result.items()
return []
connection.search_s.side_effect = search_s
response = self.client.get(url, {'mail': 'not@head.of.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'CrashStats'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), True)
response = self.client.get(url, {'mail': 'peter@example.com',
'cn': 'NotInGroup'})
self.assertEqual(response.status_code, 200)
self.assertEqual(json.loads(response.content), False)
<|fim▁end|>
|
search_s
|
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.shortcuts import render
<|fim▁hole|>
def home(request):
return render(request, 'home.html', {})<|fim▁end|>
| |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.shortcuts import render
def home(request):
<|fim_middle|>
<|fim▁end|>
|
return render(request, 'home.html', {})
|
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.shortcuts import render
def <|fim_middle|>(request):
return render(request, 'home.html', {})
<|fim▁end|>
|
home
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|>from nose.tools import with_setup
import os
import hk_glazer as js2deg
import subprocess
import json
class TestClass:
@classmethod
def setup_class(cls):
cls.here = os.path.dirname(__file__)
cls.data = cls.here + '/data'
def test_1(self):
'''Test 1: Check that json_to_degree works when imported'''
with open(self.data + "/json_test_in.json") as config_file:
config_dict = json.load(config_file)
gen_str = js2deg.dict_to_dat(config_dict)<|fim▁hole|> with open(self.data + "/json_test_out.txt") as verif_file:
test_str = verif_file.read()
assert(test_str == gen_str)
pass
def test_2(self):
'''Test 2: Check command line execution when saving to file'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
print(cmd)
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"])
with open("test2.txt") as file:
gen_str = file.read()
with open(self.data + "/json_test_out.txt") as file:
test_str = file.read()
assert(test_str == gen_str)
os.remove("test2.txt")
pass
def test_3(self):
'''Test 3: Command line execution when outfile already exists'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"])
try:
subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"])
except Exception as e:
#print(type(e))
assert(type(e) == subprocess.CalledProcessError)
pass
else:
assert(False)
finally:
os.remove("test3.txt")<|fim▁end|>
| |
<|file_name|>test.py<|end_file_name|><|fim▁begin|>from nose.tools import with_setup
import os
import hk_glazer as js2deg
import subprocess
import json
class TestClass:
<|fim_middle|>
<|fim▁end|>
|
@classmethod
def setup_class(cls):
cls.here = os.path.dirname(__file__)
cls.data = cls.here + '/data'
def test_1(self):
'''Test 1: Check that json_to_degree works when imported'''
with open(self.data + "/json_test_in.json") as config_file:
config_dict = json.load(config_file)
gen_str = js2deg.dict_to_dat(config_dict)
with open(self.data + "/json_test_out.txt") as verif_file:
test_str = verif_file.read()
assert(test_str == gen_str)
pass
def test_2(self):
'''Test 2: Check command line execution when saving to file'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
print(cmd)
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"])
with open("test2.txt") as file:
gen_str = file.read()
with open(self.data + "/json_test_out.txt") as file:
test_str = file.read()
assert(test_str == gen_str)
os.remove("test2.txt")
pass
def test_3(self):
'''Test 3: Command line execution when outfile already exists'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"])
try:
subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"])
except Exception as e:
#print(type(e))
assert(type(e) == subprocess.CalledProcessError)
pass
else:
assert(False)
finally:
os.remove("test3.txt")
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|>from nose.tools import with_setup
import os
import hk_glazer as js2deg
import subprocess
import json
class TestClass:
@classmethod
def setup_class(cls):
<|fim_middle|>
def test_1(self):
'''Test 1: Check that json_to_degree works when imported'''
with open(self.data + "/json_test_in.json") as config_file:
config_dict = json.load(config_file)
gen_str = js2deg.dict_to_dat(config_dict)
with open(self.data + "/json_test_out.txt") as verif_file:
test_str = verif_file.read()
assert(test_str == gen_str)
pass
def test_2(self):
'''Test 2: Check command line execution when saving to file'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
print(cmd)
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"])
with open("test2.txt") as file:
gen_str = file.read()
with open(self.data + "/json_test_out.txt") as file:
test_str = file.read()
assert(test_str == gen_str)
os.remove("test2.txt")
pass
def test_3(self):
'''Test 3: Command line execution when outfile already exists'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"])
try:
subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"])
except Exception as e:
#print(type(e))
assert(type(e) == subprocess.CalledProcessError)
pass
else:
assert(False)
finally:
os.remove("test3.txt")
<|fim▁end|>
|
cls.here = os.path.dirname(__file__)
cls.data = cls.here + '/data'
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|>from nose.tools import with_setup
import os
import hk_glazer as js2deg
import subprocess
import json
class TestClass:
@classmethod
def setup_class(cls):
cls.here = os.path.dirname(__file__)
cls.data = cls.here + '/data'
def test_1(self):
<|fim_middle|>
def test_2(self):
'''Test 2: Check command line execution when saving to file'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
print(cmd)
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"])
with open("test2.txt") as file:
gen_str = file.read()
with open(self.data + "/json_test_out.txt") as file:
test_str = file.read()
assert(test_str == gen_str)
os.remove("test2.txt")
pass
def test_3(self):
'''Test 3: Command line execution when outfile already exists'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"])
try:
subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"])
except Exception as e:
#print(type(e))
assert(type(e) == subprocess.CalledProcessError)
pass
else:
assert(False)
finally:
os.remove("test3.txt")
<|fim▁end|>
|
'''Test 1: Check that json_to_degree works when imported'''
with open(self.data + "/json_test_in.json") as config_file:
config_dict = json.load(config_file)
gen_str = js2deg.dict_to_dat(config_dict)
with open(self.data + "/json_test_out.txt") as verif_file:
test_str = verif_file.read()
assert(test_str == gen_str)
pass
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|>from nose.tools import with_setup
import os
import hk_glazer as js2deg
import subprocess
import json
class TestClass:
@classmethod
def setup_class(cls):
cls.here = os.path.dirname(__file__)
cls.data = cls.here + '/data'
def test_1(self):
'''Test 1: Check that json_to_degree works when imported'''
with open(self.data + "/json_test_in.json") as config_file:
config_dict = json.load(config_file)
gen_str = js2deg.dict_to_dat(config_dict)
with open(self.data + "/json_test_out.txt") as verif_file:
test_str = verif_file.read()
assert(test_str == gen_str)
pass
def test_2(self):
<|fim_middle|>
def test_3(self):
'''Test 3: Command line execution when outfile already exists'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"])
try:
subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"])
except Exception as e:
#print(type(e))
assert(type(e) == subprocess.CalledProcessError)
pass
else:
assert(False)
finally:
os.remove("test3.txt")
<|fim▁end|>
|
'''Test 2: Check command line execution when saving to file'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
print(cmd)
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"])
with open("test2.txt") as file:
gen_str = file.read()
with open(self.data + "/json_test_out.txt") as file:
test_str = file.read()
assert(test_str == gen_str)
os.remove("test2.txt")
pass
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|>from nose.tools import with_setup
import os
import hk_glazer as js2deg
import subprocess
import json
class TestClass:
@classmethod
def setup_class(cls):
cls.here = os.path.dirname(__file__)
cls.data = cls.here + '/data'
def test_1(self):
'''Test 1: Check that json_to_degree works when imported'''
with open(self.data + "/json_test_in.json") as config_file:
config_dict = json.load(config_file)
gen_str = js2deg.dict_to_dat(config_dict)
with open(self.data + "/json_test_out.txt") as verif_file:
test_str = verif_file.read()
assert(test_str == gen_str)
pass
def test_2(self):
'''Test 2: Check command line execution when saving to file'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
print(cmd)
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"])
with open("test2.txt") as file:
gen_str = file.read()
with open(self.data + "/json_test_out.txt") as file:
test_str = file.read()
assert(test_str == gen_str)
os.remove("test2.txt")
pass
def test_3(self):
<|fim_middle|>
<|fim▁end|>
|
'''Test 3: Command line execution when outfile already exists'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"])
try:
subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"])
except Exception as e:
#print(type(e))
assert(type(e) == subprocess.CalledProcessError)
pass
else:
assert(False)
finally:
os.remove("test3.txt")
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|>from nose.tools import with_setup
import os
import hk_glazer as js2deg
import subprocess
import json
class TestClass:
@classmethod
def setup_class(cls):
cls.here = os.path.dirname(__file__)
cls.data = cls.here + '/data'
def test_1(self):
'''Test 1: Check that json_to_degree works when imported'''
with open(self.data + "/json_test_in.json") as config_file:
config_dict = json.load(config_file)
gen_str = js2deg.dict_to_dat(config_dict)
with open(self.data + "/json_test_out.txt") as verif_file:
test_str = verif_file.read()
assert(test_str == gen_str)
pass
def test_2(self):
'''Test 2: Check command line execution when saving to file'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
print(cmd)
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"])
with open("test2.txt") as file:
gen_str = file.read()
with open(self.data + "/json_test_out.txt") as file:
test_str = file.read()
assert(test_str == gen_str)
os.remove("test2.txt")
pass
def test_3(self):
'''Test 3: Command line execution when outfile already exists'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"])
try:
subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"])
except Exception as e:
#print(type(e))
assert(type(e) == subprocess.CalledProcessError)
pass
else:
<|fim_middle|>
finally:
os.remove("test3.txt")
<|fim▁end|>
|
assert(False)
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|>from nose.tools import with_setup
import os
import hk_glazer as js2deg
import subprocess
import json
class TestClass:
@classmethod
def <|fim_middle|>(cls):
cls.here = os.path.dirname(__file__)
cls.data = cls.here + '/data'
def test_1(self):
'''Test 1: Check that json_to_degree works when imported'''
with open(self.data + "/json_test_in.json") as config_file:
config_dict = json.load(config_file)
gen_str = js2deg.dict_to_dat(config_dict)
with open(self.data + "/json_test_out.txt") as verif_file:
test_str = verif_file.read()
assert(test_str == gen_str)
pass
def test_2(self):
'''Test 2: Check command line execution when saving to file'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
print(cmd)
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"])
with open("test2.txt") as file:
gen_str = file.read()
with open(self.data + "/json_test_out.txt") as file:
test_str = file.read()
assert(test_str == gen_str)
os.remove("test2.txt")
pass
def test_3(self):
'''Test 3: Command line execution when outfile already exists'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"])
try:
subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"])
except Exception as e:
#print(type(e))
assert(type(e) == subprocess.CalledProcessError)
pass
else:
assert(False)
finally:
os.remove("test3.txt")
<|fim▁end|>
|
setup_class
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|>from nose.tools import with_setup
import os
import hk_glazer as js2deg
import subprocess
import json
class TestClass:
@classmethod
def setup_class(cls):
cls.here = os.path.dirname(__file__)
cls.data = cls.here + '/data'
def <|fim_middle|>(self):
'''Test 1: Check that json_to_degree works when imported'''
with open(self.data + "/json_test_in.json") as config_file:
config_dict = json.load(config_file)
gen_str = js2deg.dict_to_dat(config_dict)
with open(self.data + "/json_test_out.txt") as verif_file:
test_str = verif_file.read()
assert(test_str == gen_str)
pass
def test_2(self):
'''Test 2: Check command line execution when saving to file'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
print(cmd)
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"])
with open("test2.txt") as file:
gen_str = file.read()
with open(self.data + "/json_test_out.txt") as file:
test_str = file.read()
assert(test_str == gen_str)
os.remove("test2.txt")
pass
def test_3(self):
'''Test 3: Command line execution when outfile already exists'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"])
try:
subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"])
except Exception as e:
#print(type(e))
assert(type(e) == subprocess.CalledProcessError)
pass
else:
assert(False)
finally:
os.remove("test3.txt")
<|fim▁end|>
|
test_1
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|>from nose.tools import with_setup
import os
import hk_glazer as js2deg
import subprocess
import json
class TestClass:
@classmethod
def setup_class(cls):
cls.here = os.path.dirname(__file__)
cls.data = cls.here + '/data'
def test_1(self):
'''Test 1: Check that json_to_degree works when imported'''
with open(self.data + "/json_test_in.json") as config_file:
config_dict = json.load(config_file)
gen_str = js2deg.dict_to_dat(config_dict)
with open(self.data + "/json_test_out.txt") as verif_file:
test_str = verif_file.read()
assert(test_str == gen_str)
pass
def <|fim_middle|>(self):
'''Test 2: Check command line execution when saving to file'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
print(cmd)
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"])
with open("test2.txt") as file:
gen_str = file.read()
with open(self.data + "/json_test_out.txt") as file:
test_str = file.read()
assert(test_str == gen_str)
os.remove("test2.txt")
pass
def test_3(self):
'''Test 3: Command line execution when outfile already exists'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"])
try:
subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"])
except Exception as e:
#print(type(e))
assert(type(e) == subprocess.CalledProcessError)
pass
else:
assert(False)
finally:
os.remove("test3.txt")
<|fim▁end|>
|
test_2
|
<|file_name|>test.py<|end_file_name|><|fim▁begin|>from nose.tools import with_setup
import os
import hk_glazer as js2deg
import subprocess
import json
class TestClass:
@classmethod
def setup_class(cls):
cls.here = os.path.dirname(__file__)
cls.data = cls.here + '/data'
def test_1(self):
'''Test 1: Check that json_to_degree works when imported'''
with open(self.data + "/json_test_in.json") as config_file:
config_dict = json.load(config_file)
gen_str = js2deg.dict_to_dat(config_dict)
with open(self.data + "/json_test_out.txt") as verif_file:
test_str = verif_file.read()
assert(test_str == gen_str)
pass
def test_2(self):
'''Test 2: Check command line execution when saving to file'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
print(cmd)
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test2.txt", "-s"])
with open("test2.txt") as file:
gen_str = file.read()
with open(self.data + "/json_test_out.txt") as file:
test_str = file.read()
assert(test_str == gen_str)
os.remove("test2.txt")
pass
def <|fim_middle|>(self):
'''Test 3: Command line execution when outfile already exists'''
cmd = os.path.abspath(self.here + '/../../bin/hk_glazer')
subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"])
try:
subprocess.check_call([cmd,"js2degree", self.data + "/json_test_in.json", "-o=test3.txt"])
except Exception as e:
#print(type(e))
assert(type(e) == subprocess.CalledProcessError)
pass
else:
assert(False)
finally:
os.remove("test3.txt")
<|fim▁end|>
|
test_3
|
<|file_name|>lock.py<|end_file_name|><|fim▁begin|>from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-LockWorkStation',
'Author': ['@harmj0y'],
'Description': ("Locks the workstation's display."),
'Background' : False,
'OutputExtension' : None,
'NeedsAdmin' : False,
'OpsecSafe' : False,
'Language' : 'powershell',
'MinLanguageVersion' : '2',
'Comments': [
'http://poshcode.org/1640'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to run module on.',
'Required' : True,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu<|fim▁hole|>
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self):
script = """
Function Invoke-LockWorkStation {
# region define P/Invoke types dynamically
# stolen from PowerSploit https://github.com/mattifestation/PowerSploit/blob/master/Mayhem/Mayhem.psm1
# thanks matt and chris :)
$DynAssembly = New-Object System.Reflection.AssemblyName('Win32')
$AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('Win32', $False)
$TypeBuilder = $ModuleBuilder.DefineType('Win32.User32', 'Public, Class')
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$SetLastError = [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor,
@('User32.dll'),
[Reflection.FieldInfo[]]@($SetLastError),
@($True))
# Define [Win32.User32]::LockWorkStation()
$PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('LockWorkStation',
'User32.dll',
([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static),
[Reflection.CallingConventions]::Standard,
[Bool],
[Type[]]@(),
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Ansi)
$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
$User32 = $TypeBuilder.CreateType()
$Null = $User32::LockWorkStation()
}
Invoke-LockWorkStation; "Workstation locked."
"""
return script<|fim▁end|>
| |
<|file_name|>lock.py<|end_file_name|><|fim▁begin|>from lib.common import helpers
class Module:
<|fim_middle|>
<|fim▁end|>
|
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-LockWorkStation',
'Author': ['@harmj0y'],
'Description': ("Locks the workstation's display."),
'Background' : False,
'OutputExtension' : None,
'NeedsAdmin' : False,
'OpsecSafe' : False,
'Language' : 'powershell',
'MinLanguageVersion' : '2',
'Comments': [
'http://poshcode.org/1640'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to run module on.',
'Required' : True,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self):
script = """
Function Invoke-LockWorkStation {
# region define P/Invoke types dynamically
# stolen from PowerSploit https://github.com/mattifestation/PowerSploit/blob/master/Mayhem/Mayhem.psm1
# thanks matt and chris :)
$DynAssembly = New-Object System.Reflection.AssemblyName('Win32')
$AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('Win32', $False)
$TypeBuilder = $ModuleBuilder.DefineType('Win32.User32', 'Public, Class')
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$SetLastError = [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor,
@('User32.dll'),
[Reflection.FieldInfo[]]@($SetLastError),
@($True))
# Define [Win32.User32]::LockWorkStation()
$PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('LockWorkStation',
'User32.dll',
([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static),
[Reflection.CallingConventions]::Standard,
[Bool],
[Type[]]@(),
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Ansi)
$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
$User32 = $TypeBuilder.CreateType()
$Null = $User32::LockWorkStation()
}
Invoke-LockWorkStation; "Workstation locked."
"""
return script
|
<|file_name|>lock.py<|end_file_name|><|fim▁begin|>from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
<|fim_middle|>
def generate(self):
script = """
Function Invoke-LockWorkStation {
# region define P/Invoke types dynamically
# stolen from PowerSploit https://github.com/mattifestation/PowerSploit/blob/master/Mayhem/Mayhem.psm1
# thanks matt and chris :)
$DynAssembly = New-Object System.Reflection.AssemblyName('Win32')
$AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('Win32', $False)
$TypeBuilder = $ModuleBuilder.DefineType('Win32.User32', 'Public, Class')
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$SetLastError = [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor,
@('User32.dll'),
[Reflection.FieldInfo[]]@($SetLastError),
@($True))
# Define [Win32.User32]::LockWorkStation()
$PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('LockWorkStation',
'User32.dll',
([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static),
[Reflection.CallingConventions]::Standard,
[Bool],
[Type[]]@(),
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Ansi)
$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
$User32 = $TypeBuilder.CreateType()
$Null = $User32::LockWorkStation()
}
Invoke-LockWorkStation; "Workstation locked."
"""
return script
<|fim▁end|>
|
self.info = {
'Name': 'Invoke-LockWorkStation',
'Author': ['@harmj0y'],
'Description': ("Locks the workstation's display."),
'Background' : False,
'OutputExtension' : None,
'NeedsAdmin' : False,
'OpsecSafe' : False,
'Language' : 'powershell',
'MinLanguageVersion' : '2',
'Comments': [
'http://poshcode.org/1640'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to run module on.',
'Required' : True,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
|
<|file_name|>lock.py<|end_file_name|><|fim▁begin|>from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-LockWorkStation',
'Author': ['@harmj0y'],
'Description': ("Locks the workstation's display."),
'Background' : False,
'OutputExtension' : None,
'NeedsAdmin' : False,
'OpsecSafe' : False,
'Language' : 'powershell',
'MinLanguageVersion' : '2',
'Comments': [
'http://poshcode.org/1640'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to run module on.',
'Required' : True,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self):
<|fim_middle|>
<|fim▁end|>
|
script = """
Function Invoke-LockWorkStation {
# region define P/Invoke types dynamically
# stolen from PowerSploit https://github.com/mattifestation/PowerSploit/blob/master/Mayhem/Mayhem.psm1
# thanks matt and chris :)
$DynAssembly = New-Object System.Reflection.AssemblyName('Win32')
$AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('Win32', $False)
$TypeBuilder = $ModuleBuilder.DefineType('Win32.User32', 'Public, Class')
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$SetLastError = [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor,
@('User32.dll'),
[Reflection.FieldInfo[]]@($SetLastError),
@($True))
# Define [Win32.User32]::LockWorkStation()
$PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('LockWorkStation',
'User32.dll',
([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static),
[Reflection.CallingConventions]::Standard,
[Bool],
[Type[]]@(),
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Ansi)
$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
$User32 = $TypeBuilder.CreateType()
$Null = $User32::LockWorkStation()
}
Invoke-LockWorkStation; "Workstation locked."
"""
return script
|
<|file_name|>lock.py<|end_file_name|><|fim▁begin|>from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-LockWorkStation',
'Author': ['@harmj0y'],
'Description': ("Locks the workstation's display."),
'Background' : False,
'OutputExtension' : None,
'NeedsAdmin' : False,
'OpsecSafe' : False,
'Language' : 'powershell',
'MinLanguageVersion' : '2',
'Comments': [
'http://poshcode.org/1640'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to run module on.',
'Required' : True,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
<|fim_middle|>
def generate(self):
script = """
Function Invoke-LockWorkStation {
# region define P/Invoke types dynamically
# stolen from PowerSploit https://github.com/mattifestation/PowerSploit/blob/master/Mayhem/Mayhem.psm1
# thanks matt and chris :)
$DynAssembly = New-Object System.Reflection.AssemblyName('Win32')
$AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('Win32', $False)
$TypeBuilder = $ModuleBuilder.DefineType('Win32.User32', 'Public, Class')
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$SetLastError = [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor,
@('User32.dll'),
[Reflection.FieldInfo[]]@($SetLastError),
@($True))
# Define [Win32.User32]::LockWorkStation()
$PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('LockWorkStation',
'User32.dll',
([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static),
[Reflection.CallingConventions]::Standard,
[Bool],
[Type[]]@(),
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Ansi)
$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
$User32 = $TypeBuilder.CreateType()
$Null = $User32::LockWorkStation()
}
Invoke-LockWorkStation; "Workstation locked."
"""
return script
<|fim▁end|>
|
self.options[option]['Value'] = value
|
<|file_name|>lock.py<|end_file_name|><|fim▁begin|>from lib.common import helpers
class Module:
def <|fim_middle|>(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-LockWorkStation',
'Author': ['@harmj0y'],
'Description': ("Locks the workstation's display."),
'Background' : False,
'OutputExtension' : None,
'NeedsAdmin' : False,
'OpsecSafe' : False,
'Language' : 'powershell',
'MinLanguageVersion' : '2',
'Comments': [
'http://poshcode.org/1640'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to run module on.',
'Required' : True,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self):
script = """
Function Invoke-LockWorkStation {
# region define P/Invoke types dynamically
# stolen from PowerSploit https://github.com/mattifestation/PowerSploit/blob/master/Mayhem/Mayhem.psm1
# thanks matt and chris :)
$DynAssembly = New-Object System.Reflection.AssemblyName('Win32')
$AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('Win32', $False)
$TypeBuilder = $ModuleBuilder.DefineType('Win32.User32', 'Public, Class')
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$SetLastError = [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor,
@('User32.dll'),
[Reflection.FieldInfo[]]@($SetLastError),
@($True))
# Define [Win32.User32]::LockWorkStation()
$PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('LockWorkStation',
'User32.dll',
([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static),
[Reflection.CallingConventions]::Standard,
[Bool],
[Type[]]@(),
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Ansi)
$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
$User32 = $TypeBuilder.CreateType()
$Null = $User32::LockWorkStation()
}
Invoke-LockWorkStation; "Workstation locked."
"""
return script
<|fim▁end|>
|
__init__
|
<|file_name|>lock.py<|end_file_name|><|fim▁begin|>from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-LockWorkStation',
'Author': ['@harmj0y'],
'Description': ("Locks the workstation's display."),
'Background' : False,
'OutputExtension' : None,
'NeedsAdmin' : False,
'OpsecSafe' : False,
'Language' : 'powershell',
'MinLanguageVersion' : '2',
'Comments': [
'http://poshcode.org/1640'
]
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
'Description' : 'Agent to run module on.',
'Required' : True,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def <|fim_middle|>(self):
script = """
Function Invoke-LockWorkStation {
# region define P/Invoke types dynamically
# stolen from PowerSploit https://github.com/mattifestation/PowerSploit/blob/master/Mayhem/Mayhem.psm1
# thanks matt and chris :)
$DynAssembly = New-Object System.Reflection.AssemblyName('Win32')
$AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('Win32', $False)
$TypeBuilder = $ModuleBuilder.DefineType('Win32.User32', 'Public, Class')
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$SetLastError = [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
$SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor,
@('User32.dll'),
[Reflection.FieldInfo[]]@($SetLastError),
@($True))
# Define [Win32.User32]::LockWorkStation()
$PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('LockWorkStation',
'User32.dll',
([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static),
[Reflection.CallingConventions]::Standard,
[Bool],
[Type[]]@(),
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Ansi)
$PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
$User32 = $TypeBuilder.CreateType()
$Null = $User32::LockWorkStation()
}
Invoke-LockWorkStation; "Workstation locked."
"""
return script
<|fim▁end|>
|
generate
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
<|fim▁hole|>
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)<|fim▁end|>
|
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
<|fim_middle|>
<|fim▁end|>
|
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
<|fim_middle|>
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
<|fim_middle|>
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
<|fim_middle|>
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
<|fim_middle|>
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
<|fim_middle|>
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
<|fim_middle|>
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
<|fim_middle|>
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
<|fim_middle|>
<|fim▁end|>
|
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
<|fim_middle|>
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
start_directory = start
return self._discover_by_directory(start_directory)
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
<|fim_middle|>
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
start_filepath = start
return self._discover_by_file(start_filepath)
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
<|fim_middle|>
yield self._load_from_file(filepath)
<|fim▁end|>
|
logger.debug('Skipping %r', filepath)
continue
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def <|fim_middle|>(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
__init__
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def <|fim_middle|>(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
from_args
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def <|fim_middle|>(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
add_parser_arguments
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def <|fim_middle|>(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
discover
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def <|fim_middle|>(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
_discover_by_directory
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def <|fim_middle|>(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
_discover_by_file
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def <|fim_middle|>(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def _discover_tests(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
_load_from_file
|
<|file_name|>discoverer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe and Enthought Ltd.
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
import logging
import os
from haas.plugins.discoverer import match_path
from haas.plugins.i_discoverer_plugin import IDiscovererPlugin
from .yaml_test_loader import YamlTestLoader
logger = logging.getLogger(__name__)
class RestTestDiscoverer(IDiscovererPlugin):
"""A ``haas`` test discovery plugin to generate Web API test cases from
YAML descriptions.
Parameters
----------
loader : haas.loader.Loader
The ``haas`` test loader.
"""
def __init__(self, loader, **kwargs):
super(RestTestDiscoverer, self).__init__(**kwargs)
self._loader = loader
self._yaml_loader = YamlTestLoader(loader)
@classmethod
def from_args(cls, args, arg_prefix, loader):
"""Construct the discoverer from parsed command line arguments.
Parameters
----------
args : argparse.Namespace
The ``argparse.Namespace`` containing parsed arguments.
arg_prefix : str
The prefix used for arguments beloning solely to this plugin.
loader : haas.loader.Loader
The test loader used to construct TestCase and TestSuite instances.
"""
return cls(loader)
@classmethod
def add_parser_arguments(cls, parser, option_prefix, dest_prefix):
"""Add options for the plugin to the main argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The parser to extend
option_prefix : str
The prefix that option strings added by this plugin should use.
dest_prefix : str
The prefix that ``dest`` strings for options added by this
plugin should use.
"""
def discover(self, start, top_level_directory=None, pattern=None):
"""Discover YAML-formatted Web API tests.
Parameters
----------
start : str
Directory from which to recursively discover test cases.
top_level_directory : None
Ignored; for API compatibility with haas.
pattern : None
Ignored; for API compatibility with haas.
"""
if os.path.isdir(start):
start_directory = start
return self._discover_by_directory(start_directory)
elif os.path.isfile(start):
start_filepath = start
return self._discover_by_file(start_filepath)
return self._loader.create_suite()
def _discover_by_directory(self, start_directory):
"""Run test discovery in a directory.
Parameters
----------
start_directory : str
The package directory in which to start test discovery.
"""
start_directory = os.path.abspath(start_directory)
tests = self._discover_tests(start_directory)
return self._loader.create_suite(list(tests))
def _discover_by_file(self, start_filepath):
"""Run test discovery on a single file.
Parameters
----------
start_filepath : str
The module file in which to start test discovery.
"""
start_filepath = os.path.abspath(start_filepath)
logger.debug('Discovering tests in file: start_filepath=%r',
start_filepath)
tests = self._load_from_file(start_filepath)
return self._loader.create_suite(list(tests))
def _load_from_file(self, filepath):
logger.debug('Loading tests from %r', filepath)
tests = self._yaml_loader.load_tests_from_file(filepath)
return self._loader.create_suite(tests)
def <|fim_middle|>(self, start_directory):
pattern = 'test*.yml'
for curdir, dirnames, filenames in os.walk(start_directory):
logger.debug('Discovering tests in %r', curdir)
for filename in filenames:
filepath = os.path.join(curdir, filename)
if not match_path(filename, filepath, pattern):
logger.debug('Skipping %r', filepath)
continue
yield self._load_from_file(filepath)
<|fim▁end|>
|
_discover_tests
|
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP
from binascii import hexlify, unhexlify
import cStringIO
import time
def cltv_invalidate(tx):
'''Modify the signature in vin 0 of the tx to fail CLTV
Prepends -1 CLTV DROP in the scriptSig itself.
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
'''
This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY)
Connect to a single node.
Mine 2 (version 3) blocks (save the coinbases for later).
Generate 98 more version 3 blocks, verify the node accepts.
Mine 749 version 4 blocks, verify the node accepts.
Check that the new CLTV rules are not enforced on the 750th version 4 block.
Check that the new CLTV rules are enforced on the 751st version 4 block.
Mine 199 new version blocks.
Mine 1 old-version block.
Mine 1 new version block.
Mine 1 old version block, see that the node rejects.
'''
class BIP65Test(ComparisonTestFramework):
def __init__(self):
self.num_nodes = 1
def setup_network(self):
# Must set the blockversion for this test
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']],
binary=[self.options.testbinary])
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
def create_transaction(self, node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = cStringIO.StringIO(unhexlify(signresult['hex']))
tx.deserialize(f)
return tx
def get_tests(self):
self.coinbase_blocks = self.nodes[0].setgenerate(True, 2)
self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = time.time()
''' 98 more version 3 blocks '''
test_blocks = []
for i in xrange(98):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 749 version 4 blocks '''
test_blocks = []
for i in xrange(749):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
'''
Check that the new CLTV rules are not enforced in the 750th
version 3 block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
'''
Check that the new CLTV rules are enforced in the 751st version 4
block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
''' Mine 199 new version blocks on last valid tip '''
test_blocks = []
for i in xrange(199):
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 1 old version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1<|fim▁hole|> ''' Mine 1 new version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 old version block, should be invalid '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
if __name__ == '__main__':
BIP65Test().main()<|fim▁end|>
|
self.tip = block.sha256
yield TestInstance([[block, True]])
|
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP
from binascii import hexlify, unhexlify
import cStringIO
import time
def cltv_invalidate(tx):
<|fim_middle|>
'''
This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY)
Connect to a single node.
Mine 2 (version 3) blocks (save the coinbases for later).
Generate 98 more version 3 blocks, verify the node accepts.
Mine 749 version 4 blocks, verify the node accepts.
Check that the new CLTV rules are not enforced on the 750th version 4 block.
Check that the new CLTV rules are enforced on the 751st version 4 block.
Mine 199 new version blocks.
Mine 1 old-version block.
Mine 1 new version block.
Mine 1 old version block, see that the node rejects.
'''
class BIP65Test(ComparisonTestFramework):
def __init__(self):
self.num_nodes = 1
def setup_network(self):
# Must set the blockversion for this test
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']],
binary=[self.options.testbinary])
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
def create_transaction(self, node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = cStringIO.StringIO(unhexlify(signresult['hex']))
tx.deserialize(f)
return tx
def get_tests(self):
self.coinbase_blocks = self.nodes[0].setgenerate(True, 2)
self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = time.time()
''' 98 more version 3 blocks '''
test_blocks = []
for i in xrange(98):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 749 version 4 blocks '''
test_blocks = []
for i in xrange(749):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
'''
Check that the new CLTV rules are not enforced in the 750th
version 3 block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
'''
Check that the new CLTV rules are enforced in the 751st version 4
block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
''' Mine 199 new version blocks on last valid tip '''
test_blocks = []
for i in xrange(199):
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 1 old version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 new version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 old version block, should be invalid '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
if __name__ == '__main__':
BIP65Test().main()
<|fim▁end|>
|
'''Modify the signature in vin 0 of the tx to fail CLTV
Prepends -1 CLTV DROP in the scriptSig itself.
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
|
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP
from binascii import hexlify, unhexlify
import cStringIO
import time
def cltv_invalidate(tx):
'''Modify the signature in vin 0 of the tx to fail CLTV
Prepends -1 CLTV DROP in the scriptSig itself.
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
'''
This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY)
Connect to a single node.
Mine 2 (version 3) blocks (save the coinbases for later).
Generate 98 more version 3 blocks, verify the node accepts.
Mine 749 version 4 blocks, verify the node accepts.
Check that the new CLTV rules are not enforced on the 750th version 4 block.
Check that the new CLTV rules are enforced on the 751st version 4 block.
Mine 199 new version blocks.
Mine 1 old-version block.
Mine 1 new version block.
Mine 1 old version block, see that the node rejects.
'''
class BIP65Test(ComparisonTestFramework):
<|fim_middle|>
if __name__ == '__main__':
BIP65Test().main()
<|fim▁end|>
|
def __init__(self):
self.num_nodes = 1
def setup_network(self):
# Must set the blockversion for this test
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']],
binary=[self.options.testbinary])
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
def create_transaction(self, node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = cStringIO.StringIO(unhexlify(signresult['hex']))
tx.deserialize(f)
return tx
def get_tests(self):
self.coinbase_blocks = self.nodes[0].setgenerate(True, 2)
self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = time.time()
''' 98 more version 3 blocks '''
test_blocks = []
for i in xrange(98):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 749 version 4 blocks '''
test_blocks = []
for i in xrange(749):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
'''
Check that the new CLTV rules are not enforced in the 750th
version 3 block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
'''
Check that the new CLTV rules are enforced in the 751st version 4
block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
''' Mine 199 new version blocks on last valid tip '''
test_blocks = []
for i in xrange(199):
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 1 old version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 new version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 old version block, should be invalid '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
|
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP
from binascii import hexlify, unhexlify
import cStringIO
import time
def cltv_invalidate(tx):
'''Modify the signature in vin 0 of the tx to fail CLTV
Prepends -1 CLTV DROP in the scriptSig itself.
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
'''
This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY)
Connect to a single node.
Mine 2 (version 3) blocks (save the coinbases for later).
Generate 98 more version 3 blocks, verify the node accepts.
Mine 749 version 4 blocks, verify the node accepts.
Check that the new CLTV rules are not enforced on the 750th version 4 block.
Check that the new CLTV rules are enforced on the 751st version 4 block.
Mine 199 new version blocks.
Mine 1 old-version block.
Mine 1 new version block.
Mine 1 old version block, see that the node rejects.
'''
class BIP65Test(ComparisonTestFramework):
def __init__(self):
<|fim_middle|>
def setup_network(self):
# Must set the blockversion for this test
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']],
binary=[self.options.testbinary])
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
def create_transaction(self, node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = cStringIO.StringIO(unhexlify(signresult['hex']))
tx.deserialize(f)
return tx
def get_tests(self):
self.coinbase_blocks = self.nodes[0].setgenerate(True, 2)
self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = time.time()
''' 98 more version 3 blocks '''
test_blocks = []
for i in xrange(98):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 749 version 4 blocks '''
test_blocks = []
for i in xrange(749):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
'''
Check that the new CLTV rules are not enforced in the 750th
version 3 block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
'''
Check that the new CLTV rules are enforced in the 751st version 4
block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
''' Mine 199 new version blocks on last valid tip '''
test_blocks = []
for i in xrange(199):
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 1 old version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 new version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 old version block, should be invalid '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
if __name__ == '__main__':
BIP65Test().main()
<|fim▁end|>
|
self.num_nodes = 1
|
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP
from binascii import hexlify, unhexlify
import cStringIO
import time
def cltv_invalidate(tx):
'''Modify the signature in vin 0 of the tx to fail CLTV
Prepends -1 CLTV DROP in the scriptSig itself.
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
'''
This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY)
Connect to a single node.
Mine 2 (version 3) blocks (save the coinbases for later).
Generate 98 more version 3 blocks, verify the node accepts.
Mine 749 version 4 blocks, verify the node accepts.
Check that the new CLTV rules are not enforced on the 750th version 4 block.
Check that the new CLTV rules are enforced on the 751st version 4 block.
Mine 199 new version blocks.
Mine 1 old-version block.
Mine 1 new version block.
Mine 1 old version block, see that the node rejects.
'''
class BIP65Test(ComparisonTestFramework):
def __init__(self):
self.num_nodes = 1
def setup_network(self):
# Must set the blockversion for this test
<|fim_middle|>
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
def create_transaction(self, node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = cStringIO.StringIO(unhexlify(signresult['hex']))
tx.deserialize(f)
return tx
def get_tests(self):
self.coinbase_blocks = self.nodes[0].setgenerate(True, 2)
self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = time.time()
''' 98 more version 3 blocks '''
test_blocks = []
for i in xrange(98):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 749 version 4 blocks '''
test_blocks = []
for i in xrange(749):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
'''
Check that the new CLTV rules are not enforced in the 750th
version 3 block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
'''
Check that the new CLTV rules are enforced in the 751st version 4
block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
''' Mine 199 new version blocks on last valid tip '''
test_blocks = []
for i in xrange(199):
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 1 old version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 new version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 old version block, should be invalid '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
if __name__ == '__main__':
BIP65Test().main()
<|fim▁end|>
|
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']],
binary=[self.options.testbinary])
|
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP
from binascii import hexlify, unhexlify
import cStringIO
import time
def cltv_invalidate(tx):
'''Modify the signature in vin 0 of the tx to fail CLTV
Prepends -1 CLTV DROP in the scriptSig itself.
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
'''
This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY)
Connect to a single node.
Mine 2 (version 3) blocks (save the coinbases for later).
Generate 98 more version 3 blocks, verify the node accepts.
Mine 749 version 4 blocks, verify the node accepts.
Check that the new CLTV rules are not enforced on the 750th version 4 block.
Check that the new CLTV rules are enforced on the 751st version 4 block.
Mine 199 new version blocks.
Mine 1 old-version block.
Mine 1 new version block.
Mine 1 old version block, see that the node rejects.
'''
class BIP65Test(ComparisonTestFramework):
def __init__(self):
self.num_nodes = 1
def setup_network(self):
# Must set the blockversion for this test
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']],
binary=[self.options.testbinary])
def run_test(self):
<|fim_middle|>
def create_transaction(self, node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = cStringIO.StringIO(unhexlify(signresult['hex']))
tx.deserialize(f)
return tx
def get_tests(self):
self.coinbase_blocks = self.nodes[0].setgenerate(True, 2)
self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = time.time()
''' 98 more version 3 blocks '''
test_blocks = []
for i in xrange(98):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 749 version 4 blocks '''
test_blocks = []
for i in xrange(749):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
'''
Check that the new CLTV rules are not enforced in the 750th
version 3 block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
'''
Check that the new CLTV rules are enforced in the 751st version 4
block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
''' Mine 199 new version blocks on last valid tip '''
test_blocks = []
for i in xrange(199):
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 1 old version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 new version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 old version block, should be invalid '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
if __name__ == '__main__':
BIP65Test().main()
<|fim▁end|>
|
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
|
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP
from binascii import hexlify, unhexlify
import cStringIO
import time
def cltv_invalidate(tx):
'''Modify the signature in vin 0 of the tx to fail CLTV
Prepends -1 CLTV DROP in the scriptSig itself.
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
'''
This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY)
Connect to a single node.
Mine 2 (version 3) blocks (save the coinbases for later).
Generate 98 more version 3 blocks, verify the node accepts.
Mine 749 version 4 blocks, verify the node accepts.
Check that the new CLTV rules are not enforced on the 750th version 4 block.
Check that the new CLTV rules are enforced on the 751st version 4 block.
Mine 199 new version blocks.
Mine 1 old-version block.
Mine 1 new version block.
Mine 1 old version block, see that the node rejects.
'''
class BIP65Test(ComparisonTestFramework):
def __init__(self):
self.num_nodes = 1
def setup_network(self):
# Must set the blockversion for this test
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']],
binary=[self.options.testbinary])
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
def create_transaction(self, node, coinbase, to_address, amount):
<|fim_middle|>
def get_tests(self):
self.coinbase_blocks = self.nodes[0].setgenerate(True, 2)
self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = time.time()
''' 98 more version 3 blocks '''
test_blocks = []
for i in xrange(98):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 749 version 4 blocks '''
test_blocks = []
for i in xrange(749):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
'''
Check that the new CLTV rules are not enforced in the 750th
version 3 block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
'''
Check that the new CLTV rules are enforced in the 751st version 4
block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
''' Mine 199 new version blocks on last valid tip '''
test_blocks = []
for i in xrange(199):
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 1 old version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 new version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 old version block, should be invalid '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
if __name__ == '__main__':
BIP65Test().main()
<|fim▁end|>
|
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = cStringIO.StringIO(unhexlify(signresult['hex']))
tx.deserialize(f)
return tx
|
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP
from binascii import hexlify, unhexlify
import cStringIO
import time
def cltv_invalidate(tx):
'''Modify the signature in vin 0 of the tx to fail CLTV
Prepends -1 CLTV DROP in the scriptSig itself.
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
'''
This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY)
Connect to a single node.
Mine 2 (version 3) blocks (save the coinbases for later).
Generate 98 more version 3 blocks, verify the node accepts.
Mine 749 version 4 blocks, verify the node accepts.
Check that the new CLTV rules are not enforced on the 750th version 4 block.
Check that the new CLTV rules are enforced on the 751st version 4 block.
Mine 199 new version blocks.
Mine 1 old-version block.
Mine 1 new version block.
Mine 1 old version block, see that the node rejects.
'''
class BIP65Test(ComparisonTestFramework):
def __init__(self):
self.num_nodes = 1
def setup_network(self):
# Must set the blockversion for this test
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']],
binary=[self.options.testbinary])
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
def create_transaction(self, node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = cStringIO.StringIO(unhexlify(signresult['hex']))
tx.deserialize(f)
return tx
def get_tests(self):
<|fim_middle|>
if __name__ == '__main__':
BIP65Test().main()
<|fim▁end|>
|
self.coinbase_blocks = self.nodes[0].setgenerate(True, 2)
self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = time.time()
''' 98 more version 3 blocks '''
test_blocks = []
for i in xrange(98):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 749 version 4 blocks '''
test_blocks = []
for i in xrange(749):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
'''
Check that the new CLTV rules are not enforced in the 750th
version 3 block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
'''
Check that the new CLTV rules are enforced in the 751st version 4
block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
''' Mine 199 new version blocks on last valid tip '''
test_blocks = []
for i in xrange(199):
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 1 old version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 new version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 old version block, should be invalid '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
|
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP
from binascii import hexlify, unhexlify
import cStringIO
import time
def cltv_invalidate(tx):
'''Modify the signature in vin 0 of the tx to fail CLTV
Prepends -1 CLTV DROP in the scriptSig itself.
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
'''
This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY)
Connect to a single node.
Mine 2 (version 3) blocks (save the coinbases for later).
Generate 98 more version 3 blocks, verify the node accepts.
Mine 749 version 4 blocks, verify the node accepts.
Check that the new CLTV rules are not enforced on the 750th version 4 block.
Check that the new CLTV rules are enforced on the 751st version 4 block.
Mine 199 new version blocks.
Mine 1 old-version block.
Mine 1 new version block.
Mine 1 old version block, see that the node rejects.
'''
class BIP65Test(ComparisonTestFramework):
def __init__(self):
self.num_nodes = 1
def setup_network(self):
# Must set the blockversion for this test
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']],
binary=[self.options.testbinary])
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
def create_transaction(self, node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = cStringIO.StringIO(unhexlify(signresult['hex']))
tx.deserialize(f)
return tx
def get_tests(self):
self.coinbase_blocks = self.nodes[0].setgenerate(True, 2)
self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = time.time()
''' 98 more version 3 blocks '''
test_blocks = []
for i in xrange(98):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 749 version 4 blocks '''
test_blocks = []
for i in xrange(749):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
'''
Check that the new CLTV rules are not enforced in the 750th
version 3 block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
'''
Check that the new CLTV rules are enforced in the 751st version 4
block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
''' Mine 199 new version blocks on last valid tip '''
test_blocks = []
for i in xrange(199):
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 1 old version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 new version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 old version block, should be invalid '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|>
|
BIP65Test().main()
|
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP
from binascii import hexlify, unhexlify
import cStringIO
import time
def <|fim_middle|>(tx):
'''Modify the signature in vin 0 of the tx to fail CLTV
Prepends -1 CLTV DROP in the scriptSig itself.
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
'''
This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY)
Connect to a single node.
Mine 2 (version 3) blocks (save the coinbases for later).
Generate 98 more version 3 blocks, verify the node accepts.
Mine 749 version 4 blocks, verify the node accepts.
Check that the new CLTV rules are not enforced on the 750th version 4 block.
Check that the new CLTV rules are enforced on the 751st version 4 block.
Mine 199 new version blocks.
Mine 1 old-version block.
Mine 1 new version block.
Mine 1 old version block, see that the node rejects.
'''
class BIP65Test(ComparisonTestFramework):
def __init__(self):
self.num_nodes = 1
def setup_network(self):
# Must set the blockversion for this test
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']],
binary=[self.options.testbinary])
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
def create_transaction(self, node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = cStringIO.StringIO(unhexlify(signresult['hex']))
tx.deserialize(f)
return tx
def get_tests(self):
self.coinbase_blocks = self.nodes[0].setgenerate(True, 2)
self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = time.time()
''' 98 more version 3 blocks '''
test_blocks = []
for i in xrange(98):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 749 version 4 blocks '''
test_blocks = []
for i in xrange(749):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
'''
Check that the new CLTV rules are not enforced in the 750th
version 3 block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
'''
Check that the new CLTV rules are enforced in the 751st version 4
block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
''' Mine 199 new version blocks on last valid tip '''
test_blocks = []
for i in xrange(199):
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 1 old version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 new version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 old version block, should be invalid '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
if __name__ == '__main__':
BIP65Test().main()
<|fim▁end|>
|
cltv_invalidate
|
<|file_name|>bip65-cltv-p2p.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_NOP2, OP_DROP
from binascii import hexlify, unhexlify
import cStringIO
import time
def cltv_invalidate(tx):
'''Modify the signature in vin 0 of the tx to fail CLTV
Prepends -1 CLTV DROP in the scriptSig itself.
'''
tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_NOP2, OP_DROP] +
list(CScript(tx.vin[0].scriptSig)))
'''
This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY)
Connect to a single node.
Mine 2 (version 3) blocks (save the coinbases for later).
Generate 98 more version 3 blocks, verify the node accepts.
Mine 749 version 4 blocks, verify the node accepts.
Check that the new CLTV rules are not enforced on the 750th version 4 block.
Check that the new CLTV rules are enforced on the 751st version 4 block.
Mine 199 new version blocks.
Mine 1 old-version block.
Mine 1 new version block.
Mine 1 old version block, see that the node rejects.
'''
class BIP65Test(ComparisonTestFramework):
def <|fim_middle|>(self):
self.num_nodes = 1
def setup_network(self):
# Must set the blockversion for this test
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=3']],
binary=[self.options.testbinary])
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
def create_transaction(self, node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = cStringIO.StringIO(unhexlify(signresult['hex']))
tx.deserialize(f)
return tx
def get_tests(self):
self.coinbase_blocks = self.nodes[0].setgenerate(True, 2)
self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = time.time()
''' 98 more version 3 blocks '''
test_blocks = []
for i in xrange(98):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 749 version 4 blocks '''
test_blocks = []
for i in xrange(749):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
'''
Check that the new CLTV rules are not enforced in the 750th
version 3 block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
'''
Check that the new CLTV rules are enforced in the 751st version 4
block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
cltv_invalidate(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
''' Mine 199 new version blocks on last valid tip '''
test_blocks = []
for i in xrange(199):
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 1 old version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 new version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 4
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 old version block, should be invalid '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
if __name__ == '__main__':
BIP65Test().main()
<|fim▁end|>
|
__init__
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.