Dataset Viewer
repo_name
stringlengths 7
65
| path
stringlengths 5
189
| copies
stringclasses 681
values | size
stringlengths 4
7
| content
stringlengths 697
1.02M
| license
stringclasses 14
values |
---|---|---|---|---|---|
mozilla/normandy | normandy/recipes/tests/api/v3/test_shield_identicon.py | 1 | 1396 | import pytest
from normandy.recipes.api.v3.shield_identicon import Genome
@pytest.fixture
def genome():
seed = 123
return Genome(seed)
class TestGenome(object):
"""
Tests the Genome module by setting the seed to a known value and making sure that the
random choices remain consistent, ie. they do not change over time.
"""
def test_weighted_choice(self, genome):
weighted_options = [
{"weight": 1, "value": "apple"},
{"weight": 2, "value": "orange"},
{"weight": 4, "value": "strawberry"},
]
weighted_choice_values = [
genome.weighted_choice(weighted_options),
genome.weighted_choice(weighted_options),
genome.weighted_choice(weighted_options),
]
assert weighted_choice_values == [
{"weight": 1, "value": "apple"},
{"weight": 2, "value": "orange"},
{"weight": 1, "value": "apple"},
]
def test_emoji(self, genome):
emoji_values = [genome.emoji(), genome.emoji(), genome.emoji()]
assert emoji_values == ["😅", "🐯", "😈"]
def test_color(self, genome):
color_values = [
genome.color().rgb_color,
genome.color().rgb_color,
genome.color().rgb_color,
]
assert color_values == [(7, 54, 66), (255, 207, 0), (88, 110, 117)]
| mpl-2.0 |
mozilla/normandy | normandy/recipes/tests/api/v3/test_api.py | 1 | 84448 | from datetime import timedelta, datetime
from django.conf import settings
from django.db import connection
from django.test.utils import CaptureQueriesContext
import pytest
from rest_framework import serializers
from rest_framework.reverse import reverse
from pathlib import Path
from normandy.base.api.permissions import AdminEnabledOrReadOnly
from normandy.base.tests import UserFactory, Whatever
from normandy.base.utils import canonical_json_dumps
from normandy.recipes.models import ApprovalRequest, Recipe, RecipeRevision
from normandy.recipes import filters as filter_objects
from normandy.recipes.tests import (
ActionFactory,
ApprovalRequestFactory,
ChannelFactory,
CountryFactory,
LocaleFactory,
RecipeFactory,
RecipeRevisionFactory,
fake_sign,
)
@pytest.mark.django_db
class TestActionAPI(object):
def test_it_works(self, api_client):
res = api_client.get("/api/v3/action/")
assert res.status_code == 200
assert res.data == {"count": 0, "next": None, "previous": None, "results": []}
def test_it_serves_actions(self, api_client):
action = ActionFactory(
name="foo", implementation="foobar", arguments_schema={"type": "object"}
)
res = api_client.get("/api/v3/action/")
action_url = reverse(
"recipes:v1:action-implementation",
kwargs={"name": action.name, "impl_hash": action.implementation_hash},
)
assert res.status_code == 200
assert res.data == {
"count": 1,
"next": None,
"previous": None,
"results": [
{
"id": action.id,
"name": "foo",
"implementation_url": Whatever.endswith(action_url),
"arguments_schema": {"type": "object"},
}
],
}
def test_it_serves_actions_without_implementation(self, api_client):
action = ActionFactory(
name="foo-remote", implementation=None, arguments_schema={"type": "object"}
)
res = api_client.get("/api/v3/action/")
assert res.status_code == 200
assert res.data["results"] == [
{
"id": action.id,
"name": "foo-remote",
"implementation_url": None,
"arguments_schema": {"type": "object"},
}
]
def test_list_view_includes_cache_headers(self, api_client):
res = api_client.get("/api/v3/action/")
assert res.status_code == 200
# It isn't important to assert a particular value for max-age
assert "max-age=" in res["Cache-Control"]
assert "public" in res["Cache-Control"]
def test_detail_view_includes_cache_headers(self, api_client):
action = ActionFactory()
res = api_client.get("/api/v3/action/{id}/".format(id=action.id))
assert res.status_code == 200
# It isn't important to assert a particular value for max-age
assert "max-age=" in res["Cache-Control"]
assert "public" in res["Cache-Control"]
def test_list_sets_no_cookies(self, api_client):
res = api_client.get("/api/v3/action/")
assert res.status_code == 200
assert "Cookies" not in res
def test_detail_sets_no_cookies(self, api_client):
action = ActionFactory()
res = api_client.get("/api/v3/action/{id}/".format(id=action.id))
assert res.status_code == 200
assert res.client.cookies == {}
@pytest.mark.django_db
class TestRecipeAPI(object):
@pytest.mark.django_db
class TestListing(object):
def test_it_works(self, api_client):
res = api_client.get("/api/v3/recipe/")
assert res.status_code == 200
assert res.data["results"] == []
def test_it_serves_recipes(self, api_client):
recipe = RecipeFactory()
res = api_client.get("/api/v3/recipe/")
assert res.status_code == 200
assert res.data["results"][0]["latest_revision"]["name"] == recipe.latest_revision.name
def test_available_if_admin_enabled(self, api_client, settings):
settings.ADMIN_ENABLED = True
res = api_client.get("/api/v3/recipe/")
assert res.status_code == 200
assert res.data["results"] == []
def test_readonly_if_admin_disabled(self, api_client, settings):
settings.ADMIN_ENABLED = False
res = api_client.get("/api/v3/recipe/")
assert res.status_code == 200
recipe = RecipeFactory(name="unchanged")
res = api_client.patch("/api/v3/recipe/%s/" % recipe.id, {"name": "changed"})
assert res.status_code == 403
assert res.data["detail"] == AdminEnabledOrReadOnly.message
def test_list_view_includes_cache_headers(self, api_client):
res = api_client.get("/api/v3/recipe/")
assert res.status_code == 200
# It isn't important to assert a particular value for max_age
assert "max-age=" in res["Cache-Control"]
assert "public" in res["Cache-Control"]
def test_list_sets_no_cookies(self, api_client):
res = api_client.get("/api/v3/recipe/")
assert res.status_code == 200
assert "Cookies" not in res
def test_list_can_filter_baseline_recipes(
self, rs_settings, api_client, mocked_remotesettings
):
recipe1 = RecipeFactory(
extra_capabilities=[], approver=UserFactory(), enabler=UserFactory()
)
rs_settings.BASELINE_CAPABILITIES |= recipe1.latest_revision.capabilities
assert recipe1.latest_revision.uses_only_baseline_capabilities()
recipe2 = RecipeFactory(
extra_capabilities=["test-capability"],
approver=UserFactory(),
enabler=UserFactory(),
)
assert not recipe2.latest_revision.uses_only_baseline_capabilities()
# Only approved recipes are considered as part of uses_only_baseline_capabilities
recipe3 = RecipeFactory(extra_capabilities=[])
rs_settings.BASELINE_CAPABILITIES |= recipe3.latest_revision.capabilities
assert recipe3.latest_revision.uses_only_baseline_capabilities()
res = api_client.get("/api/v3/recipe/")
assert res.status_code == 200
assert res.data["count"] == 3
res = api_client.get("/api/v3/recipe/?uses_only_baseline_capabilities=true")
assert res.status_code == 200
assert res.data["count"] == 1
assert res.data["results"][0]["id"] == recipe1.id
def test_list_can_filter_by_filter_object_fields(self, api_client):
locale = LocaleFactory()
recipe1 = RecipeFactory(
filter_object=[
filter_objects.BucketSampleFilter.create(
start=100,
count=200,
total=10_000,
input=["normandy.userId", '"global-v4'],
),
filter_objects.LocaleFilter.create(locales=[locale.code]),
]
)
recipe2 = RecipeFactory(
filter_object=[
filter_objects.PresetFilter.create(name="pocket-1"),
filter_objects.LocaleFilter.create(locales=[locale.code]),
]
)
# All recipes are visible
res = api_client.get("/api/v3/recipe/")
assert res.status_code == 200
assert {r["id"] for r in res.data["results"]} == {recipe1.id, recipe2.id}
# Filters can find simple-strings
res = api_client.get("/api/v3/recipe/?filter_object=name:pocket")
assert res.status_code == 200
assert {r["id"] for r in res.data["results"]} == {recipe2.id}
# Filters can find partial values in lists
res = api_client.get("/api/v3/recipe/?filter_object=input:global-v4")
assert res.status_code == 200
assert {r["id"] for r in res.data["results"]} == {recipe1.id}
# Filters can find multiple results
res = api_client.get(f"/api/v3/recipe/?filter_object=locales:{locale.code}")
assert res.status_code == 200
assert {r["id"] for r in res.data["results"]} == {recipe1.id, recipe2.id}
# Filters can find nothing
res = api_client.get("/api/v3/recipe/?filter_object=doesnt:exist")
assert res.status_code == 200
assert res.data["count"] == 0
def test_list_invalid_filter_by_filter_object(self, api_client):
# The filter is supposed to be of the form
# `key1:val1,key2:val2,...`. What if we don't follow that format?
res = api_client.get("/api/v3/recipe/?filter_object=nocolon")
assert res.status_code == 400
assert res.data == {
"filter_object": "Filters must be of the format `key1:val1,key2:val2,..."
}
def test_list_can_filter_by_filter_object_type(self, api_client):
locale = LocaleFactory()
recipe1 = RecipeFactory(
filter_object=[
filter_objects.BucketSampleFilter.create(
start=100,
count=200,
total=10_000,
input=["normandy.userId", '"global-v4"'],
),
filter_objects.LocaleFilter.create(locales=[locale.code]),
]
)
recipe2 = RecipeFactory(
filter_object=[
filter_objects.PresetFilter.create(name="pocket-1"),
filter_objects.LocaleFilter.create(locales=[locale.code]),
]
)
# All recipes are visible
res = api_client.get("/api/v3/recipe/")
assert res.status_code == 200
assert {r["id"] for r in res.data["results"]} == {recipe1.id, recipe2.id}
# Filters can find types that exist on both
res = api_client.get("/api/v3/recipe/?filter_object=type:locale")
assert res.status_code == 200
assert {r["id"] for r in res.data["results"]} == {recipe1.id, recipe2.id}
# Filters can find a type that exists on just one
res = api_client.get("/api/v3/recipe/?filter_object=type:bucket")
assert res.status_code == 200
assert {r["id"] for r in res.data["results"]} == {recipe1.id}
# Filters can find nothing
res = api_client.get("/api/v3/recipe/?filter_object=type:unused")
assert res.status_code == 200
assert res.data["count"] == 0
@pytest.mark.django_db
class TestCreation(object):
def test_it_can_create_recipes(self, api_client):
action = ActionFactory()
# Enabled recipe
res = api_client.post(
"/api/v3/recipe/",
{
"name": "Test Recipe",
"action_id": action.id,
"arguments": {},
"extra_filter_expression": "whatever",
"enabled": True,
},
)
assert res.status_code == 201, res.json()
recipes = Recipe.objects.all()
assert recipes.count() == 1
def test_it_can_create_recipes_actions_without_implementation(self, api_client):
action = ActionFactory(implementation=None)
assert action.implementation is None
# Enabled recipe
res = api_client.post(
"/api/v3/recipe/",
{
"name": "Test Recipe",
"action_id": action.id,
"arguments": {},
"extra_filter_expression": "whatever",
"enabled": True,
},
)
assert res.status_code == 201
(recipe,) = Recipe.objects.all()
assert recipe.latest_revision.action.implementation is None
def test_it_can_create_disabled_recipes(self, api_client):
action = ActionFactory()
# Disabled recipe
res = api_client.post(
"/api/v3/recipe/",
{
"name": "Test Recipe",
"action_id": action.id,
"arguments": {},
"extra_filter_expression": "whatever",
"enabled": False,
},
)
assert res.status_code == 201
recipes = Recipe.objects.all()
assert recipes.count() == 1
def test_creation_when_action_does_not_exist(self, api_client):
res = api_client.post(
"/api/v3/recipe/", {"name": "Test Recipe", "action_id": 1234, "arguments": {}}
)
assert res.status_code == 400
assert res.json()["action_id"] == [
serializers.PrimaryKeyRelatedField.default_error_messages["does_not_exist"].format(
pk_value=1234
)
]
recipes = Recipe.objects.all()
assert recipes.count() == 0
def test_creation_when_action_id_is_missing(self, api_client):
res = api_client.post("/api/v3/recipe/", {"name": "Test Recipe", "arguments": {}})
assert res.status_code == 400
assert res.json()["action_id"] == [
serializers.PrimaryKeyRelatedField.default_error_messages["required"]
]
recipes = Recipe.objects.all()
assert recipes.count() == 0
def test_creation_when_action_id_is_invalid(self, api_client):
res = api_client.post(
"/api/v3/recipe/",
{"name": "Test Recipe", "action_id": "a string", "arguments": {}},
)
assert res.status_code == 400
assert res.json()["action_id"] == [
serializers.PrimaryKeyRelatedField.default_error_messages["incorrect_type"].format(
data_type="str"
)
]
recipes = Recipe.objects.all()
assert recipes.count() == 0
def test_creation_when_arguments_are_invalid(self, api_client):
action = ActionFactory(
name="foobarbaz",
arguments_schema={
"type": "object",
"properties": {"message": {"type": "string"}},
"required": ["message"],
},
)
res = api_client.post(
"/api/v3/recipe/",
{
"name": "Test Recipe",
"enabled": True,
"extra_filter_expression": "true",
"action_id": action.id,
"arguments": {},
},
)
assert res.status_code == 400
assert res.json()["arguments"]["message"] == "This field is required."
recipes = Recipe.objects.all()
assert recipes.count() == 0
def test_creation_when_arguments_is_missing(self, api_client):
action = ActionFactory(
name="foobarbaz",
arguments_schema={
"type": "object",
"properties": {"message": {"type": "string"}},
"required": ["message"],
},
)
res = api_client.post(
"/api/v3/recipe/",
{
"name": "Test Recipe",
"enabled": True,
"extra_filter_expression": "true",
"action_id": action.id,
},
)
assert res.status_code == 400
assert res.json()["arguments"] == [
serializers.PrimaryKeyRelatedField.default_error_messages["required"]
]
recipes = Recipe.objects.all()
assert recipes.count() == 0
def test_creation_when_arguments_is_a_string(self, api_client):
action = ActionFactory(
name="foobarbaz",
arguments_schema={
"type": "object",
"properties": {"message": {"type": "string"}},
"required": ["message"],
},
)
data = {
"name": "Test Recipe",
"enabled": True,
"extra_filter_expression": "true",
"action_id": action.id,
"arguments": '{"message": "the message"}',
}
res = api_client.post("/api/v3/recipe/", data)
assert res.status_code == 400
assert res.data == {"arguments": ["Must be an object."]}
recipes = Recipe.objects.all()
assert recipes.count() == 0
def test_creation_when_action_id_is_a_string_and_arguments_are_invalid(self, api_client):
action = ActionFactory(
name="foobarbaz",
arguments_schema={
"type": "object",
"properties": {"message": {"type": "string"}},
"required": ["message"],
},
)
data = {
"name": "Test Recipe",
"enabled": True,
"extra_filter_expression": "true",
"action_id": f"{action.id}",
"arguments": {},
}
res = api_client.post("/api/v3/recipe/", data)
assert res.status_code == 400
assert res.data == {"arguments": {"message": "This field is required."}}
recipes = Recipe.objects.all()
assert recipes.count() == 0
def test_creation_when_identicon_seed_is_invalid(self, api_client):
action = ActionFactory()
res = api_client.post(
"/api/v3/recipe/",
{
"name": "Test Recipe",
"action_id": action.id,
"arguments": {},
"extra_filter_expression": "whatever",
"enabled": True,
"identicon_seed": "invalid_identicon_seed",
},
)
assert res.status_code == 400
def test_at_least_one_filter_is_required(self, api_client):
action = ActionFactory()
res = api_client.post(
"/api/v3/recipe/",
{"name": "Test Recipe", "action_id": action.id, "arguments": {}, "enabled": True},
)
assert res.status_code == 400, res.json()
assert res.json() == {
"non_field_errors": ["one of extra_filter_expression or filter_object is required"]
}
def test_with_experimenter_slug(self, api_client):
action = ActionFactory()
res = api_client.post(
"/api/v3/recipe/",
{
"name": "Test Recipe",
"action_id": action.id,
"arguments": {},
"extra_filter_expression": "whatever",
"enabled": True,
"experimenter_slug": "some-experimenter-slug",
},
)
assert res.status_code == 201, res.json()
recipe = Recipe.objects.get()
assert recipe.latest_revision.experimenter_slug == "some-experimenter-slug"
def test_without_experimenter_slug(self, api_client):
action = ActionFactory()
res = api_client.post(
"/api/v3/recipe/",
{
"name": "Test Recipe",
"action_id": action.id,
"arguments": {},
"extra_filter_expression": "whatever",
"enabled": True,
},
)
assert res.status_code == 201, res.json()
recipe = Recipe.objects.get()
assert recipe.latest_revision.experimenter_slug is None
def test_creating_recipes_stores_the_user(self, api_client):
action = ActionFactory()
api_client.post(
"/api/v3/recipe/",
{
"name": "Test Recipe",
"action_id": action.id,
"arguments": {},
"extra_filter_expression": "whatever",
},
)
recipe = Recipe.objects.get()
assert recipe.latest_revision.user is not None
def test_it_can_create_recipes_with_only_filter_object(self, api_client):
action = ActionFactory()
channel = ChannelFactory()
res = api_client.post(
"/api/v3/recipe/",
{
"name": "Test Recipe",
"action_id": action.id,
"arguments": {},
"extra_filter_expression": " ",
"filter_object": [{"type": "channel", "channels": [channel.slug]}],
"enabled": True,
},
)
assert res.status_code == 201, res.json()
assert Recipe.objects.count() == 1
recipe = Recipe.objects.get()
assert recipe.latest_revision.extra_filter_expression == ""
assert (
recipe.latest_revision.filter_expression
== f'normandy.channel in ["{channel.slug}"]'
)
def test_it_can_create_extra_filter_expression_omitted(self, api_client):
action = ActionFactory()
channel = ChannelFactory()
# First try to create a recipe with 0 filter objects.
res = api_client.post(
"/api/v3/recipe/",
{
"name": "Test Recipe",
"action_id": action.id,
"arguments": {},
"filter_object": [],
"enabled": True,
},
)
assert res.status_code == 400
assert res.json()["non_field_errors"] == [
"one of extra_filter_expression or filter_object is required"
]
# Setting at least some filter_object but omitting the extra_filter_expression.
res = api_client.post(
"/api/v3/recipe/",
{
"name": "Test Recipe",
"action_id": action.id,
"arguments": {},
"filter_object": [{"type": "channel", "channels": [channel.slug]}],
"enabled": True,
},
)
assert res.status_code == 201, res.json()
assert Recipe.objects.count() == 1
recipe = Recipe.objects.get()
assert recipe.latest_revision.extra_filter_expression == ""
assert (
recipe.latest_revision.filter_expression
== f'normandy.channel in ["{channel.slug}"]'
)
def test_it_accepts_capabilities(self, api_client):
action = ActionFactory()
res = api_client.post(
"/api/v3/recipe/",
{
"action_id": action.id,
"extra_capabilities": ["test.one", "test.two"],
"arguments": {},
"name": "test recipe",
"extra_filter_expression": "true",
},
)
assert res.status_code == 201, res.json()
assert Recipe.objects.count() == 1
recipe = Recipe.objects.get()
# Passed extra capabilities:
assert recipe.latest_revision.extra_capabilities == ["test.one", "test.two"]
# Extra capabilities get included in capabilities
assert {"test.one", "test.two"} <= set(recipe.latest_revision.capabilities)
@pytest.mark.django_db
class TestUpdates(object):
def test_it_can_edit_recipes(self, api_client):
recipe = RecipeFactory(
name="unchanged", extra_filter_expression="true", filter_object_json=None
)
old_revision_id = recipe.latest_revision.id
res = api_client.patch(
"/api/v3/recipe/%s/" % recipe.id,
{"name": "changed", "extra_filter_expression": "false"},
)
assert res.status_code == 200
recipe = Recipe.objects.all()[0]
assert recipe.latest_revision.name == "changed"
assert recipe.latest_revision.filter_expression == "false"
assert recipe.latest_revision.id != old_revision_id
def test_it_can_change_action_for_recipes(self, api_client):
recipe = RecipeFactory()
action = ActionFactory()
res = api_client.patch("/api/v3/recipe/%s/" % recipe.id, {"action_id": action.id})
assert res.status_code == 200
recipe = Recipe.objects.get(pk=recipe.id)
assert recipe.latest_revision.action == action
def test_it_can_change_arguments_for_recipes(self, api_client):
recipe = RecipeFactory(arguments_json="{}")
action = ActionFactory(
name="foobarbaz",
arguments_schema={
"type": "object",
"properties": {"message": {"type": "string"}, "checkbox": {"type": "boolean"}},
"required": ["message", "checkbox"],
},
)
arguments = {"message": "test message", "checkbox": False}
res = api_client.patch(
"/api/v3/recipe/%s/" % recipe.id, {"action_id": action.id, "arguments": arguments}
)
assert res.status_code == 200, res.json()
recipe.refresh_from_db()
assert recipe.latest_revision.arguments == arguments
res = api_client.get("/api/v3/recipe/%s/" % recipe.id)
assert res.status_code == 200, res.json()
assert res.json()["latest_revision"]["arguments"] == arguments
arguments = {"message": "second message", "checkbox": True}
res = api_client.patch(
"/api/v3/recipe/%s/" % recipe.id, {"action_id": action.id, "arguments": arguments}
)
assert res.status_code == 200, res.json()
recipe.refresh_from_db()
assert recipe.latest_revision.arguments == arguments
res = api_client.get("/api/v3/recipe/%s/" % recipe.id)
assert res.status_code == 200, res.json()
assert res.json()["latest_revision"]["arguments"] == arguments
def test_it_can_delete_recipes(self, api_client):
recipe = RecipeFactory()
res = api_client.delete("/api/v3/recipe/%s/" % recipe.id)
assert res.status_code == 204
recipes = Recipe.objects.all()
assert recipes.count() == 0
def test_update_recipe_action(self, api_client):
r = RecipeFactory()
a = ActionFactory(name="test")
res = api_client.patch(f"/api/v3/recipe/{r.pk}/", {"action_id": a.id})
assert res.status_code == 200
r.refresh_from_db()
assert r.latest_revision.action == a
def test_update_recipe_comment(self, api_client):
r = RecipeFactory(comment="foo")
res = api_client.patch(f"/api/v3/recipe/{r.pk}/", {"comment": "bar"})
assert res.status_code == 200
r.refresh_from_db()
assert r.latest_revision.comment == "bar"
def test_update_recipe_experimenter_slug(self, api_client):
r = RecipeFactory()
res = api_client.patch(f"/api/v3/recipe/{r.pk}/", {"experimenter_slug": "a-new-slug"})
assert res.status_code == 200
r.refresh_from_db()
assert r.latest_revision.experimenter_slug == "a-new-slug"
def test_updating_recipes_stores_the_user(self, api_client):
recipe = RecipeFactory()
api_client.patch(f"/api/v3/recipe/{recipe.pk}/", {"name": "Test Recipe"})
recipe.refresh_from_db()
assert recipe.latest_revision.user is not None
def test_it_can_update_recipes_with_only_filter_object(self, api_client):
recipe = RecipeFactory(name="unchanged", extra_filter_expression="true")
channel = ChannelFactory()
res = api_client.patch(
"/api/v3/recipe/%s/" % recipe.id,
{
"name": "changed",
"extra_filter_expression": "",
"filter_object": [{"type": "channel", "channels": [channel.slug]}],
},
)
assert res.status_code == 200, res.json()
recipe.refresh_from_db()
assert recipe.latest_revision.extra_filter_expression == ""
assert recipe.latest_revision.filter_object
assert (
recipe.latest_revision.filter_expression
== f'normandy.channel in ["{channel.slug}"]'
)
# And you can omit it too
res = api_client.patch(
"/api/v3/recipe/%s/" % recipe.id,
{
"name": "changed",
"filter_object": [{"type": "channel", "channels": [channel.slug]}],
},
)
assert res.status_code == 200, res.json()
recipe.refresh_from_db()
assert recipe.latest_revision.extra_filter_expression == ""
# Let's paranoid-check that you can't unset the filter_object too.
res = api_client.patch(
"/api/v3/recipe/%s/" % recipe.id, {"name": "changed", "filter_object": []}
)
assert res.status_code == 400
assert res.json()["non_field_errors"] == [
"if extra_filter_expression is blank, at least one filter_object is required"
]
def test_it_can_update_capabilities(self, api_client):
recipe = RecipeFactory(extra_capabilities=["always", "original"])
res = api_client.patch(
f"/api/v3/recipe/{recipe.id}/", {"extra_capabilities": ["always", "changed"]}
)
assert res.status_code == 200
recipe = Recipe.objects.get()
assert {"always", "changed"} <= set(recipe.latest_revision.capabilities)
assert "original" not in recipe.latest_revision.capabilities
@pytest.mark.django_db
class TestFilterObjects(object):
def make_recipe(self, api_client, **kwargs):
data = {
"name": "Test Recipe",
"action_id": ActionFactory().id,
"arguments": {},
"enabled": True,
"extra_filter_expression": "true",
"filter_object": [],
}
data.update(kwargs)
return api_client.post("/api/v3/recipe/", data)
def test_bad_filter_objects(self, api_client):
res = self.make_recipe(api_client, filter_object={}) # not a list
assert res.status_code == 400
assert res.json() == {
"filter_object": ['Expected a list of items but got type "dict".']
}
res = self.make_recipe(
api_client, filter_object=["1 + 1 == 2"]
) # not a list of objects
assert res.status_code == 400
assert res.json() == {
"filter_object": {
"0": {"non field errors": ["filter_object members must be objects."]}
}
}
res = self.make_recipe(
api_client, filter_object=[{"channels": ["release"]}]
) # type is required
assert res.status_code == 400
assert res.json() == {"filter_object": {"0": {"type": ["This field is required."]}}}
def test_validate_filter_objects_channels(self, api_client):
res = self.make_recipe(
api_client, filter_object=[{"type": "channel", "channels": ["nightwolf"]}]
)
assert res.status_code == 400
assert res.json() == {
"filter_object": {"0": {"channels": ["Unrecognized channel slug 'nightwolf'"]}}
}
ChannelFactory(slug="nightwolf")
res = self.make_recipe(
api_client, filter_object=[{"type": "channel", "channels": ["nightwolf"]}]
)
assert res.status_code == 201
def test_validate_filter_objects_locales(self, api_client):
res = self.make_recipe(
api_client, filter_object=[{"type": "locale", "locales": ["sv"]}]
)
assert res.status_code == 400
assert res.json() == {
"filter_object": {"0": {"locales": ["Unrecognized locale code 'sv'"]}}
}
LocaleFactory(code="sv")
res = self.make_recipe(
api_client, filter_object=[{"type": "locale", "locales": ["sv"]}]
)
assert res.status_code == 201
def test_validate_filter_objects_countries(self, api_client):
res = self.make_recipe(
api_client, filter_object=[{"type": "country", "countries": ["SS"]}]
)
assert res.status_code == 400
assert res.json() == {
"filter_object": {"0": {"countries": ["Unrecognized country code 'SS'"]}}
}
CountryFactory(code="SS", name="South Sudan")
res = self.make_recipe(
api_client, filter_object=[{"type": "country", "countries": ["SS"]}]
)
assert res.status_code == 201
def test_channel_works(self, api_client):
channel1 = ChannelFactory(slug="beta")
channel2 = ChannelFactory(slug="release")
res = self.make_recipe(
api_client,
filter_object=[{"type": "channel", "channels": [channel1.slug, channel2.slug]}],
)
assert res.status_code == 201, res.json()
recipe_data = res.json()
Recipe.objects.get(id=recipe_data["id"])
assert recipe_data["latest_revision"]["filter_expression"] == (
f'(normandy.channel in ["{channel1.slug}","{channel2.slug}"]) && (true)'
)
def test_channel_correct_fields(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "channel"}])
assert res.status_code == 400
assert res.json() == {
"filter_object": {"0": {"channels": ["This field is required."]}}
}
def test_locale_works(self, api_client):
locale1 = LocaleFactory()
locale2 = LocaleFactory(code="de")
res = self.make_recipe(
api_client,
filter_object=[{"type": "locale", "locales": [locale1.code, locale2.code]}],
)
assert res.status_code == 201, res.json()
recipe_data = res.json()
Recipe.objects.get(id=recipe_data["id"])
assert recipe_data["latest_revision"]["filter_expression"] == (
f'(normandy.locale in ["{locale1.code}","{locale2.code}"]) && (true)'
)
def test_locale_correct_fields(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "locale"}])
assert res.status_code == 400
assert res.json() == {"filter_object": {"0": {"locales": ["This field is required."]}}}
def test_country_works(self, api_client):
country1 = CountryFactory()
country2 = CountryFactory(code="DE")
res = self.make_recipe(
api_client,
filter_object=[{"type": "country", "countries": [country1.code, country2.code]}],
)
assert res.status_code == 201, res.json()
recipe_data = res.json()
Recipe.objects.get(id=recipe_data["id"])
assert recipe_data["latest_revision"]["filter_expression"] == (
f'(normandy.country in ["{country1.code}","{country2.code}"]) && (true)'
)
def test_country_correct_fields(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "country"}])
assert res.status_code == 400
assert res.json() == {
"filter_object": {"0": {"countries": ["This field is required."]}}
}
def test_bucket_sample_works(self, api_client):
res = self.make_recipe(
api_client,
filter_object=[
{
"type": "bucketSample",
"start": 1,
"count": 2,
"total": 3,
"input": ["normandy.userId", "normandy.recipeId"],
}
],
)
assert res.status_code == 201, res.json()
recipe_data = res.json()
Recipe.objects.get(id=recipe_data["id"])
assert recipe_data["latest_revision"]["filter_expression"] == (
"([normandy.userId,normandy.recipeId]|bucketSample(1,2,3)) && (true)"
)
def test_bucket_sample_correct_fields(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "bucketSample"}])
assert res.status_code == 400
assert res.json() == {
"filter_object": {
"0": {
"start": ["This field is required."],
"count": ["This field is required."],
"total": ["This field is required."],
"input": ["This field is required."],
}
}
}
res = self.make_recipe(
api_client,
filter_object=[{"type": "bucketSample", "start": "a", "count": -1, "total": -2}],
)
assert res.status_code == 400
assert res.json() == {
"filter_object": {
"0": {
"start": ["A valid number is required."],
"count": ["Ensure this value is greater than or equal to 0."],
"total": ["Ensure this value is greater than or equal to 0."],
"input": ["This field is required."],
}
}
}
def test_stable_sample_works(self, api_client):
res = self.make_recipe(
api_client,
filter_object=[
{
"type": "stableSample",
"rate": 0.5,
"input": ["normandy.userId", "normandy.recipeId"],
}
],
)
assert res.status_code == 201, res.json()
recipe_data = res.json()
Recipe.objects.get(id=recipe_data["id"])
assert recipe_data["latest_revision"]["filter_expression"] == (
"([normandy.userId,normandy.recipeId]|stableSample(0.5)) && (true)"
)
def test_stable_sample_correct_fields(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "stableSample"}])
assert res.status_code == 400
assert res.json() == {
"filter_object": {
"0": {
"rate": ["This field is required."],
"input": ["This field is required."],
}
}
}
res = self.make_recipe(
api_client, filter_object=[{"type": "stableSample", "rate": 10}]
)
assert res.status_code == 400
assert res.json() == {
"filter_object": {
"0": {
"rate": ["Ensure this value is less than or equal to 1."],
"input": ["This field is required."],
}
}
}
def test_version_works(self, api_client):
res = self.make_recipe(
api_client, filter_object=[{"type": "version", "versions": [57, 58, 62]}]
)
assert res.status_code == 201, res.json()
recipe_data = res.json()
Recipe.objects.get(id=recipe_data["id"])
assert recipe_data["latest_revision"]["filter_expression"] == (
'((env.version|versionCompare("57.!")>=0)&&'
'(env.version|versionCompare("57.*")<0)||'
'(env.version|versionCompare("58.!")>=0)&&'
'(env.version|versionCompare("58.*")<0)||'
'(env.version|versionCompare("62.!")>=0)&&'
'(env.version|versionCompare("62.*")<0)) && (true)'
)
def test_version_correct_fields(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "version"}])
assert res.status_code == 400
assert res.json() == {
"filter_object": {"0": {"versions": ["This field is required."]}}
}
def test_invalid_filter(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "invalid"}])
assert res.status_code == 400
assert res.json() == {
"filter_object": {"0": {"type": ['Unknown filter object type "invalid".']}}
}
@pytest.mark.django_db
class TestDetail(object):
def test_history(self, api_client):
recipe = RecipeFactory(name="version 1")
recipe.revise(name="version 2")
recipe.revise(name="version 3")
res = api_client.get("/api/v3/recipe/%s/history/" % recipe.id)
assert res.data[0]["name"] == "version 3"
assert res.data[1]["name"] == "version 2"
assert res.data[2]["name"] == "version 1"
def test_it_can_enable_recipes(self, api_client):
recipe = RecipeFactory(approver=UserFactory())
res = api_client.post("/api/v3/recipe/%s/enable/" % recipe.id)
assert res.status_code == 200
assert res.data["approved_revision"]["enabled"] is True
recipe = Recipe.objects.all()[0]
assert recipe.approved_revision.enabled
def test_cannot_enable_unapproved_recipes(self, api_client):
recipe = RecipeFactory()
res = api_client.post("/api/v3/recipe/%s/enable/" % recipe.id)
assert res.status_code == 409
assert res.data["error"] == "Cannot enable a recipe that is not approved."
def test_cannot_enable_enabled_recipes(self, api_client):
recipe = RecipeFactory(approver=UserFactory(), enabler=UserFactory())
res = api_client.post("/api/v3/recipe/%s/enable/" % recipe.id)
assert res.status_code == 409
assert res.data["error"] == "This revision is already enabled."
def test_it_can_disable_enabled_recipes(self, api_client):
recipe = RecipeFactory(approver=UserFactory(), enabler=UserFactory())
assert recipe.approved_revision.enabled
res = api_client.post("/api/v3/recipe/%s/disable/" % recipe.id)
assert res.status_code == 200
assert res.data["approved_revision"]["enabled"] is False
recipe = Recipe.objects.all()[0]
assert not recipe.approved_revision.enabled
# Can't disable it a second time.
res = api_client.post("/api/v3/recipe/%s/disable/" % recipe.id)
assert res.status_code == 409
assert res.json()["error"] == "This revision is already disabled."
def test_detail_view_includes_cache_headers(self, api_client):
recipe = RecipeFactory()
res = api_client.get(f"/api/v3/recipe/{recipe.id}/")
assert res.status_code == 200
# It isn't important to assert a particular value for max-age
assert "max-age=" in res["Cache-Control"]
assert "public" in res["Cache-Control"]
def test_detail_sets_no_cookies(self, api_client):
recipe = RecipeFactory()
res = api_client.get("/api/v3/recipe/{id}/".format(id=recipe.id))
assert res.status_code == 200
assert res.client.cookies == {}
@pytest.mark.django_db
class TestFiltering(object):
def test_filtering_by_enabled_lowercase(self, api_client):
r1 = RecipeFactory(approver=UserFactory(), enabler=UserFactory())
RecipeFactory()
res = api_client.get("/api/v3/recipe/?enabled=true")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r1.id]
def test_filtering_by_enabled_fuzz(self, api_client):
"""
Test that we don't return 500 responses when we get unexpected boolean filters.
This was a real case that showed up in our error logging.
"""
url = (
"/api/v3/recipe/?enabled=javascript%3a%2f*"
"<%2fscript><svg%2fonload%3d'%2b%2f'%2f%2b"
)
res = api_client.get(url)
assert res.status_code == 200
def test_list_filter_status(self, api_client):
r1 = RecipeFactory()
r2 = RecipeFactory(approver=UserFactory(), enabler=UserFactory())
res = api_client.get("/api/v3/recipe/?status=enabled")
assert res.status_code == 200
results = res.data["results"]
assert len(results) == 1
assert results[0]["id"] == r2.id
res = api_client.get("/api/v3/recipe/?status=disabled")
assert res.status_code == 200
results = res.data["results"]
assert len(results) == 1
assert results[0]["id"] == r1.id
def test_list_filter_text(self, api_client):
r1 = RecipeFactory(name="first", extra_filter_expression="1 + 1 == 2")
r2 = RecipeFactory(name="second", extra_filter_expression="one + one == two")
res = api_client.get("/api/v3/recipe/?text=first")
assert res.status_code == 200
results = res.data["results"]
assert len(results) == 1
assert results[0]["id"] == r1.id
res = api_client.get("/api/v3/recipe/?text=one")
assert res.status_code == 200
results = res.data["results"]
assert len(results) == 1
assert results[0]["id"] == r2.id
res = api_client.get("/api/v3/recipe/?text=t")
assert res.status_code == 200
results = res.data["results"]
assert len(results) == 2
for recipe in results:
assert recipe["id"] in [r1.id, r2.id]
def test_list_filter_text_null_bytes(self, api_client):
res = api_client.get("/api/v3/recipe/?text=\x00")
assert res.status_code == 400
assert res.json()["detail"] == "Null bytes in text"
def test_search_works_with_arguments(self, api_client):
r1 = RecipeFactory(arguments={"one": 1})
r2 = RecipeFactory(arguments={"two": 2})
res = api_client.get("/api/v3/recipe/?text=one")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r1.id]
res = api_client.get("/api/v3/recipe/?text=2")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r2.id]
def test_search_out_of_order(self, api_client):
r1 = RecipeFactory(name="apple banana")
r2 = RecipeFactory(name="cherry daikon")
res = api_client.get("/api/v3/recipe/?text=banana apple")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r1.id]
res = api_client.get("/api/v3/recipe/?text=daikon cherry")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r2.id]
def test_search_all_words_required(self, api_client):
r1 = RecipeFactory(name="apple banana")
RecipeFactory(name="apple")
res = api_client.get("/api/v3/recipe/?text=apple banana")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r1.id]
def test_list_filter_action_legacy(self, api_client):
a1 = ActionFactory()
a2 = ActionFactory()
r1 = RecipeFactory(action=a1)
r2 = RecipeFactory(action=a2)
assert a1.id != a2.id
res = api_client.get(f"/api/v3/recipe/?latest_revision__action={a1.id}")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r1.id]
res = api_client.get(f"/api/v3/recipe/?latest_revision__action={a2.id}")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r2.id]
assert a1.id != -1 and a2.id != -1
res = api_client.get("/api/v3/recipe/?latest_revision__action=-1")
assert res.status_code == 400
assert res.data["latest_revision__action"][0].code == "invalid_choice"
def test_list_filter_action(self, api_client):
a1 = ActionFactory()
a2 = ActionFactory()
r1 = RecipeFactory(action=a1)
r2 = RecipeFactory(action=a2)
assert a1.name != a2.name
res = api_client.get(f"/api/v3/recipe/?action={a1.name}")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r1.id]
res = api_client.get(f"/api/v3/recipe/?action={a2.name}")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r2.id]
assert a1.name != "nonexistant" and a2.name != "nonexistant"
res = api_client.get("/api/v3/recipe/?action=nonexistant")
assert res.status_code == 200
assert res.data["count"] == 0
def test_filter_by_experimenter_slug(self, api_client):
RecipeFactory()
match1 = RecipeFactory(experimenter_slug="a-slug")
RecipeFactory(experimenter_slug="something-else")
RecipeFactory(experimenter_slug="some-other-slug")
res = api_client.get("/api/v3/recipe/?experimenter_slug=a-slug")
assert res.status_code == 200
assert res.data["count"] == 1
assert set(r["id"] for r in res.data["results"]) == set([match1.id])
def test_order_last_updated(self, api_client):
r1 = RecipeFactory()
r2 = RecipeFactory()
now = r1.latest_revision.updated
yesterday = now - timedelta(days=1)
r1.latest_revision.updated = yesterday
r2.latest_revision.updated = now
# Call the super class's save method so that
# `latest_revision.updated` doesn't get rewritten
super(RecipeRevision, r1.latest_revision).save()
super(RecipeRevision, r2.latest_revision).save()
res = api_client.get("/api/v3/recipe/?ordering=last_updated")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r1.id, r2.id]
res = api_client.get("/api/v3/recipe/?ordering=-last_updated")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r2.id, r1.id]
def test_order_name(self, api_client):
r1 = RecipeFactory(name="a")
r2 = RecipeFactory(name="b")
res = api_client.get("/api/v3/recipe/?ordering=name")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r1.id, r2.id]
res = api_client.get("/api/v3/recipe/?ordering=-name")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == [r2.id, r1.id]
def test_order_by_action_name(self, api_client):
r1 = RecipeFactory(name="a")
r1.latest_revision.action.name = "Bee"
r1.latest_revision.action.save()
r2 = RecipeFactory(name="b")
r2.latest_revision.action.name = "Cee"
r2.latest_revision.action.save()
r3 = RecipeFactory(name="c")
r3.latest_revision.action.name = "Ahh"
r3.latest_revision.action.save()
res = api_client.get("/api/v3/recipe/?ordering=action")
assert res.status_code == 200
# Expected order is ['Ahh', 'Bee', 'Cee']
assert [r["id"] for r in res.data["results"]] == [r3.id, r1.id, r2.id]
res = api_client.get("/api/v3/recipe/?ordering=-action")
assert res.status_code == 200
# Expected order is ['Cee', 'Bee', 'Ahh']
assert [r["id"] for r in res.data["results"]] == [r2.id, r1.id, r3.id]
def test_order_bogus(self, api_client):
"""Test that filtering by an unknown key doesn't change the sort order"""
RecipeFactory(name="a")
RecipeFactory(name="b")
res = api_client.get("/api/v3/recipe/?ordering=bogus")
assert res.status_code == 200
first_ordering = [r["id"] for r in res.data["results"]]
res = api_client.get("/api/v3/recipe/?ordering=-bogus")
assert res.status_code == 200
assert [r["id"] for r in res.data["results"]] == first_ordering
@pytest.mark.django_db
class TestRecipeRevisionAPI(object):
def test_it_works(self, api_client):
res = api_client.get("/api/v3/recipe_revision/")
assert res.status_code == 200
assert res.data == {"count": 0, "next": None, "previous": None, "results": []}
def test_it_serves_revisions(self, api_client):
recipe = RecipeFactory()
res = api_client.get("/api/v3/recipe_revision/%s/" % recipe.latest_revision.id)
assert res.status_code == 200
assert res.data["id"] == recipe.latest_revision.id
def test_request_approval(self, api_client):
recipe = RecipeFactory()
res = api_client.post(
"/api/v3/recipe_revision/{}/request_approval/".format(recipe.latest_revision.id)
)
assert res.status_code == 201
assert res.data["id"] == recipe.latest_revision.approval_request.id
def test_cannot_open_second_approval_request(self, api_client):
recipe = RecipeFactory()
ApprovalRequestFactory(revision=recipe.latest_revision)
res = api_client.post(
"/api/v3/recipe_revision/{}/request_approval/".format(recipe.latest_revision.id)
)
assert res.status_code == 400
def test_it_has_an_identicon_seed(self, api_client):
recipe = RecipeFactory(enabler=UserFactory(), approver=UserFactory())
res = api_client.get(f"/api/v3/recipe_revision/{recipe.latest_revision.id}/")
assert res.data["identicon_seed"] == recipe.latest_revision.identicon_seed
def test_metadata(self, api_client):
revision = RecipeFactory(metadata={"test1": "a"}).latest_revision
assert revision.metadata == {"test1": "a"}
url = f"/api/v3/recipe_revision/{revision.id}/"
metadata_url = url + "metadata/"
res = api_client.get(url)
assert res.status_code == 200
assert res.data["metadata"] == {"test1": "a"}
res = api_client.patch(metadata_url, {"test1": "b"})
assert res.status_code == 200
revision.refresh_from_db()
assert revision.metadata == {"test1": "b"}
res = api_client.patch(metadata_url, {"test2": "c"})
assert res.status_code == 200
revision.refresh_from_db()
assert revision.metadata == {"test1": "b", "test2": "c"}
res = api_client.patch(metadata_url, {"test1": None})
assert res.status_code == 200
revision.refresh_from_db()
assert revision.metadata == {"test2": "c"}
res = api_client.get(metadata_url)
assert res.status_code == 200
assert res.data == {"test2": "c"}
def test_filter_by_creation_date(self, api_client):
r1 = RecipeFactory(created=datetime(2019, 1, 1)).latest_revision
r2 = RecipeFactory(created=datetime(2020, 1, 1)).latest_revision
r3 = RecipeFactory(created=datetime(2021, 1, 1)).latest_revision
res = api_client.get("/api/v3/recipe_revision/")
assert res.status_code == 200, res.data
assert set(rev["id"] for rev in res.data["results"]) == set(
[r1.id, r2.id, r3.id]
), "no filters returns everything"
assert set(rev["date_created"][:4] for rev in res.data["results"]) == set(
["2019", "2020", "2021"]
), "correct dates are in the API"
res = api_client.get("/api/v3/recipe_revision/?created_end=2020-06-01")
assert res.status_code == 200, res.data
assert set(rev["id"] for rev in res.data["results"]) == set(
[r1.id, r2.id]
), "before filter works"
res = api_client.get("/api/v3/recipe_revision/?created_start=2019-06-01")
assert res.status_code == 200, res.data
assert set(rev["id"] for rev in res.data["results"]) == set(
[r2.id, r3.id]
), "after filter works"
res = api_client.get(
"/api/v3/recipe_revision/?created_start=2019-06-01&created_end=2020-06-01"
)
assert res.status_code == 200, res.data
assert set(rev["id"] for rev in res.data["results"]) == set(
[r2.id]
), "before and after can be combined"
res = api_client.get("/api/v3/recipe_revision/?created_end=1965-01-01")
assert res.status_code == 200, res.data
assert len(res.data["results"]) == 0, "before can find nothing"
res = api_client.get("/api/v3/recipe_revision/?created_start=2055-01-01")
assert res.status_code == 200, res.data
assert len(res.data["results"]) == 0, "after can find nothing"
def test_filter_by_creation_date_is_inclusive(self, api_client):
revisions = [RecipeFactory(created=datetime(2021, 1, d)) for d in range(1, 32)]
assert len(revisions) == 31
res = api_client.get(
"/api/v3/recipe_revision/?created_start=2021-01-10&created_end=2021-01-20"
)
assert res.status_code == 200, res.data
assert set(rev["date_created"][:10] for rev in res.data["results"]) == set(
f"2021-01-{d}" for d in range(10, 21)
)
@pytest.mark.django_db
class TestApprovalRequestAPI(object):
def test_it_works(self, api_client):
res = api_client.get("/api/v3/approval_request/")
assert res.status_code == 200
assert res.data == {"count": 0, "next": None, "previous": None, "results": []}
def test_approve(self, api_client):
r = RecipeFactory()
a = ApprovalRequestFactory(revision=r.latest_revision)
res = api_client.post(
"/api/v3/approval_request/{}/approve/".format(a.id), {"comment": "r+"}
)
assert res.status_code == 200
r.refresh_from_db()
assert r.is_approved
assert r.approved_revision.approval_request.comment == "r+"
def test_approve_no_comment(self, api_client):
r = RecipeFactory()
a = ApprovalRequestFactory(revision=r.latest_revision)
res = api_client.post("/api/v3/approval_request/{}/approve/".format(a.id))
assert res.status_code == 400
assert res.data["comment"] == "This field is required."
def test_approve_not_actionable(self, api_client):
r = RecipeFactory()
a = ApprovalRequestFactory(revision=r.latest_revision)
a.approve(UserFactory(), "r+")
res = api_client.post(
"/api/v3/approval_request/{}/approve/".format(a.id), {"comment": "r+"}
)
assert res.status_code == 400
assert res.data["error"] == "This approval request has already been approved or rejected."
def test_reject(self, api_client):
r = RecipeFactory()
a = ApprovalRequestFactory(revision=r.latest_revision)
res = api_client.post(
"/api/v3/approval_request/{}/reject/".format(a.id), {"comment": "r-"}
)
assert res.status_code == 200
r.latest_revision.approval_request.refresh_from_db()
assert r.latest_revision.approval_status == r.latest_revision.REJECTED
assert r.latest_revision.approval_request.comment == "r-"
def test_reject_no_comment(self, api_client):
r = RecipeFactory()
a = ApprovalRequestFactory(revision=r.latest_revision)
res = api_client.post("/api/v3/approval_request/{}/reject/".format(a.id))
assert res.status_code == 400
assert res.data["comment"] == "This field is required."
def test_reject_not_actionable(self, api_client):
r = RecipeFactory()
a = ApprovalRequestFactory(revision=r.latest_revision)
a.approve(UserFactory(), "r+")
res = api_client.post(
"/api/v3/approval_request/{}/reject/".format(a.id), {"comment": "-r"}
)
assert res.status_code == 400
assert res.data["error"] == "This approval request has already been approved or rejected."
def test_close(self, api_client):
r = RecipeFactory()
a = ApprovalRequestFactory(revision=r.latest_revision)
res = api_client.post("/api/v3/approval_request/{}/close/".format(a.id))
assert res.status_code == 204
with pytest.raises(ApprovalRequest.DoesNotExist):
ApprovalRequest.objects.get(pk=a.pk)
def test_list(self, api_client):
approval_requests = ApprovalRequestFactory.create_batch(5)
res = api_client.get("/api/v3/approval_request/")
assert res.status_code == 200
assert set(a.id for a in approval_requests) == set(a["id"] for a in res.data["results"])
def test_filter_by_approval(self, api_client):
pending = ApprovalRequestFactory(approved=None)
approved = ApprovalRequestFactory(approved=True)
rejected = ApprovalRequestFactory(approved=False)
# First check that all of them show up
res = api_client.get("/api/v3/approval_request/")
assert res.status_code == 200
assert {approved.id, pending.id, rejected.id} == set(a["id"] for a in res.data["results"])
# Now check that filtering works as expected
patterns = [
(["true", "1", "approved"], approved.id),
(["false", "0", "rejected"], rejected.id),
(["null", "pending"], pending.id),
]
for (aliases, expected_id) in patterns:
for alias in aliases:
res = api_client.get(f"/api/v3/approval_request/?approved={alias}")
assert res.status_code == 200, f"Expected {alias} to give a 200 status"
assert {expected_id} == set(
a["id"] for a in res.data["results"]
), f"Expected alias {alias!r} to return the right approval request"
@pytest.mark.django_db
class TestApprovalFlow(object):
def verify_signatures(self, api_client, expected_count=None):
# v1 usage here is correct, since v3 doesn't yet provide signatures
res = api_client.get("/api/v1/recipe/signed/")
assert res.status_code == 200
signed_data = res.json()
if expected_count is not None:
assert len(signed_data) == expected_count
for recipe_and_signature in signed_data:
recipe = recipe_and_signature["recipe"]
expected_signature = recipe_and_signature["signature"]["signature"]
data = canonical_json_dumps(recipe).encode()
actual_signature = fake_sign([data])[0]["signature"]
assert actual_signature == expected_signature
def test_full_approval_flow(self, settings, api_client, mocked_autograph):
# The `mocked_autograph` fixture is provided so that recipes can be signed
settings.PEER_APPROVAL_ENFORCED = True
action = ActionFactory()
user1 = UserFactory(is_superuser=True)
user2 = UserFactory(is_superuser=True)
api_client.force_authenticate(user1)
settings.BASELINE_CAPABILITIES |= action.capabilities
# Create a recipe
res = api_client.post(
"/api/v3/recipe/",
{
"action_id": action.id,
"arguments": {},
"name": "test recipe",
"extra_filter_expression": "counter == 0",
"enabled": "false",
},
)
assert res.status_code == 201, res.data
recipe_data_0 = res.json()
# It is visible in the api but not approved
res = api_client.get(f"/api/v3/recipe/{recipe_data_0['id']}/")
assert res.status_code == 200
assert res.json()["latest_revision"] is not None
assert res.json()["approved_revision"] is None
# Request approval for it
res = api_client.post(
"/api/v3/recipe_revision/{}/request_approval/".format(
recipe_data_0["latest_revision"]["id"]
)
)
approval_data = res.json()
assert res.status_code == 201
# The requester isn't allowed to approve a recipe
res = api_client.post(
"/api/v3/approval_request/{}/approve/".format(approval_data["id"]), {"comment": "r+"}
)
assert res.status_code == 403 # Forbidden
# Approve and enable the recipe
api_client.force_authenticate(user2)
res = api_client.post(
"/api/v3/approval_request/{}/approve/".format(approval_data["id"]), {"comment": "r+"}
)
assert res.status_code == 200
res = api_client.post("/api/v3/recipe/{}/enable/".format(recipe_data_0["id"]))
assert res.status_code == 200
# It is now visible in the API as approved and signed
res = api_client.get("/api/v3/recipe/{}/".format(recipe_data_0["id"]))
assert res.status_code == 200
recipe_data_1 = res.json()
assert recipe_data_1["approved_revision"] is not None
assert (
Recipe.objects.get(id=recipe_data_1["id"]).latest_revision.capabilities
<= settings.BASELINE_CAPABILITIES
)
self.verify_signatures(api_client, expected_count=1)
# Make another change
api_client.force_authenticate(user1)
res = api_client.patch(
"/api/v3/recipe/{}/".format(recipe_data_1["id"]),
{"extra_filter_expression": "counter == 1"},
)
assert res.status_code == 200
# The change should only be seen in the latest revision, not the approved
res = api_client.get("/api/v3/recipe/{}/".format(recipe_data_1["id"]))
assert res.status_code == 200
recipe_data_2 = res.json()
assert recipe_data_2["approved_revision"]["extra_filter_expression"] == "counter == 0"
assert recipe_data_2["latest_revision"]["extra_filter_expression"] == "counter == 1"
self.verify_signatures(api_client, expected_count=1)
# Request approval for the change
res = api_client.post(
"/api/v3/recipe_revision/{}/request_approval/".format(
recipe_data_2["latest_revision"]["id"]
)
)
approval_data = res.json()
recipe_data_2["latest_revision"]["approval_request"] = approval_data
assert res.status_code == 201
# The change should not be visible yet, since it isn't approved
res = api_client.get("/api/v3/recipe/{}/".format(recipe_data_1["id"]))
assert res.status_code == 200
assert res.json()["approved_revision"] == recipe_data_2["approved_revision"]
assert res.json()["latest_revision"] == recipe_data_2["latest_revision"]
self.verify_signatures(api_client, expected_count=1)
# Can't reject your own approval
res = api_client.post(
"/api/v3/approval_request/{}/reject/".format(approval_data["id"]), {"comment": "r-"}
)
assert res.status_code == 403
assert res.json()["error"] == "You cannot reject your own approval request."
# Reject the change
api_client.force_authenticate(user2)
res = api_client.post(
"/api/v3/approval_request/{}/reject/".format(approval_data["id"]), {"comment": "r-"}
)
approval_data = res.json()
recipe_data_2["approval_request"] = approval_data
recipe_data_2["latest_revision"]["approval_request"] = approval_data
assert res.status_code == 200
# The change should not be visible yet, since it isn't approved
res = api_client.get("/api/v3/recipe/{}/".format(recipe_data_1["id"]))
assert res.status_code == 200
assert res.json()["approved_revision"] == recipe_data_2["approved_revision"]
assert res.json()["latest_revision"] == recipe_data_2["latest_revision"]
self.verify_signatures(api_client, expected_count=1)
# Make a third version of the recipe
api_client.force_authenticate(user1)
res = api_client.patch(
"/api/v3/recipe/{}/".format(recipe_data_1["id"]),
{"extra_filter_expression": "counter == 2"},
)
recipe_data_3 = res.json()
assert res.status_code == 200
# Request approval
res = api_client.post(
"/api/v3/recipe_revision/{}/request_approval/".format(
recipe_data_3["latest_revision"]["id"]
)
)
approval_data = res.json()
assert res.status_code == 201
# Approve the change
api_client.force_authenticate(user2)
res = api_client.post(
"/api/v3/approval_request/{}/approve/".format(approval_data["id"]), {"comment": "r+"}
)
assert res.status_code == 200
# The change should be visible now, since it is approved
res = api_client.get("/api/v3/recipe/{}/".format(recipe_data_1["id"]))
assert res.status_code == 200
recipe_data_4 = res.json()
assert recipe_data_4["approved_revision"]["extra_filter_expression"] == "counter == 2"
self.verify_signatures(api_client, expected_count=1)
def test_cancel_approval(self, api_client, mocked_autograph, settings):
action = ActionFactory()
settings.BASELINE_CAPABILITIES |= action.capabilities
user1 = UserFactory(is_superuser=True)
user2 = UserFactory(is_superuser=True)
api_client.force_authenticate(user1)
# Create a recipe
res = api_client.post(
"/api/v3/recipe/",
{
"action_id": action.id,
"arguments": {},
"name": "test recipe",
"extra_filter_expression": "counter == 0",
"enabled": "false",
},
)
assert res.status_code == 201
recipe_id = res.json()["id"]
revision_id = res.json()["latest_revision"]["id"]
assert (
Recipe.objects.get(id=recipe_id).latest_revision.capabilities
<= settings.BASELINE_CAPABILITIES
)
# Request approval
res = api_client.post(f"/api/v3/recipe_revision/{revision_id}/request_approval/")
assert res.status_code == 201
approval_request_id = res.json()["id"]
# Approve the recipe
api_client.force_authenticate(user2)
res = api_client.post(
f"/api/v3/approval_request/{approval_request_id}/approve/", {"comment": "r+"}
)
assert res.status_code == 200
# The API shouldn't have any signed recipe yet
self.verify_signatures(api_client, expected_count=0)
# Enable the recipe
res = api_client.post(f"/api/v3/recipe/{recipe_id}/enable/")
assert res.status_code == 200
# The API should have correct signatures now
self.verify_signatures(api_client, expected_count=1)
# Make another change
api_client.force_authenticate(user1)
res = api_client.patch(
f"/api/v3/recipe/{recipe_id}/", {"extra_filter_expression": "counter == 1"}
)
assert res.status_code == 200
revision_id = res.json()["latest_revision"]["id"]
# Request approval for the second change
res = api_client.post(f"/api/v3/recipe_revision/{revision_id}/request_approval/")
approval_request_id = res.json()["id"]
assert res.status_code == 201
# Cancel the approval request
res = api_client.post(f"/api/v3/approval_request/{approval_request_id}/close/")
assert res.status_code == 204
# The API should still have correct signatures
self.verify_signatures(api_client, expected_count=1)
@pytest.mark.django_db
@pytest.mark.parametrize(
"endpoint,Factory",
[
("/api/v3/action/", ActionFactory),
("/api/v3/recipe/", RecipeFactory),
("/api/v3/recipe_revision/", RecipeRevisionFactory),
("/api/v3/approval_request/", ApprovalRequestFactory),
],
)
def test_apis_makes_a_reasonable_number_of_db_queries(endpoint, Factory, client, settings):
# Naive versions of this view could easily make several queries
# per item, which is very slow. Make sure that isn't the case.
Factory.create_batch(100)
queries = CaptureQueriesContext(connection)
with queries:
res = client.get(endpoint)
assert res.status_code == 200
# Pagination naturally makes one query per item in the page. Anything
# under `page_size * 2` isn't doing any additional queries per recipe.
page_size = settings.REST_FRAMEWORK["PAGE_SIZE"]
assert len(queries) < page_size * 2, queries
class TestIdenticonAPI(object):
def test_it_works(self, client):
res = client.get("/api/v3/identicon/v1:foobar.svg")
assert res.status_code == 200
def test_it_returns_the_same_output(self, client):
res1 = client.get("/api/v3/identicon/v1:foobar.svg")
res2 = client.get("/api/v3/identicon/v1:foobar.svg")
assert res1.content == res2.content
def test_it_returns_known_output(self, client):
res = client.get("/api/v3/identicon/v1:foobar.svg")
reference_svg = Path(settings.BASE_DIR).joinpath(
"normandy", "recipes", "tests", "api", "v3", "foobar.svg"
)
with open(reference_svg, "rb") as svg_file:
assert svg_file.read() == res.content
def test_includes_cache_headers(self, client):
res = client.get("/api/v3/identicon/v1:foobar.svg")
assert f"max-age={settings.IMMUTABLE_CACHE_TIME}" in res["Cache-Control"]
assert "public" in res["Cache-Control"]
assert "immutable" in res["Cache-Control"]
def test_unrecognized_generation(self, client):
res = client.get("/api/v3/identicon/v9:foobar.svg")
assert res.status_code == 400
assert res.json()["error"] == "Invalid identicon generation, only v1 is supported."
@pytest.mark.django_db
class TestFilterObjects(object):
def make_recipe(self, api_client, **kwargs):
data = {
"name": "Test Recipe",
"action_id": ActionFactory().id,
"arguments": {},
"enabled": True,
}
data.update(kwargs)
return api_client.post("/api/v3/recipe/", data)
def test_bad_filter_objects(self, api_client):
res = self.make_recipe(api_client, filter_object={}) # not a list
assert res.status_code == 400
assert res.json() == {"filter_object": ['Expected a list of items but got type "dict".']}
res = self.make_recipe(api_client, filter_object=["1 + 1 == 2"]) # not a list of objects
assert res.status_code == 400
assert res.json() == {
"filter_object": {
"0": {"non field errors": ["filter_object members must be objects."]}
}
}
res = self.make_recipe(api_client, filter_object=[{"channels": ["release"]}])
assert res.status_code == 400
assert res.json() == {"filter_object": {"0": {"type": ["This field is required."]}}}
def test_channel_works(self, api_client):
channel1 = ChannelFactory(slug="beta")
channel2 = ChannelFactory(slug="release")
res = self.make_recipe(
api_client,
filter_object=[{"type": "channel", "channels": [channel1.slug, channel2.slug]}],
)
assert res.status_code == 201, res.json()
assert res.json()["latest_revision"]["filter_expression"] == (
f'normandy.channel in ["{channel1.slug}","{channel2.slug}"]'
)
def test_channel_correct_fields(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "channel"}])
assert res.status_code == 400
assert res.json() == {"filter_object": {"0": {"channels": ["This field is required."]}}}
def test_locale_works(self, api_client):
locale1 = LocaleFactory()
locale2 = LocaleFactory(code="de")
res = self.make_recipe(
api_client, filter_object=[{"type": "locale", "locales": [locale1.code, locale2.code]}]
)
assert res.status_code == 201, res.json()
assert res.json()["latest_revision"]["filter_expression"] == (
f'normandy.locale in ["{locale1.code}","{locale2.code}"]'
)
def test_locale_correct_fields(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "locale"}])
assert res.status_code == 400
assert res.json() == {"filter_object": {"0": {"locales": ["This field is required."]}}}
def test_country_works(self, api_client):
country1 = CountryFactory()
country2 = CountryFactory(code="DE")
res = self.make_recipe(
api_client,
filter_object=[{"type": "country", "countries": [country1.code, country2.code]}],
)
assert res.status_code == 201, res.json()
assert res.json()["latest_revision"]["filter_expression"] == (
f'normandy.country in ["{country1.code}","{country2.code}"]'
)
def test_country_correct_fields(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "country"}])
assert res.status_code == 400
assert res.json() == {"filter_object": {"0": {"countries": ["This field is required."]}}}
def test_bucket_sample_works(self, api_client):
res = self.make_recipe(
api_client,
filter_object=[
{
"type": "bucketSample",
"start": 1,
"count": 2,
"total": 3,
"input": ["normandy.userId", "normandy.recipeId"],
}
],
)
assert res.status_code == 201, res.json()
assert res.json()["latest_revision"]["filter_expression"] == (
"[normandy.userId,normandy.recipeId]|bucketSample(1,2,3)"
)
def test_bucket_sample_correct_fields(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "bucketSample"}])
assert res.status_code == 400
assert res.json() == {
"filter_object": {
"0": {
"start": ["This field is required."],
"count": ["This field is required."],
"total": ["This field is required."],
"input": ["This field is required."],
}
}
}
res = self.make_recipe(
api_client,
filter_object=[{"type": "bucketSample", "start": "a", "count": -1, "total": -2}],
)
assert res.status_code == 400
assert res.json() == {
"filter_object": {
"0": {
"start": ["A valid number is required."],
"count": ["Ensure this value is greater than or equal to 0."],
"total": ["Ensure this value is greater than or equal to 0."],
"input": ["This field is required."],
}
}
}
def test_stable_sample_works(self, api_client):
res = self.make_recipe(
api_client,
filter_object=[
{
"type": "stableSample",
"rate": 0.5,
"input": ["normandy.userId", "normandy.recipeId"],
}
],
)
assert res.status_code == 201, res.json()
assert res.json()["latest_revision"]["filter_expression"] == (
"[normandy.userId,normandy.recipeId]|stableSample(0.5)"
)
def test_stable_sample_correct_fields(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "stableSample"}])
assert res.status_code == 400
assert res.json() == {
"filter_object": {
"0": {"rate": ["This field is required."], "input": ["This field is required."]}
}
}
res = self.make_recipe(api_client, filter_object=[{"type": "stableSample", "rate": 10}])
assert res.status_code == 400
assert res.json() == {
"filter_object": {
"0": {
"rate": ["Ensure this value is less than or equal to 1."],
"input": ["This field is required."],
}
}
}
def test_version_works(self, api_client):
res = self.make_recipe(
api_client, filter_object=[{"type": "version", "versions": [57, 58, 59, 60]}]
)
assert res.status_code == 201, res.json()
assert res.json()["latest_revision"]["filter_expression"] == (
'(env.version|versionCompare("57.!")>=0)&&' '(env.version|versionCompare("60.*")<0)'
)
def test_version_correct_fields(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "version"}])
assert res.status_code == 400
assert res.json() == {"filter_object": {"0": {"versions": ["This field is required."]}}}
def test_invalid_filter(self, api_client):
res = self.make_recipe(api_client, filter_object=[{"type": "invalid"}])
assert res.status_code == 400
assert res.json() == {
"filter_object": {"0": {"type": ['Unknown filter object type "invalid".']}}
}
@pytest.mark.django_db
class TestFilters(object):
def test_it_works(self, api_client):
country = CountryFactory()
locale = LocaleFactory()
channel = ChannelFactory()
res = api_client.get("/api/v3/filters/")
assert res.status_code == 200, res.json()
assert res.json() == {
"countries": [{"key": country.code, "value": country.name}],
"locales": [{"key": locale.code, "value": locale.name}],
"channels": [{"key": channel.slug, "value": channel.name}],
"status": [
{"key": "enabled", "value": "Enabled"},
{"key": "disabled", "value": "Disabled"},
],
}
| mpl-2.0 |
mozilla/normandy | normandy/recipes/tests/test_checks.py | 1 | 4881 | from datetime import timedelta
from django.core.exceptions import ImproperlyConfigured
from django.db.utils import ProgrammingError
import pytest
import requests.exceptions
from normandy.recipes import checks, signing
from normandy.recipes.tests import ActionFactory, RecipeFactory, SignatureFactory, UserFactory
@pytest.mark.django_db
class TestSignaturesUseGoodCertificates(object):
def test_it_works(self):
assert checks.signatures_use_good_certificates(None) == []
def test_it_fails_if_a_signature_does_not_verify(self, mocker, settings):
settings.CERTIFICATES_EXPIRE_EARLY_DAYS = None
recipe = RecipeFactory(approver=UserFactory(), signed=True)
mock_verify_x5u = mocker.patch("normandy.recipes.checks.signing.verify_x5u")
mock_verify_x5u.side_effect = signing.BadCertificate("testing exception")
errors = checks.signatures_use_good_certificates(None)
mock_verify_x5u.assert_called_once_with(recipe.signature.x5u, None)
assert len(errors) == 1
assert errors[0].id == checks.ERROR_BAD_SIGNING_CERTIFICATE
assert recipe.approved_revision.name in errors[0].msg
def test_it_ignores_signatures_without_x5u(self):
recipe = RecipeFactory(approver=UserFactory(), signed=True)
recipe.signature.x5u = None
recipe.signature.save()
actions = ActionFactory(signed=True)
actions.signature.x5u = None
actions.signature.save()
assert checks.signatures_use_good_certificates(None) == []
def test_it_ignores_signatures_not_in_use(self, mocker, settings):
settings.CERTIFICATES_EXPIRE_EARLY_DAYS = None
recipe = RecipeFactory(approver=UserFactory(), signed=True)
SignatureFactory(x5u="https://example.com/bad_x5u") # unused signature
mock_verify_x5u = mocker.patch("normandy.recipes.checks.signing.verify_x5u")
def side_effect(x5u, *args):
if "bad" in x5u:
raise signing.BadCertificate("testing exception")
return True
mock_verify_x5u.side_effect = side_effect
errors = checks.signatures_use_good_certificates(None)
mock_verify_x5u.assert_called_once_with(recipe.signature.x5u, None)
assert errors == []
def test_it_passes_expire_early_setting(self, mocker, settings):
settings.CERTIFICATES_EXPIRE_EARLY_DAYS = 7
recipe = RecipeFactory(approver=UserFactory(), signed=True)
mock_verify_x5u = mocker.patch("normandy.recipes.checks.signing.verify_x5u")
errors = checks.signatures_use_good_certificates(None)
mock_verify_x5u.assert_called_once_with(recipe.signature.x5u, timedelta(7))
assert errors == []
def test_it_reports_x5u_network_errors(self, mocker):
RecipeFactory(approver=UserFactory(), signed=True)
mock_verify_x5u = mocker.patch("normandy.recipes.checks.signing.verify_x5u")
mock_verify_x5u.side_effect = requests.exceptions.ConnectionError
errors = checks.signatures_use_good_certificates(None)
mock_verify_x5u.assert_called_once()
assert len(errors) == 1
assert errors[0].id == checks.ERROR_COULD_NOT_VERIFY_CERTIFICATE
@pytest.mark.django_db
class TestRecipeSignatureAreCorrect:
def test_it_warns_if_a_field_isnt_available(self, mocker):
"""This is to allow for un-applied to migrations to not break running migrations."""
RecipeFactory(approver=UserFactory(), signed=True)
mock_canonical_json = mocker.patch("normandy.recipes.models.Recipe.canonical_json")
mock_canonical_json.side_effect = ProgrammingError("error for testing")
errors = checks.recipe_signatures_are_correct(None)
assert len(errors) == 1
assert errors[0].id == checks.WARNING_COULD_NOT_CHECK_SIGNATURES
@pytest.mark.django_db
class TestActionSignatureAreCorrect:
def test_it_warns_if_a_field_isnt_available(self, mocker):
"""This is to allow for un-applied to migrations to not break running migrations."""
ActionFactory(signed=True)
mock_canonical_json = mocker.patch("normandy.recipes.models.Action.canonical_json")
mock_canonical_json.side_effect = ProgrammingError("error for testing")
errors = checks.action_signatures_are_correct(None)
assert len(errors) == 1
assert errors[0].id == checks.WARNING_COULD_NOT_CHECK_SIGNATURES
class TestRemoteSettingsConfigIsCorrect:
def test_it_warns_if_remote_settings_config_is_incorrect(self, mocker):
mock_check_config = mocker.patch("normandy.recipes.exports.RemoteSettings.check_config")
mock_check_config.side_effect = ImproperlyConfigured("error for testing")
errors = checks.remotesettings_config_is_correct(None)
assert len(errors) == 1
assert errors[0].id == checks.ERROR_REMOTE_SETTINGS_INCORRECT_CONFIG
| mpl-2.0 |
mozilla/normandy | normandy/recipes/api/filters.py | 1 | 4813 | import django_filters
from rest_framework import serializers
from normandy.recipes.models import Recipe
class EnabledStateFilter(django_filters.Filter):
"""A special case filter for filtering recipes by their enabled state"""
def filter(self, qs, value):
if value is not None:
lc_value = value.lower()
if lc_value in ["true", "1"]:
return qs.only_enabled()
elif lc_value in ["false", "0"]:
return qs.only_disabled()
return qs
class ApprovalStateFilter(django_filters.Filter):
"""A special case filter for filtering approval requests by their approval state"""
def filter(self, qs, value):
if value is None:
return qs
lc_value = value.lower()
if lc_value in ["true", "1", "approved"]:
return qs.filter(approved=True)
elif lc_value in ["false", "0", "rejected"]:
return qs.filter(approved=False)
elif lc_value in ["null", "pending"]:
return qs.filter(approved=None)
class BaselineCapabilitiesFilter(django_filters.Filter):
"""Filters recipe by whether they use only baseline capabilities, defaulting to only baseline."""
def __init__(self, *args, default_only_baseline=False, **kwargs):
super().__init__(*args, **kwargs)
self.default_only_baseline = default_only_baseline
def filter(self, qs, value):
baseline_only = self.default_only_baseline
if value is not None:
lc_value = value.lower()
baseline_only = lc_value in ["true", "1"]
if baseline_only:
recipes = list(qs)
if not all(isinstance(recipe, Recipe) for recipe in recipes):
raise TypeError("BaselineCapabilitiesFilter can only be used to filter recipes")
match_ids = []
for recipe in recipes:
if (
recipe.approved_revision
and recipe.approved_revision.uses_only_baseline_capabilities()
):
match_ids.append(recipe.id)
return Recipe.objects.filter(id__in=match_ids)
return qs
class CharSplitFilter(django_filters.CharFilter):
"""Custom CharFilter class that splits the value (if it's set) by `,` into a list
and uses the `__in` operator."""
def filter(self, qs, value):
if value:
qs = qs.filter(**{"{}__in".format(self.field_name): value.split(",")})
return qs
class FilterObjectFieldFilter(django_filters.Filter):
"""
Find recipes that have a filter object with the given field
Format for the filter's value is `key1:value1,key2:value2`. This would
include recipes that have a filter object that has a field `key1` that
contains the value `value1`, and that have a filter object with a field
`key2` that contains `value2`. The two filter objects do not have to be
the same, but may be.
"""
def filter(self, qs, value):
if value is None:
return qs
needles = []
for segment in value.split(","):
if ":" not in segment:
raise serializers.ValidationError(
{"filter_object": "Filters must be of the format `key1:val1,key2:val2,..."}
)
key, val = segment.split(":", 1)
needles.append((key, val))
# Let the database do a first pass filter
for k, v in needles:
qs = qs.filter(latest_revision__filter_object_json__contains=k)
qs = qs.filter(latest_revision__filter_object_json__contains=v)
recipes = list(qs)
if not all(isinstance(recipe, Recipe) for recipe in recipes):
raise TypeError("FilterObjectFieldFilter can only be used to filter recipes")
# For every recipe that contains the right substrings, look through
# their filter objects for an actual match
match_ids = []
for recipe in recipes:
recipe_matches = True
# Recipes needs to have all the keys and values in the needles
for k, v in needles:
for filter_object in recipe.latest_revision.filter_object:
# Don't consider invalid filter objects
if not filter_object.is_valid():
continue
if k in filter_object.data and v in str(filter_object.data[k]):
# Found a match
break
else:
# Did not break, so no match was not found
recipe_matches = False
break
if recipe_matches:
match_ids.append(recipe.id)
return Recipe.objects.filter(id__in=match_ids)
| mpl-2.0 |
mozilla/normandy | normandy/recipes/migrations/0008_auto_20180510_2252.py | 1 | 1967 | # Generated by Django 2.0.5 on 2018-05-10 22:52
# flake8: noqa
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("recipes", "0007_convert_simple_filters_to_filter_objects"),
]
operations = [
migrations.CreateModel(
name="EnabledState",
fields=[
(
"id",
models.AutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
("created", models.DateTimeField(default=django.utils.timezone.now)),
("enabled", models.BooleanField(default=False)),
(
"creator",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="enabled_states",
to=settings.AUTH_USER_MODEL,
),
),
(
"revision",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="enabled_states",
to="recipes.RecipeRevision",
),
),
],
options={"ordering": ("-created",)},
),
migrations.AddField(
model_name="reciperevision",
name="enabled_state",
field=models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="current_for_revision",
to="recipes.EnabledState",
),
),
]
| mpl-2.0 |
mozilla/normandy | normandy/recipes/exports.py | 1 | 8717 | import logging
import kinto_http
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from normandy.base.utils import ScopedSettings
APPROVE_CHANGES_FLAG = {"status": "to-sign"}
ROLLBACK_CHANGES_FLAG = {"status": "to-rollback"}
logger = logging.getLogger(__name__)
rs_settings = ScopedSettings("REMOTE_SETTINGS_")
def recipe_as_record(recipe):
"""
Transform a recipe to a dict with the minimum amount of fields needed for clients
to verify and execute recipes.
:param recipe: a recipe ready to be exported.
:returns: a dict to be posted on Remote Settings.
"""
from normandy.recipes.api.v1.serializers import (
MinimalRecipeSerializer,
SignatureSerializer,
) # avoid circular imports
record = {
"id": str(recipe.id),
"recipe": MinimalRecipeSerializer(recipe).data,
"signature": SignatureSerializer(recipe.signature).data,
}
return record
class RemoteSettings:
"""
Interacts with a RemoteSettings service.
Recipes get published as records in one or both of the dedicated
collections on Remote Settings. When disabled, those records are removed.
Since Normandy already has the required approval/signoff features, the integration
bypasses the one of Remote Settings (leveraging a specific server configuration for this
particular collection).
There are two collections used. One is the "baseline" collection, which
is used only for recipes that fit within the baseline capabilities, and
are therefore compatible with a broad range of clients. The second is the
"capabilities" collection, in which all recipes are published. Clients
that read from the capabilities collection are expected to process
capabilities and only execute compatible recipes.
.. notes::
Remote Settings signoff workflow relies on several buckets (see kinto-signer API).
The ``main-workspace`` is only readable and writable by authorized accounts.
The ``main`` bucket is read-only, but publicly readable. The Remote Settings
clients pull data from there.
Since the review step is disabled for Normandy, publishing data is done in two steps:
1. Create, update or delete records in the ``main-workspace`` bucket
2. Approve the changes by flipping the ``status`` field to ``to-sign``
in the collection metadata
3. The server will sign and publish the new data to the ``main`` bucket.
"""
def __init__(self):
# Kinto is the underlying implementation of Remote Settings. The client
# is basically a tiny abstraction on top of the requests library.
self.client = (
kinto_http.Client(
server_url=rs_settings.URL,
auth=(rs_settings.USERNAME, rs_settings.PASSWORD),
retry=rs_settings.RETRY_REQUESTS,
)
if rs_settings.URL
else None
)
def check_config(self):
"""
Verify that integration with Remote Settings is configured properly.
"""
if self.client is None:
return # no check if disabled.
required_keys = [
"CAPABILITIES_COLLECTION_ID",
"WORKSPACE_BUCKET_ID",
"PUBLISH_BUCKET_ID",
"USERNAME",
"PASSWORD",
]
for key in required_keys:
if not getattr(settings, f"REMOTE_SETTINGS_{key}"):
msg = f"set settings.REMOTE_SETTINGS_{key} to use Remote Settings integration"
raise ImproperlyConfigured(msg)
# Test authentication.
server_info = self.client.server_info()
is_authenticated = (
"user" in server_info and rs_settings.USERNAME in server_info["user"]["id"]
)
if not is_authenticated:
raise ImproperlyConfigured("Invalid Remote Settings credentials")
# Test that collection is writable.
bucket = rs_settings.WORKSPACE_BUCKET_ID
collection = rs_settings.CAPABILITIES_COLLECTION_ID
metadata = self.client.get_collection(id=collection, bucket=bucket)
if server_info["user"]["id"] not in metadata["permissions"].get("write", []):
raise ImproperlyConfigured(
f"Remote Settings collection {collection} is not writable in bucket {bucket}."
)
# Test that collection has the proper review settings.
capabilities = server_info["capabilities"]
if "signer" in capabilities:
signer_config = capabilities["signer"]
normandy_resource = [
r
for r in signer_config["resources"]
if r["source"]["bucket"] == bucket and r["source"]["collection"] == collection
]
review_disabled = len(normandy_resource) == 1 and not normandy_resource[0].get(
"to_review_enabled", signer_config["to_review_enabled"]
)
if not review_disabled:
raise ImproperlyConfigured(
f"Review was not disabled on Remote Settings collection {collection}."
)
def published_recipes(self):
"""
Return the current list of remote records.
"""
if self.client is None:
raise ImproperlyConfigured("Remote Settings is not enabled.")
capabilities_records = self.client.get_records(
bucket=rs_settings.PUBLISH_BUCKET_ID, collection=rs_settings.CAPABILITIES_COLLECTION_ID
)
return capabilities_records
def publish(self, recipe, approve_changes=True):
"""
Publish the specified `recipe` on the remote server by upserting a record.
"""
if self.client is None:
return # no-op if disabled.
# 1. Put the record.
record = recipe_as_record(recipe)
self.client.update_record(
data=record,
bucket=rs_settings.WORKSPACE_BUCKET_ID,
collection=rs_settings.CAPABILITIES_COLLECTION_ID,
)
# 2. Approve the changes immediately (multi-signoff is disabled).
log_action = "Batch published"
if approve_changes:
self.approve_changes()
log_action = "Published"
logger.info(
f"{log_action} record '{recipe.id}' for recipe {recipe.approved_revision.name!r}"
)
def unpublish(self, recipe, approve_changes=True):
"""
Unpublish the specified `recipe` by deleted its associated record on the remote server.
"""
if self.client is None:
return # no-op if disabled.
# 1. Delete the record
either_existed = False
try:
self.client.delete_record(
id=str(recipe.id),
bucket=rs_settings.WORKSPACE_BUCKET_ID,
collection=rs_settings.CAPABILITIES_COLLECTION_ID,
)
either_existed = True
except kinto_http.KintoException as e:
if e.response.status_code == 404:
logger.warning(
f"The recipe '{recipe.id}' was not published in the capabilities collection. Skip."
)
else:
raise
# 2. Approve the changes immediately (multi-signoff is disabled).
log_action = "Batch deleted"
if either_existed and approve_changes:
self.approve_changes()
log_action = "Deleted"
logger.info(
f"{log_action} record '{recipe.id}' of recipe {recipe.approved_revision.name!r}"
)
def approve_changes(self):
"""
Approve the changes made in the workspace collection.
.. note::
This only works because multi-signoff is disabled for the Normandy recipes
in configuration (see :ref:`remote-settings-install`)
"""
if self.client is None:
return # no-op if disabled.
try:
self.client.patch_collection(
id=rs_settings.CAPABILITIES_COLLECTION_ID,
data=APPROVE_CHANGES_FLAG,
bucket=rs_settings.WORKSPACE_BUCKET_ID,
)
logger.info("Changes were approved.")
except kinto_http.exceptions.KintoException:
# Approval failed unexpectedly.
# The changes in the `main-workspace` bucket must be reverted.
self.client.patch_collection(
id=rs_settings.CAPABILITIES_COLLECTION_ID,
data=ROLLBACK_CHANGES_FLAG,
bucket=rs_settings.WORKSPACE_BUCKET_ID,
)
raise
| mpl-2.0 |
mozilla/normandy | normandy/recipes/tests/test_filters.py | 1 | 25613 | from datetime import datetime
import factory.fuzzy
import pytest
import re
from collections import defaultdict
from rest_framework import serializers
from normandy.base.jexl import get_normandy_jexl
from normandy.recipes import filters
from normandy.recipes.tests import (
ChannelFactory,
CountryFactory,
LocaleFactory,
RecipeRevisionFactory,
WindowsVersionFactory,
)
@pytest.mark.django_db
class FilterTestsBase:
"""Common tests for all filter object types"""
should_be_baseline = True
def create_basic_filter(self):
"""To be overwritten by subclasses to create test filters"""
raise NotImplementedError
def create_revision(self, *args, **kwargs):
return RecipeRevisionFactory(*args, **kwargs)
def test_it_can_be_constructed(self):
self.create_basic_filter()
def test_has_capabilities(self):
filter = self.create_basic_filter()
# Would throw if not defined
assert isinstance(filter.get_capabilities(), set)
def test_jexl_works(self):
filter = self.create_basic_filter()
rev = self.create_revision()
# Would throw if not defined
expr = filter.to_jexl(rev)
assert isinstance(expr, str)
jexl = get_normandy_jexl()
errors = jexl.validate(expr)
assert list(errors) == []
def test_uses_only_baseline_capabilities(self, settings):
if self.should_be_baseline == "skip":
return
filter = self.create_basic_filter()
capabilities = filter.get_capabilities()
if self.should_be_baseline:
assert capabilities <= settings.BASELINE_CAPABILITIES
else:
assert capabilities - settings.BASELINE_CAPABILITIES
def test_it_is_in_the_by_type_list(self):
filter_instance = self.create_basic_filter()
filter_class = filter_instance.__class__
assert filter_class in filters.by_type.values()
def test_its_type_is_camelcase(self):
filter_instance = self.create_basic_filter()
assert re.match("[a-zA-Z]+", filter_instance.type)
assert "_" not in filter_instance.type
class TestProfileCreationDateFilter(FilterTestsBase):
def create_basic_filter(self, direction="olderThan", date="2020-02-01"):
return filters.ProfileCreateDateFilter.create(direction=direction, date=date)
def test_generates_jexl_older_than(self):
filter = self.create_basic_filter(direction="olderThan", date="2020-07-30")
assert (
filter.to_jexl(self.create_revision())
== "(normandy.telemetry.main.environment.profile.creationDate<=18473)"
)
def test_generates_jexl_newer_than(self):
filter = self.create_basic_filter(direction="newerThan", date="2020-02-01")
assert set(filter.to_jexl(self.create_revision()).split("||")) == {
"(!normandy.telemetry.main)",
"(normandy.telemetry.main.environment.profile.creationDate>18293)",
}
def test_issue_2242(self):
"""Make sure that dates are parsed correctly"""
epoch = datetime.utcfromtimestamp(0)
datetime_factory = factory.fuzzy.FuzzyNaiveDateTime(epoch)
dt = datetime_factory.fuzz()
# Profile Creation Date is measured in days since epoch.
daystamp = (dt - epoch).days
filter = self.create_basic_filter(date=f"{dt.year}-{dt.month}-{dt.day}")
assert str(daystamp) in filter.to_jexl(self.create_revision())
def test_throws_error_on_bad_direction(self):
filter = self.create_basic_filter(direction="newer", date="2020-02-01")
with pytest.raises(serializers.ValidationError):
filter.to_jexl(self.create_revision())
def test_throws_error_on_bad_date(self):
with pytest.raises(AssertionError):
self.create_basic_filter(direction="newerThan", date="Jan 7, 2020")
class TestVersionFilter(FilterTestsBase):
should_be_baseline = False
def create_basic_filter(self, versions=None):
if versions is None:
versions = [72, 74]
return filters.VersionFilter.create(versions=versions)
def test_generates_jexl(self):
filter = self.create_basic_filter(versions=[72, 74])
assert set(filter.to_jexl(self.create_revision()).split("||")) == {
'(env.version|versionCompare("72.!")>=0)&&(env.version|versionCompare("72.*")<0)',
'(env.version|versionCompare("74.!")>=0)&&(env.version|versionCompare("74.*")<0)',
}
class TestVersionRangeFilter(FilterTestsBase):
should_be_baseline = False
def create_basic_filter(self, min_version="72.0b2", max_version="72.0b8"):
return filters.VersionRangeFilter.create(min_version=min_version, max_version=max_version)
def test_generates_jexl(self):
filter = self.create_basic_filter(min_version="72.0b2", max_version="75.0a1")
assert set(filter.to_jexl(self.create_revision()).split("&&")) == {
'(env.version|versionCompare("72.0b2")>=0)',
'(env.version|versionCompare("75.0a1")<0)',
}
class TestDateRangeFilter(FilterTestsBase):
def create_basic_filter(
self, not_before="2020-02-01T00:00:00Z", not_after="2020-03-01T00:00:00Z"
):
return filters.DateRangeFilter.create(not_before=not_before, not_after=not_after)
def test_generates_jexl(self):
filter = self.create_basic_filter()
assert set(filter.to_jexl(self.create_revision()).split("&&")) == {
'(normandy.request_time>="2020-02-01T00:00:00Z"|date)',
'(normandy.request_time<"2020-03-01T00:00:00Z"|date)',
}
class TestWindowsBuildNumberFilter(FilterTestsBase):
def create_basic_filter(self, value=12345, comparison="equal"):
return filters.WindowsBuildNumberFilter.create(value=value, comparison=comparison)
@pytest.mark.parametrize(
"comparison,symbol",
[
("equal", "=="),
("greater_than", ">"),
("greater_than_equal", ">="),
("less_than", "<"),
("less_than_equal", "<="),
],
)
def test_generates_jexl_number_ops(self, comparison, symbol):
filter = self.create_basic_filter(comparison=comparison)
assert (
filter.to_jexl(self.create_revision())
== f"(normandy.os.isWindows && normandy.os.windowsBuildNumber {symbol} 12345)"
)
def test_generates_jexl_error_on_bad_comparison(self):
filter = self.create_basic_filter(comparison="typo")
with pytest.raises(serializers.ValidationError):
filter.to_jexl(self.create_revision())
class TestWindowsVersionFilter(FilterTestsBase):
def create_basic_filter(self, versions_list=[6.1]):
WindowsVersionFactory(nt_version=6.1)
return filters.WindowsVersionFilter.create(versions_list=versions_list)
def test_generates_jexl(self):
filter = self.create_basic_filter()
assert (
filter.to_jexl(self.create_revision())
== "(normandy.os.isWindows && normandy.os.windowsVersion in [6.1])"
)
def test_generates_jexl_error_on_bad_version(self):
with pytest.raises(AssertionError):
filters.WindowsVersionFilter.create(versions_list=[8.9])
class TestChannelFilter(FilterTestsBase):
def create_basic_filter(self, channels=None):
if channels:
channel_objs = [ChannelFactory(slug=slug) for slug in channels]
else:
channel_objs = [ChannelFactory()]
return filters.ChannelFilter.create(channels=[c.slug for c in channel_objs])
def test_generates_jexl(self):
filter = self.create_basic_filter(channels=["release", "beta"])
assert filter.to_jexl(self.create_revision()) == 'normandy.channel in ["release","beta"]'
class TestLocaleFilter(FilterTestsBase):
def create_basic_filter(self, locales=None):
if locales:
locale_objs = [LocaleFactory(code=code) for code in locales]
else:
locale_objs = [LocaleFactory()]
return filters.LocaleFilter.create(locales=[locale.code for locale in locale_objs])
def test_generates_jexl(self):
filter = self.create_basic_filter(locales=["en-US", "en-CA"])
assert filter.to_jexl(self.create_revision()) == 'normandy.locale in ["en-US","en-CA"]'
class TestCountryFilter(FilterTestsBase):
def create_basic_filter(self, countries=None):
if countries:
country_objs = [CountryFactory(code=code) for code in countries]
else:
country_objs = [CountryFactory()]
return filters.CountryFilter.create(countries=[c.code for c in country_objs])
def test_generates_jexl(self):
filter = self.create_basic_filter(countries=["SV", "MX"])
assert filter.to_jexl(self.create_revision()) == 'normandy.country in ["SV","MX"]'
class TestPlatformFilter(FilterTestsBase):
def create_basic_filter(self, platforms=["all_mac", "all_windows"]):
return filters.PlatformFilter.create(platforms=platforms)
def test_generates_jexl_list_of_two(self):
filter = self.create_basic_filter()
assert set(filter.to_jexl(self.create_revision()).split("||")) == {
"normandy.os.isMac",
"normandy.os.isWindows",
}
def test_generates_jexl_list_of_one(self):
filter = self.create_basic_filter(platforms=["all_linux"])
assert set(filter.to_jexl(self.create_revision()).split("||")) == {"normandy.os.isLinux"}
def test_throws_error_on_bad_platform(self):
filter = self.create_basic_filter(platforms=["all_linu"])
with pytest.raises(serializers.ValidationError):
filter.to_jexl(self.create_revision())
class TestNegateFilter(FilterTestsBase):
def create_basic_filter(self):
data_for_filter = {"type": "channel", "channels": ["release", "beta"]}
return filters.NegateFilter.create(filter_to_negate=data_for_filter)
def test_generates_jexl(self):
negate_filter = self.create_basic_filter()
assert (
negate_filter.to_jexl(self.create_revision())
== '!(normandy.channel in ["release","beta"])'
)
class TestAndFilter(FilterTestsBase):
def create_basic_filter(self, subfilters=None):
if subfilters is None:
subfilters = [
{"type": "channel", "channels": ["release", "beta"]},
{"type": "locale", "locales": ["en-US", "de"]},
]
return filters.AndFilter.create(subfilters=subfilters)
def test_generates_jexl_zero_subfilters(self):
with pytest.raises(AssertionError) as excinfo:
self.create_basic_filter(subfilters=[])
assert "has at least 1 element" in str(excinfo.value)
def test_generates_jexl_one_subfilter(self):
negate_filter = self.create_basic_filter(
subfilters=[{"type": "channel", "channels": ["release"]}]
)
assert negate_filter.to_jexl(self.create_revision()) == '(normandy.channel in ["release"])'
def test_generates_jexl_two_subfilters(self):
negate_filter = self.create_basic_filter(
subfilters=[
{"type": "channel", "channels": ["release"]},
{"type": "locale", "locales": ["en-US"]},
]
)
assert (
negate_filter.to_jexl(self.create_revision())
== '(normandy.channel in ["release"]&&normandy.locale in ["en-US"])'
)
class TestOrFilter(FilterTestsBase):
def create_basic_filter(self, subfilters=None):
if subfilters is None:
subfilters = [
{"type": "channel", "channels": ["release", "beta"]},
{"type": "locale", "locales": ["en-US", "de"]},
]
return filters.OrFilter.create(subfilters=subfilters)
def test_generates_jexl_zero_subfilters(self):
with pytest.raises(AssertionError) as excinfo:
self.create_basic_filter(subfilters=[])
assert "has at least 1 element" in str(excinfo.value)
def test_generates_jexl_one_subfilter(self):
negate_filter = self.create_basic_filter(
subfilters=[{"type": "channel", "channels": ["release"]}]
)
assert negate_filter.to_jexl(self.create_revision()) == '(normandy.channel in ["release"])'
def test_generates_jexl_two_subfilters(self):
negate_filter = self.create_basic_filter(
subfilters=[
{"type": "channel", "channels": ["release"]},
{"type": "locale", "locales": ["en-US"]},
]
)
assert (
negate_filter.to_jexl(self.create_revision())
== '(normandy.channel in ["release"]||normandy.locale in ["en-US"])'
)
class TestAddonInstalledFilter(FilterTestsBase):
def create_basic_filter(self, addons=["@abcdef", "ghijk@lmnop"], any_or_all="any"):
return filters.AddonInstalledFilter.create(addons=addons, any_or_all=any_or_all)
def test_generates_jexl_installed_any(self):
filter = self.create_basic_filter()
assert set(filter.to_jexl(self.create_revision()).split("||")) == {
'normandy.addons["@abcdef"]',
'normandy.addons["ghijk@lmnop"]',
}
def test_generates_jexl_installed_all(self):
filter = self.create_basic_filter(any_or_all="all")
assert set(filter.to_jexl(self.create_revision()).split("&&")) == {
'normandy.addons["@abcdef"]',
'normandy.addons["ghijk@lmnop"]',
}
def test_throws_error_on_bad_any_or_all(self):
filter = self.create_basic_filter(any_or_all="error")
with pytest.raises(serializers.ValidationError):
filter.to_jexl(self.create_revision())
class TestAddonActiveFilter(FilterTestsBase):
def create_basic_filter(self, addons=["@abcdef", "ghijk@lmnop"], any_or_all="any"):
return filters.AddonActiveFilter.create(addons=addons, any_or_all=any_or_all)
def test_generates_jexl_active_any(self):
filter = self.create_basic_filter()
assert set(filter.to_jexl(self.create_revision()).split("||")) == {
'normandy.addons["@abcdef"].isActive',
'normandy.addons["ghijk@lmnop"].isActive',
}
def test_generates_jexl_active_all(self):
filter = self.create_basic_filter(any_or_all="all")
assert set(filter.to_jexl(self.create_revision()).split("&&")) == {
'normandy.addons["@abcdef"].isActive',
'normandy.addons["ghijk@lmnop"].isActive',
}
def test_throws_error_on_bad_any_or_all(self):
filter = self.create_basic_filter(any_or_all="error")
with pytest.raises(serializers.ValidationError):
filter.to_jexl(self.create_revision())
class TestPrefCompareFilter(FilterTestsBase):
def create_basic_filter(
self, pref="browser.urlbar.maxRichResults", value=10, comparison="equal"
):
return filters.PrefCompareFilter.create(pref=pref, value=value, comparison=comparison)
def test_generates_jexl(self):
filter = self.create_basic_filter()
assert (
filter.to_jexl(self.create_revision())
== "'browser.urlbar.maxRichResults'|preferenceValue == 10"
)
@pytest.mark.parametrize(
"comparison,symbol",
[
("greater_than", ">"),
("greater_than_equal", ">="),
("less_than", "<"),
("less_than_equal", "<="),
],
)
def test_generates_jexl_number_ops(self, comparison, symbol):
filter = self.create_basic_filter(comparison=comparison)
assert (
filter.to_jexl(self.create_revision())
== f"'browser.urlbar.maxRichResults'|preferenceValue {symbol} 10"
)
def test_generates_jexl_boolean(self):
filter = self.create_basic_filter(value=False)
assert (
filter.to_jexl(self.create_revision())
== "'browser.urlbar.maxRichResults'|preferenceValue == false"
)
def test_generates_jexl_string_in(self):
filter = self.create_basic_filter(value="default", comparison="contains")
assert (
filter.to_jexl(self.create_revision())
== "\"default\" in 'browser.urlbar.maxRichResults'|preferenceValue"
)
def test_generates_jexl_error(self):
filter = self.create_basic_filter(comparison="invalid")
with pytest.raises(serializers.ValidationError):
filter.to_jexl(self.create_revision())
class TestPrefExistsFilter(FilterTestsBase):
def create_basic_filter(self, pref="browser.urlbar.maxRichResults", value=True):
return filters.PrefExistsFilter.create(pref=pref, value=value)
def test_generates_jexl_pref_exists_true(self):
filter = self.create_basic_filter()
assert (
filter.to_jexl(self.create_revision())
== "'browser.urlbar.maxRichResults'|preferenceExists"
)
def test_generates_jexl_pref_exists_false(self):
filter = self.create_basic_filter(value=False)
assert (
filter.to_jexl(self.create_revision())
== "!('browser.urlbar.maxRichResults'|preferenceExists)"
)
class TestPrefUserSetFilter(FilterTestsBase):
def create_basic_filter(self, pref="browser.urlbar.maxRichResults", value=True):
return filters.PrefUserSetFilter.create(pref=pref, value=value)
def test_generates_jexl_is_user_set_true(self):
filter = self.create_basic_filter()
assert (
filter.to_jexl(self.create_revision())
== "'browser.urlbar.maxRichResults'|preferenceIsUserSet"
)
def test_generates_jexl_is_user_set_false(self):
filter = self.create_basic_filter(value=False)
assert (
filter.to_jexl(self.create_revision())
== "!('browser.urlbar.maxRichResults'|preferenceIsUserSet)"
)
class TestBucketSampleFilter(FilterTestsBase):
def create_basic_filter(self, input=None, start=123, count=10, total=1_000):
if input is None:
input = ["normandy.clientId"]
return filters.BucketSampleFilter.create(
input=input, start=start, count=count, total=total
)
def test_generates_jexl(self):
filter = self.create_basic_filter(input=["A"], start=10, count=20, total=1_000)
assert filter.to_jexl(self.create_revision()) == "[A]|bucketSample(10,20,1000)"
def test_supports_floats(self):
filter = self.create_basic_filter(input=["A"], start=10, count=0.5, total=1_000)
assert filter.to_jexl(self.create_revision()) == "[A]|bucketSample(10,0.5,1000)"
class TestStableSampleFilter(FilterTestsBase):
def create_basic_filter(self, input=None, rate=0.01):
if input is None:
input = ["normandy.clientId"]
return filters.StableSampleFilter.create(input=input, rate=rate)
def test_generates_jexl(self):
filter = self.create_basic_filter(input=["A"], rate=0.1)
assert filter.to_jexl(self.create_revision()) == "[A]|stableSample(0.1)"
class TestNamespaceSampleFilter(FilterTestsBase):
def create_basic_filter(self, namespace="global-v42", start=123, count=10):
return filters.NamespaceSampleFilter.create(namespace=namespace, start=start, count=count)
def test_generates_jexl(self):
filter = self.create_basic_filter(namespace="fancy-rollout", start=10, count=20)
assert (
filter.to_jexl(self.create_revision())
== '["fancy-rollout",normandy.userId]|bucketSample(10,20,10000)'
)
def test_supports_floats(self):
filter = self.create_basic_filter(namespace="risky-experiment", start=123, count=0.5)
assert (
filter.to_jexl(self.create_revision())
== '["risky-experiment",normandy.userId]|bucketSample(123,0.5,10000)'
)
class TestJexlFilter(FilterTestsBase):
should_be_baseline = "skip"
def create_basic_filter(self, expression="true", capabilities=None, comment="a comment"):
if capabilities is None:
capabilities = ["capabilities-v1"]
return filters.JexlFilter.create(
expression=expression, capabilities=capabilities, comment=comment
)
def test_generates_jexl(self):
filter = self.create_basic_filter(expression="2 + 2")
assert filter.to_jexl(self.create_revision()) == "(2 + 2)"
def test_it_rejects_invalid_jexl(self):
filter = self.create_basic_filter(expression="this is an invalid expression")
with pytest.raises(serializers.ValidationError):
filter.to_jexl(self.create_revision())
def test_it_has_capabilities(self):
filter = self.create_basic_filter(capabilities=["a.b", "c.d"])
assert filter.get_capabilities() == {"a.b", "c.d"}
def test_empty_capabilities_is_ok(self):
filter = self.create_basic_filter(capabilities=[])
assert filter.get_capabilities() == set()
filter.to_jexl(None) # should not throw
def test_throws_error_on_non_iterable_capabilities(self):
with pytest.raises(AssertionError) as excinfo:
self.create_basic_filter(capabilities=5)
assert excinfo.value.args[0]["capabilities"][0].code == "not_a_list"
def test_throws_error_on_non_list_capabilities(self):
with pytest.raises(AssertionError) as excinfo:
self.create_basic_filter(capabilities="a mistake")
assert excinfo.value.args[0]["capabilities"][0].code == "not_a_list"
class TestPresetFilter(FilterTestsBase):
def create_basic_filter(self, name="pocket-1"):
return filters.PresetFilter.create(name=name)
def test_all_choices_have_generators(self):
f = filters.PresetFilter()
choices = f.preset_choices
for choice in choices:
identifier = choice.replace("-", "_")
generator_name = f"_get_subfilters_{identifier}"
getattr(f, generator_name)()
def test_pocket_1(self):
filter_object = self.create_basic_filter(name="pocket-1")
# The preset is an and filter
assert filter_object._get_operator() == "&&"
# Pull out the first level subfilters
subfilters = defaultdict(lambda: [])
for filter in filter_object._get_subfilters():
subfilters[type(filter)].append(filter)
# There should be one or filter
or_filters = subfilters.pop(filters.OrFilter)
assert len(or_filters) == 1
or_subfilters = or_filters[0]._get_subfilters()
# It should be made up of negative PrefUserSet filters
for f in or_subfilters:
assert isinstance(f, filters.PrefUserSetFilter)
assert f.initial_data["value"] is False
# And it should use the exected prefs
assert set(f.initial_data["pref"] for f in or_subfilters) == set(
["browser.newtabpage.enabled", "browser.startup.homepage"]
)
# There should be a bunch more negative PrefUserSet filters at the top level
pref_subfilters = subfilters.pop(filters.PrefUserSetFilter)
for f in pref_subfilters:
assert f.initial_data["value"] is False
# and they should be the expected prefs
assert set(f.initial_data["pref"] for f in pref_subfilters) == set(
[
"browser.newtabpage.activity-stream.showSearch",
"browser.newtabpage.activity-stream.feeds.topsites",
"browser.newtabpage.activity-stream.feeds.section.topstories",
"browser.newtabpage.activity-stream.feeds.section.highlights",
]
)
# There should be no other filters
assert subfilters == {}, "no unexpected filters"
class TestQaOnlyFilter(FilterTestsBase):
def create_basic_filter(self):
return filters.QaOnlyFilter.create()
def create_revision(self, *args, **kwargs):
kwargs.setdefault("action__name", "multi-preference-experiment")
return super().create_revision(*args, **kwargs)
def test_it_works_for_multi_preference_experiment(self):
rev = self.create_revision(action__name="multi-preference-experiment")
filter = self.create_basic_filter()
slug = rev.arguments["slug"]
assert (
filter.to_jexl(rev)
== f"\"{slug}\" in 'app.normandy.testing-for-recipes'|preferenceValue"
)
def test_it_works_for_branched_addon_study(self):
rev = self.create_revision(action__name="branched-addon-study")
filter = self.create_basic_filter()
slug = rev.arguments["slug"]
assert (
filter.to_jexl(rev)
== f"\"{slug}\" in 'app.normandy.testing-for-recipes'|preferenceValue"
)
def test_it_works_for_preference_rollout(self):
rev = self.create_revision(action__name="preference-rollout")
filter = self.create_basic_filter()
slug = rev.arguments["slug"]
assert (
filter.to_jexl(rev)
== f"\"{slug}\" in 'app.normandy.testing-for-recipes'|preferenceValue"
)
def test_it_works_for_heartbeat(self):
rev = self.create_revision(action__name="show-heartbeat")
filter = self.create_basic_filter()
slug = rev.arguments["surveyId"]
assert (
filter.to_jexl(rev)
== f"\"{slug}\" in 'app.normandy.testing-for-recipes'|preferenceValue"
)
| mpl-2.0 |
mozilla/normandy | normandy/recipes/migrations/0009_auto_20180510_2328.py | 1 | 1037 | # Generated by Django 2.0.5 on 2018-05-10 23:28
from django.db import migrations
def enabled_to_enabled_state(apps, schema_editor):
Recipe = apps.get_model("recipes", "Recipe")
EnabledState = apps.get_model("recipes", "EnabledState")
for recipe in Recipe.objects.filter(enabled=True):
if recipe.approved_revision:
es = EnabledState.objects.create(revision=recipe.approved_revision, enabled=True)
es.current_for_revision.add(recipe.approved_revision)
def enabled_state_to_enabled(apps, schema_editor):
Recipe = apps.get_model("recipes", "Recipe")
for recipe in Recipe.objects.exclude(approved_revision=None):
enabled_state = recipe.approved_revision.enabled_state
if enabled_state and enabled_state.enabled:
recipe.enabled = True
recipe.save()
class Migration(migrations.Migration):
dependencies = [("recipes", "0008_auto_20180510_2252")]
operations = [migrations.RunPython(enabled_to_enabled_state, enabled_state_to_enabled)]
| mpl-2.0 |
mozilla/normandy | normandy/studies/tests/__init__.py | 1 | 4038 | import factory
import json
import tempfile
import zipfile
from factory.django import DjangoModelFactory
from faker import Faker
from normandy.base.tests import FuzzyUnicode
from normandy.studies.models import Extension
INSTALL_RDF_TEMPLATE = """<?xml version="1.0" encoding="utf-8"?>
<RDF xmlns="http://w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://mozilla.org/2004/em-rdf#">
<Description about="urn:mozilla:install-manifest">
<em:type>2</em:type>
<em:bootstrap>true</em:bootstrap>
<em:unpack>false</em:unpack>
<em:multiprocessCompatible>true</em:multiprocessCompatible>
{}
<em:targetApplication>
<Description>
<em:id>{{ec8030f7-c20a-464f-9b0e-13a3a9e97384}}</em:id>
<em:minVersion>52.0</em:minVersion>
<em:maxVersion>*</em:maxVersion>
</Description>
</em:targetApplication>
</Description>
</RDF>
"""
class XPIFileFactory(object):
def __init__(self, signed=True):
# Generate a unique random path for the new XPI file
f, self._path = tempfile.mkstemp(suffix=".xpi")
# Create a blank zip file on disk
zf = zipfile.ZipFile(self.path, mode="w")
zf.close()
if signed:
self.add_file("META-INF/manifest.mf", b"")
self.add_file("META-INF/mozilla.rsa", b"")
self.add_file("META-INF/mozilla.sf", b"")
@property
def path(self):
return self._path
def add_file(self, filename, data):
with zipfile.ZipFile(self.path, mode="a") as zf:
with zf.open(filename, mode="w") as f:
f.write(data)
def open(self, mode="rb"):
return open(self.path, mode="rb")
class WebExtensionFileFactory(XPIFileFactory):
def __init__(self, signed=True, from_file=None, gecko_id=None, overwrite_data=None):
super().__init__(signed=signed)
if not gecko_id:
gecko_id = f"{Faker().md5()}@normandy.mozilla.org"
if from_file:
self._manifest = json.load(from_file)
else:
self._manifest = {
"manifest_version": 2,
"name": "normandy test addon",
"version": "0.1",
"description": "This is an add-on for us in Normandy's tests",
"applications": {"gecko": {"id": gecko_id}},
}
if overwrite_data:
self._manifest.update(overwrite_data)
self.save_manifest()
@property
def manifest(self):
return self._manifest
def save_manifest(self):
self.add_file("manifest.json", json.dumps(self.manifest).encode())
def update_manifest(self, data):
self._manifest.update(data)
self.save_manifest()
def replace_manifest(self, data):
self._manifest = data
self.save_manifest()
class LegacyAddonFileFactory(XPIFileFactory):
def __init__(self, signed=True, from_file=None, addon_id=None, overwrite_data=None):
super().__init__(signed=signed)
if not addon_id:
name = Faker().md5()
addon_id = f"{name}@normandy.mozilla.org"
if from_file:
with open(from_file, "rb") as f:
self.add_file("install.rdf", f.read())
else:
data = {
"id": addon_id,
"version": "0.1",
"name": "Signed Bootstrap Mozilla Extension Example",
"description": "Example of a bootstrapped addon",
}
if overwrite_data:
data.update(overwrite_data)
self.generate_install_rdf(data)
def generate_install_rdf(self, data):
insert = ""
for k in data:
insert += "<em:{}>{}</em:{}>\n".format(k, data[k], k)
self.add_file("install.rdf", INSTALL_RDF_TEMPLATE.format(insert).encode())
class ExtensionFactory(DjangoModelFactory):
name = FuzzyUnicode()
xpi = factory.django.FileField(from_func=lambda: WebExtensionFileFactory().open())
class Meta:
model = Extension
| mpl-2.0 |
mozilla/normandy | normandy/recipes/management/commands/initial_data.py | 1 | 1928 | from django.core.management.base import BaseCommand
from django_countries import countries
from normandy.recipes.models import Channel, Country, WindowsVersion
class Command(BaseCommand):
"""
Adds some helpful initial data to the site's database. If matching
data already exists, it should _not_ be overwritten, making this
safe to run multiple times.
This exists instead of data migrations so that test runs do not load
this data into the test database.
If this file grows too big, we should consider finding a library or
coming up with a more robust way of adding this data.
"""
help = "Adds initial data to database"
def handle(self, *args, **options):
self.add_release_channels()
self.add_countries()
self.add_windows_versions()
def add_release_channels(self):
self.stdout.write("Adding Release Channels...", ending="")
channels = {
"release": "Release",
"beta": "Beta",
"aurora": "Developer Edition",
"nightly": "Nightly",
}
for slug, name in channels.items():
Channel.objects.update_or_create(slug=slug, defaults={"name": name})
self.stdout.write("Done")
def add_countries(self):
self.stdout.write("Adding Countries...", ending="")
for code, name in countries:
Country.objects.update_or_create(code=code, defaults={"name": name})
self.stdout.write("Done")
def add_windows_versions(self):
self.stdout.write("Adding Windows Versions...", ending="")
versions = [
(6.1, "Windows 7"),
(6.2, "Windows 8"),
(6.3, "Windows 8.1"),
(10.0, "Windows 10"),
]
for nt_version, name in versions:
WindowsVersion.objects.update_or_create(nt_version=nt_version, defaults={"name": name})
self.stdout.write("Done")
| mpl-2.0 |
mozilla/normandy | normandy/base/tests/test_storage.py | 1 | 1594 | from itertools import chain
import pytest
from django.core.files.base import ContentFile
from normandy.base.storage import PermissiveFilenameStorageMixin
class TestPermissiveFilenameStorageMixin(object):
@pytest.fixture
def storage(self):
return PermissiveFilenameStorageMixin()
class TestGetValidName(object):
def test_it_works(self, storage):
assert storage.get_valid_name("simple-name") == "simple-name"
def test_it_removes_whitespace(self, storage):
assert storage.get_valid_name(" hello world ") == "hello_world"
def test_it_removes_some_special_chars(self, storage):
assert (
storage.get_valid_name("""special \\^`<>{}[]#%"'~|[]*? characters""")
== "special_characters"
)
def test_it_removes_non_printable_ascii_characters(self, storage):
for c in chain(range(32), range(127, 256)):
assert storage.get_valid_name(chr(c)) == ""
def test_it_allows_an_addon_filename(self, storage):
addon_filename = "shield-recipe-client@mozilla.org-82.1.g32b36827-signed.xpi"
assert storage.get_valid_name(addon_filename) == addon_filename
class TestRestrictedOverwriteFilenameStorageMixin(object):
def test_get_available_name(self, storage):
assert storage.get_available_name("tmp/f00") == "tmp/f00"
def test_file_exists(self, storage):
storage.save("tmp/foo", ContentFile(b""))
with pytest.raises(FileExistsError):
storage.get_available_name("tmp/foo")
| mpl-2.0 |
mozilla/normandy | contract-tests/v1_api/test_performance.py | 1 | 3083 | from urllib.parse import urljoin
import html5lib
import pytest
"""These are paths hit by self repair that need to be very fast"""
HOT_PATHS = [
"/en-US/repair",
"/en-US/repair/",
"/api/v1/recipe/?enabled=1",
"/api/v1/recipe/signed/?enabled=1",
"/api/v1/action/",
]
@pytest.mark.parametrize("path", HOT_PATHS)
class TestHotPaths(object):
"""
Test for performance-enhancing properties of the site.
This file does not test performance by measuring runtimes and throughput.
Instead it tests for markers of features that would speed up or slow down the
site, such as cache headers.
"""
def test_no_redirects(self, conf, requests_session, path):
r = requests_session.get(conf.getoption("server") + path)
r.raise_for_status()
assert 200 <= r.status_code < 300
def test_no_vary_cookie(self, conf, requests_session, path, only_readonly):
r = requests_session.get(conf.getoption("server") + path)
r.raise_for_status()
assert "cookie" not in r.headers.get("vary", "").lower()
def test_cache_headers(self, conf, requests_session, path, only_readonly):
if path.startswith("/api/"):
pytest.xfail("caching temporarily hidden on api by nginx")
r = requests_session.get(conf.getoption("server") + path)
r.raise_for_status()
cache_control = r.headers.get("cache-control")
assert cache_control is not None
# parse cache-control header.
parts = [part.strip() for part in cache_control.split(",")]
max_age = [part for part in parts if part.startswith("max-age=")][0]
max_age_seconds = int(max_age.split("=")[1])
assert "public" in parts
assert max_age_seconds > 0
def test_static_cache_headers(conf, requests_session):
"""Test that all scripts included from self-repair have long lived cache headers"""
req = requests_session.get(conf.getoption("server") + "/en-US/repair")
req.raise_for_status()
document = html5lib.parse(req.content, treebuilder="dom")
scripts = document.getElementsByTagName("script")
for script in scripts:
src = script.getAttribute("src")
url = urljoin(conf.getoption("server"), src)
script_req = requests_session.get(url)
script_req.raise_for_status()
cache_control = parse_cache_control(script_req.headers["cache-control"])
assert cache_control["public"], f"Cache-control: public for {url}"
ONE_YEAR = 31_536_000
assert cache_control["max-age"] >= ONE_YEAR, f"Cache-control: max-age > 1 year for {url}"
assert cache_control["immutable"], f"Cache-control: immutable for {url}"
def parse_cache_control(header):
parsed = {}
parts = header.split(",")
for part in parts:
part = part.strip()
if "=" in part:
key, val = part.split("=", 1)
try:
val = int(val)
except ValueError:
pass
parsed[key] = val
else:
parsed[part] = True
return parsed
| mpl-2.0 |
mozilla/normandy | normandy/recipes/api/v1/views.py | 1 | 6564 | from django.conf import settings
from django.db import transaction
from django.db.models import Q
from django.views.decorators.cache import never_cache
import django_filters
from rest_framework import generics, permissions, views, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound, ParseError
from rest_framework.response import Response
from normandy.base.api.mixins import CachingViewsetMixin
from normandy.base.api.permissions import AdminEnabledOrReadOnly
from normandy.base.api.renderers import JavaScriptRenderer
from normandy.base.decorators import api_cache_control
from normandy.recipes.models import Action, ApprovalRequest, Client, Recipe, RecipeRevision
from normandy.recipes.api.filters import (
BaselineCapabilitiesFilter,
CharSplitFilter,
EnabledStateFilter,
)
from normandy.recipes.api.v1.serializers import (
ActionSerializer,
ApprovalRequestSerializer,
ClientSerializer,
RecipeRevisionSerializer,
RecipeSerializer,
SignedActionSerializer,
SignedRecipeSerializer,
)
class ActionViewSet(CachingViewsetMixin, viewsets.ReadOnlyModelViewSet):
"""Viewset for viewing recipe actions."""
queryset = Action.objects.all()
serializer_class = ActionSerializer
pagination_class = None
lookup_field = "name"
lookup_value_regex = r"[_\-\w]+"
@action(detail=False, methods=["GET"])
@api_cache_control()
def signed(self, request, pk=None):
actions = self.filter_queryset(self.get_queryset()).exclude(signature=None)
serializer = SignedActionSerializer(actions, many=True)
return Response(serializer.data)
class ActionImplementationView(generics.RetrieveAPIView):
"""
Retrieves the implementation code for an action. Raises a 404 if the
given hash doesn't match the hash we've stored.
"""
queryset = Action.objects.all()
lookup_field = "name"
permission_classes = []
renderer_classes = [JavaScriptRenderer]
pagination_class = None
@api_cache_control(max_age=settings.IMMUTABLE_CACHE_TIME)
def retrieve(self, request, name, impl_hash):
action = self.get_object()
if impl_hash != action.implementation_hash:
raise NotFound("Hash does not match current stored action.")
return Response(action.implementation)
class RecipeFilters(django_filters.FilterSet):
enabled = EnabledStateFilter()
action = django_filters.CharFilter(field_name="latest_revision__action__name")
channels = CharSplitFilter("latest_revision__channels__slug")
locales = CharSplitFilter("latest_revision__locales__code")
countries = CharSplitFilter("latest_revision__countries__code")
only_baseline_capabilities = BaselineCapabilitiesFilter(default_only_baseline=False)
class Meta:
model = Recipe
fields = ["action", "enabled", "latest_revision__action"]
class SignedRecipeFilters(RecipeFilters):
only_baseline_capabilities = BaselineCapabilitiesFilter(default_only_baseline=True)
class RecipeViewSet(CachingViewsetMixin, viewsets.ReadOnlyModelViewSet):
"""Viewset for viewing and uploading recipes."""
queryset = (
Recipe.objects.all()
# Foreign keys
.select_related("latest_revision")
.select_related("latest_revision__action")
.select_related("latest_revision__approval_request")
# Many-to-many
.prefetch_related("latest_revision__channels")
.prefetch_related("latest_revision__countries")
.prefetch_related("latest_revision__locales")
)
serializer_class = RecipeSerializer
filterset_class = RecipeFilters
permission_classes = [permissions.DjangoModelPermissionsOrAnonReadOnly, AdminEnabledOrReadOnly]
pagination_class = None
def get_queryset(self):
queryset = self.queryset
if self.request.GET.get("status") == "enabled":
queryset = queryset.only_enabled()
elif self.request.GET.get("status") == "disabled":
queryset = queryset.only_disabled()
if "text" in self.request.GET:
text = self.request.GET.get("text")
if "\x00" in text:
raise ParseError("Null bytes in text")
queryset = queryset.filter(
Q(latest_revision__name__contains=text)
| Q(latest_revision__extra_filter_expression__contains=text)
)
return queryset
@transaction.atomic
def create(self, request, *args, **kwargs):
return super().create(request, *args, **kwargs)
@transaction.atomic
def update(self, request, *args, **kwargs):
return super().update(request, *args, **kwargs)
@action(detail=False, methods=["GET"], filterset_class=SignedRecipeFilters)
@api_cache_control()
def signed(self, request, pk=None):
recipes = self.filter_queryset(self.get_queryset()).exclude(signature=None)
serializer = SignedRecipeSerializer(recipes, many=True)
return Response(serializer.data)
@action(detail=True, methods=["GET"])
@api_cache_control()
def history(self, request, pk=None):
recipe = self.get_object()
serializer = RecipeRevisionSerializer(
recipe.revisions.all().order_by("-id"), many=True, context={"request": request}
)
return Response(serializer.data)
class RecipeRevisionViewSet(viewsets.ReadOnlyModelViewSet):
queryset = (
RecipeRevision.objects.all()
.select_related("action")
.select_related("approval_request")
.select_related("recipe")
# Many-to-many
.prefetch_related("channels")
.prefetch_related("countries")
.prefetch_related("locales")
)
serializer_class = RecipeRevisionSerializer
permission_classes = [AdminEnabledOrReadOnly, permissions.DjangoModelPermissionsOrAnonReadOnly]
pagination_class = None
class ApprovalRequestViewSet(viewsets.ReadOnlyModelViewSet):
queryset = ApprovalRequest.objects.all()
serializer_class = ApprovalRequestSerializer
permission_classes = [AdminEnabledOrReadOnly, permissions.DjangoModelPermissionsOrAnonReadOnly]
pagination_class = None
class ClassifyClient(views.APIView):
authentication_classes = []
permission_classes = []
serializer_class = ClientSerializer
@never_cache
def get(self, request, format=None):
client = Client(request)
serializer = self.serializer_class(client, context={"request": request})
return Response(serializer.data)
| mpl-2.0 |
mozilla/normandy | normandy/recipes/migrations/0004_auto_20180502_2340.py | 1 | 5164 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-05-02 23:40
# flake8: noqa
from __future__ import unicode_literals
import hashlib
from django.db import migrations
def create_tmp_from_revision(apps, revision, parent=None):
ApprovalRequest = apps.get_model("recipes", "ApprovalRequest")
TmpRecipeRevision = apps.get_model("recipes", "TmpRecipeRevision")
tmp = TmpRecipeRevision(
created=revision.created,
updated=revision.updated,
comment=revision.comment,
name=revision.name,
arguments_json=revision.arguments_json,
extra_filter_expression=revision.extra_filter_expression,
identicon_seed=revision.identicon_seed,
action=revision.action,
parent=parent,
recipe=revision.recipe,
user=revision.user,
)
tmp.save()
if revision.approved_for_recipe.count():
tmp.approved_for_recipe.add(revision.approved_for_recipe.get())
if revision.latest_for_recipe.count():
tmp.latest_for_recipe.add(revision.latest_for_recipe.get())
try:
approval_request = revision.approval_request
approval_request.tmp_revision = tmp
approval_request.save()
except ApprovalRequest.DoesNotExist:
pass
for channel in revision.channels.all():
tmp.channels.add(channel)
for country in revision.countries.all():
tmp.countries.add(country)
for locale in revision.locales.all():
tmp.locales.add(locale)
return tmp
def copy_revisions_to_tmp(apps, schema_editor):
RecipeRevision = apps.get_model("recipes", "RecipeRevision")
for revision in RecipeRevision.objects.filter(parent=None):
current_rev = revision
parent_tmp = create_tmp_from_revision(apps, current_rev)
try:
while current_rev.child:
parent_tmp = create_tmp_from_revision(apps, current_rev.child, parent=parent_tmp)
current_rev = current_rev.child
except RecipeRevision.DoesNotExist:
pass
def get_filter_expression(revision):
parts = []
if revision.locales.count():
locales = ", ".join(["'{}'".format(l.code) for l in revision.locales.all()])
parts.append("normandy.locale in [{}]".format(locales))
if revision.countries.count():
countries = ", ".join(["'{}'".format(c.code) for c in revision.countries.all()])
parts.append("normandy.country in [{}]".format(countries))
if revision.channels.count():
channels = ", ".join(["'{}'".format(c.slug) for c in revision.channels.all()])
parts.append("normandy.channel in [{}]".format(channels))
if revision.extra_filter_expression:
parts.append(revision.extra_filter_expression)
expression = ") && (".join(parts)
return "({})".format(expression) if len(parts) > 1 else expression
def hash(revision):
data = "{}{}{}{}{}{}".format(
revision.recipe.id,
revision.created,
revision.name,
revision.action.id,
revision.arguments_json,
get_filter_expression(revision),
)
return hashlib.sha256(data.encode()).hexdigest()
def create_revision_from_tmp(apps, tmp, parent=None):
ApprovalRequest = apps.get_model("recipes", "ApprovalRequest")
RecipeRevision = apps.get_model("recipes", "RecipeRevision")
rev = RecipeRevision(
created=tmp.created,
updated=tmp.updated,
comment=tmp.comment,
name=tmp.name,
arguments_json=tmp.arguments_json,
extra_filter_expression=tmp.extra_filter_expression,
identicon_seed=tmp.identicon_seed,
action=tmp.action,
parent=parent,
recipe=tmp.recipe,
user=tmp.user,
)
initial_id = hash(tmp)
rev.id = initial_id
rev.save()
if tmp.approved_for_recipe.count():
rev.approved_for_recipe.add(tmp.approved_for_recipe.get())
if tmp.latest_for_recipe.count():
rev.latest_for_recipe.add(tmp.latest_for_recipe.get())
try:
approval_request = tmp.approval_request
approval_request.revision = rev
approval_request.save()
except ApprovalRequest.DoesNotExist:
pass
for channel in tmp.channels.all():
rev.channels.add(channel)
for country in tmp.countries.all():
rev.countries.add(country)
for locale in tmp.locales.all():
rev.locales.add(locale)
return rev
def copy_tmp_to_revisions(apps, schema_editor):
TmpRecipeRevision = apps.get_model("recipes", "TmpRecipeRevision")
for tmp in TmpRecipeRevision.objects.filter(parent=None):
current_tmp = tmp
parent_rev = create_revision_from_tmp(apps, current_tmp)
try:
while current_tmp.child:
parent_rev = create_revision_from_tmp(apps, current_tmp.child, parent=parent_rev)
current_tmp = current_tmp.child
except TmpRecipeRevision.DoesNotExist:
pass
class Migration(migrations.Migration):
dependencies = [("recipes", "0003_tmpreciperevision")]
operations = [migrations.RunPython(copy_revisions_to_tmp, copy_tmp_to_revisions)]
| mpl-2.0 |
mozilla/normandy | contract-tests/v3_api/test_approval_request_reject.py | 1 | 1850 | from support.assertions import assert_valid_schema
from support.helpers import new_recipe
from urllib.parse import urljoin
def test_approval_request_reject(conf, requests_session, headers):
# Get an action we can work with
action_response = requests_session.get(
urljoin(conf.getoption("server"), "/api/v3/action/"), headers=headers
)
data = action_response.json()
action_id = data["results"][0]["id"]
# Create a recipe associated with that action
recipe_details = new_recipe(requests_session, action_id, conf.getoption("server"), headers)
# Create a approval request
response = requests_session.post(
urljoin(
conf.getoption("server"),
"/api/v3/recipe_revision/{}/request_approval/".format(
recipe_details["latest_revision_id"]
),
),
headers=headers,
)
data = response.json()
approval_id = data["id"]
assert response.status_code != 404
assert_valid_schema(response.json())
# Reject the approval
response = requests_session.post(
urljoin(
conf.getoption("server"), "/api/v3/approval_request/{}/reject/".format(approval_id)
),
data={"comment": "r-"},
headers=headers,
)
assert response.status_code == 200
assert_valid_schema(response.json())
# Look at the recipe and make sure it the approval status has been set to False and our comment shows up
response = requests_session.get(
urljoin(conf.getoption("server"), "/api/v3/recipe/{}/".format(recipe_details["id"]))
)
assert response.status_code != 404
assert_valid_schema(response.json())
approval_request = response.json()["latest_revision"]["approval_request"]
assert approval_request["approved"] is False
assert approval_request["comment"] == "r-"
| mpl-2.0 |
mozilla/normandy | normandy/recipes/api/v3/serializers.py | 1 | 11345 | from rest_framework import serializers
from factory.fuzzy import FuzzyText
from normandy.base.api.v3.serializers import UserSerializer
from normandy.base.jexl import get_normandy_jexl
from normandy.recipes import filters
from normandy.recipes.api.fields import (
ActionImplementationHyperlinkField,
FilterObjectField,
)
from normandy.recipes.models import (
Action,
ApprovalRequest,
EnabledState,
Recipe,
RecipeRevision,
Signature,
)
from normandy.recipes.validators import JSONSchemaValidator
class CustomizableSerializerMixin:
"""Serializer Mixin that allows callers to exclude fields on instance of this serializer."""
def __init__(self, *args, **kwargs):
exclude_fields = kwargs.pop("exclude_fields", [])
super().__init__(*args, **kwargs)
if exclude_fields:
for field in exclude_fields:
self.fields.pop(field)
class ActionSerializer(serializers.ModelSerializer):
arguments_schema = serializers.JSONField()
implementation_url = ActionImplementationHyperlinkField()
class Meta:
model = Action
fields = ["arguments_schema", "name", "id", "implementation_url"]
class ApprovalRequestSerializer(serializers.ModelSerializer):
approver = UserSerializer()
created = serializers.DateTimeField(read_only=True)
creator = UserSerializer()
revision = serializers.SerializerMethodField(read_only=True)
class Meta:
model = ApprovalRequest
fields = ["approved", "approver", "comment", "created", "creator", "id", "revision"]
def get_revision(self, instance):
serializer = RecipeRevisionLinkSerializer(instance.revision)
return serializer.data
class EnabledStateSerializer(CustomizableSerializerMixin, serializers.ModelSerializer):
creator = UserSerializer()
class Meta:
model = EnabledState
fields = ["id", "revision_id", "created", "creator", "enabled", "carryover_from"]
class RecipeRevisionSerializer(serializers.ModelSerializer):
action = serializers.SerializerMethodField(read_only=True)
approval_request = ApprovalRequestSerializer(read_only=True)
capabilities = serializers.ListField(read_only=True)
comment = serializers.CharField(required=False)
creator = UserSerializer(source="user", read_only=True)
date_created = serializers.DateTimeField(source="created", read_only=True)
enabled_states = EnabledStateSerializer(many=True, exclude_fields=["revision_id"])
filter_object = serializers.ListField(child=FilterObjectField())
recipe = serializers.SerializerMethodField(read_only=True)
class Meta:
model = RecipeRevision
fields = [
"action",
"approval_request",
"arguments",
"experimenter_slug",
"capabilities",
"comment",
"creator",
"date_created",
"enabled_states",
"enabled",
"extra_capabilities",
"extra_filter_expression",
"filter_expression",
"filter_object",
"id",
"identicon_seed",
"metadata",
"name",
"recipe",
"updated",
]
def get_recipe(self, instance):
serializer = RecipeLinkSerializer(instance.recipe)
return serializer.data
def get_action(self, instance):
serializer = ActionSerializer(
instance.action, read_only=True, context={"request": self.context.get("request")}
)
return serializer.data
class SignatureSerializer(serializers.ModelSerializer):
timestamp = serializers.DateTimeField(read_only=True)
signature = serializers.ReadOnlyField()
x5u = serializers.ReadOnlyField()
public_key = serializers.ReadOnlyField()
class Meta:
model = Signature
fields = ["timestamp", "signature", "x5u", "public_key"]
class RecipeSerializer(CustomizableSerializerMixin, serializers.ModelSerializer):
# read-only fields
approved_revision = RecipeRevisionSerializer(read_only=True)
latest_revision = RecipeRevisionSerializer(read_only=True)
signature = SignatureSerializer(read_only=True)
uses_only_baseline_capabilities = serializers.BooleanField(
source="latest_revision.uses_only_baseline_capabilities", read_only=True
)
# write-only fields
action_id = serializers.PrimaryKeyRelatedField(
source="action", queryset=Action.objects.all(), write_only=True
)
arguments = serializers.JSONField(write_only=True)
extra_filter_expression = serializers.CharField(
required=False, allow_blank=True, write_only=True
)
filter_object = serializers.ListField(
child=FilterObjectField(), required=False, write_only=True
)
name = serializers.CharField(write_only=True)
identicon_seed = serializers.CharField(required=False, write_only=True)
comment = serializers.CharField(required=False, write_only=True)
experimenter_slug = serializers.CharField(
required=False, write_only=True, allow_null=True, allow_blank=True
)
extra_capabilities = serializers.ListField(required=False, write_only=True)
class Meta:
model = Recipe
fields = [
# read-only
"approved_revision",
"id",
"latest_revision",
"signature",
"uses_only_baseline_capabilities",
# write-only
"action_id",
"arguments",
"extra_filter_expression",
"filter_object",
"name",
"identicon_seed",
"comment",
"experimenter_slug",
"extra_capabilities",
]
def get_action(self, instance):
serializer = ActionSerializer(
instance.latest_revision.action,
read_only=True,
context={"request": self.context.get("request")},
)
return serializer.data
def update(self, instance, validated_data):
request = self.context.get("request")
if request and request.user:
validated_data["user"] = request.user
instance.revise(**validated_data)
return instance
def create(self, validated_data):
request = self.context.get("request")
if request and request.user:
validated_data["user"] = request.user
if "identicon_seed" not in validated_data:
validated_data["identicon_seed"] = f"v1:{FuzzyText().fuzz()}"
recipe = Recipe.objects.create()
return self.update(recipe, validated_data)
def validate_extra_filter_expression(self, value):
if value:
jexl = get_normandy_jexl()
errors = list(jexl.validate(value))
if errors:
raise serializers.ValidationError(errors)
return value
def validate(self, data):
data = super().validate(data)
action = data.get("action")
if action is None:
action = self.instance.latest_revision.action
arguments = data.get("arguments")
if arguments is not None:
# Ensure the value is a dict
if not isinstance(arguments, dict):
raise serializers.ValidationError({"arguments": "Must be an object."})
# Get the schema associated with the selected action
schema = action.arguments_schema
schemaValidator = JSONSchemaValidator(schema)
errorResponse = {}
errors = sorted(schemaValidator.iter_errors(arguments), key=lambda e: e.path)
# Loop through ValidationErrors returned by JSONSchema
# Each error contains a message and a path attribute
# message: string human-readable error explanation
# path: list containing path to offending element
for error in errors:
currentLevel = errorResponse
# Loop through the path of the current error
# e.g. ['surveys'][0]['weight']
for index, path in enumerate(error.path):
# If this key already exists in our error response, step into it
if path in currentLevel:
currentLevel = currentLevel[path]
continue
else:
# If we haven't reached the end of the path, add this path
# as a key in our error response object and step into it
if index < len(error.path) - 1:
currentLevel[path] = {}
currentLevel = currentLevel[path]
continue
# If we've reached the final path, set the error message
else:
currentLevel[path] = error.message
if errorResponse:
raise serializers.ValidationError({"arguments": errorResponse})
if self.instance is None:
if data.get("extra_filter_expression", "").strip() == "":
if not data.get("filter_object"):
raise serializers.ValidationError(
"one of extra_filter_expression or filter_object is required"
)
else:
if "extra_filter_expression" in data or "filter_object" in data:
# If either is attempted to be updated, at least one of them must be truthy.
if not data.get("extra_filter_expression", "").strip() and not data.get(
"filter_object"
):
raise serializers.ValidationError(
"if extra_filter_expression is blank, "
"at least one filter_object is required"
)
return data
def validate_filter_object(self, value):
if not isinstance(value, list):
raise serializers.ValidationError(
{"non field errors": ["filter_object must be a list."]}
)
errors = {}
for i, obj in enumerate(value):
if not isinstance(obj, dict):
errors[i] = {"non field errors": ["filter_object members must be objects."]}
continue
if "type" not in obj:
errors[i] = {"type": ["This field is required."]}
break
Filter = filters.by_type.get(obj["type"])
if Filter is not None:
filter = Filter(data=obj)
if not filter.is_valid():
errors[i] = filter.errors
else:
errors[i] = {"type": [f'Unknown filter object type "{obj["type"]}".']}
if errors:
raise serializers.ValidationError(errors)
return value
class RecipeLinkSerializer(RecipeSerializer):
class Meta(RecipeSerializer.Meta):
fields = ["approved_revision_id", "id", "latest_revision_id"]
class RecipeRevisionLinkSerializer(RecipeRevisionSerializer):
recipe_id = serializers.SerializerMethodField(read_only=True)
class Meta(RecipeSerializer.Meta):
fields = ["id", "recipe_id"]
def get_recipe_id(self, instance):
return instance.recipe.id
| mpl-2.0 |
mozilla/normandy | contract-tests/v3_api/test_group_delete.py | 1 | 1231 | import uuid
from support.assertions import assert_valid_schema
from urllib.parse import urljoin
def test_group_delete(conf, requests_session, headers):
# Create a new group
data = {"name": str(uuid.uuid4())}
response = requests_session.post(
urljoin(conf.getoption("server"), "/api/v3/group/"), headers=headers, data=data
)
assert response.status_code == 201
assert_valid_schema(response.json())
group_data = response.json()
group_id = group_data["id"]
# Verify group was stored and contains expected data
response = requests_session.get(
urljoin(conf.getoption("server"), "/api/v3/group/{}/".format(group_id)), headers=headers
)
group_data = response.json()
assert response.status_code == 200
assert_valid_schema(response.json())
# Delete the group
response = requests_session.delete(
urljoin(conf.getoption("server"), "/api/v3/group/{}/".format(group_id)), headers=headers
)
assert response.status_code == 204
# Verify that it no longer exists
response = requests_session.get(
urljoin(conf.getoption("server"), "/api/v3/group/{}/".format(group_id)), headers=headers
)
assert response.status_code == 404
| mpl-2.0 |
developmentseed/landsat-util | docs/conf.py | 9 | 9890 | # -*- coding: utf-8 -*-
#
# Landsat-util documentation build configuration file, created by
# sphinx-quickstart on Thu May 28 17:52:10 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
from mock import Mock as MagicMock
class Mock(MagicMock):
@classmethod
def __getattr__(cls, name):
return Mock()
MOCK_MODULES = ['numpy', 'rasterio', 'scipy', 'scikit-image', 'homura', 'boto',
'termcolor', 'requests', 'python-dateutil']
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
import os
import sphinx_rtd_theme
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
sys.path.insert(0, project_root)
print project_root
import landsat
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.coverage',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'landsat-util'
copyright = u'2015, Development Seed'
author = u'Development Seed'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = landsat.__version__
# The full version, including alpha/beta/rc tags.
release = landsat.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'Landsat-utildoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Landsat-util.tex', u'Landsat-util Documentation',
u'Development Seed', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'landsat-util', u'Landsat-util Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Landsat-util', u'Landsat-util Documentation',
author, 'Landsat-util', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
| cc0-1.0 |
rmmh/skybot | plugins/lastfm.py | 3 | 2391 | """
The Last.fm API key is retrieved from the bot config file.
"""
from util import hook, http
api_url = "http://ws.audioscrobbler.com/2.0/?format=json"
@hook.api_key("lastfm")
@hook.command(autohelp=False)
def lastfm(inp, chan="", nick="", reply=None, api_key=None, db=None):
".lastfm <username> [dontsave] | @<nick> -- gets current or last played " "track from lastfm"
db.execute(
"create table if not exists "
"lastfm(chan, nick, user, primary key(chan, nick))"
)
if inp[0:1] == "@":
nick = inp[1:].strip()
user = None
dontsave = True
else:
user = inp
dontsave = user.endswith(" dontsave")
if dontsave:
user = user[:-9].strip().lower()
if not user:
user = db.execute(
"select user from lastfm where chan=? and nick=lower(?)", (chan, nick)
).fetchone()
if not user:
return lastfm.__doc__
user = user[0]
response = http.get_json(
api_url, method="user.getrecenttracks", api_key=api_key, user=user, limit=1
)
if "error" in response:
return "error: %s" % response["message"]
if (
not "track" in response["recenttracks"]
or len(response["recenttracks"]["track"]) == 0
):
return "no recent tracks for user \x02%s\x0F found" % user
tracks = response["recenttracks"]["track"]
if type(tracks) == list:
# if the user is listening to something, the tracks entry is a list
# the first item is the current track
track = tracks[0]
status = "current track"
elif type(tracks) == dict:
# otherwise, they aren't listening to anything right now, and
# the tracks entry is a dict representing the most recent track
track = tracks
status = "last track"
else:
return "error parsing track listing"
title = track["name"]
album = track["album"]["#text"]
artist = track["artist"]["#text"]
ret = "\x02%s\x0F's %s - \x02%s\x0f" % (user, status, title)
if artist:
ret += " by \x02%s\x0f" % artist
if album:
ret += " on \x02%s\x0f" % album
reply(ret)
if inp and not dontsave:
db.execute(
"insert or replace into lastfm(chan, nick, user) " "values (?, ?, ?)",
(chan, nick.lower(), inp),
)
db.commit()
| unlicense |
rmmh/skybot | plugins/google.py | 2 | 1308 | from __future__ import unicode_literals
import random
from util import hook, http
def api_get(query, key, is_image=None, num=1):
url = (
"https://www.googleapis.com/customsearch/v1?cx=007629729846476161907:ud5nlxktgcw"
"&fields=items(title,link,snippet)&safe=off&nfpr=1"
+ ("&searchType=image" if is_image else "")
)
return http.get_json(url, key=key, q=query, num=num)
@hook.api_key("google")
@hook.command("can i get a picture of")
@hook.command("can you grab me a picture of")
@hook.command("give me a print out of")
@hook.command
def gis(inp, api_key=None):
""".gis <term> -- finds an image using google images (safesearch off)"""
parsed = api_get(inp, api_key, is_image=True, num=10)
if "items" not in parsed:
return "no images found"
return random.choice(parsed["items"])["link"]
@hook.api_key("google")
@hook.command("g")
@hook.command
def google(inp, api_key=None):
""".g/.google <query> -- returns first google search result"""
parsed = api_get(inp, api_key)
if "items" not in parsed:
return "no results found"
out = '{link} -- \x02{title}\x02: "{snippet}"'.format(**parsed["items"][0])
out = " ".join(out.split())
if len(out) > 300:
out = out[: out.rfind(" ")] + '..."'
return out
| unlicense |
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 43