Example #1
0
  def test_create_alert_created(self):
    """Tests alert created successfully."""
    alert_uuid, is_valid, error = utils.CreateAlert(self.draft_alert_content,
                                                    self.TEST_USER_NAME)
    self.assertTrue(UUID_RE.match(alert_uuid))
    self.assertTrue(is_valid)
    self.assertEqual(error, None)

    alert = models.Alert.objects.get(uuid=alert_uuid)
    alert_dict = utils.ParseAlert(alert.content, "xml", alert.uuid)
    draft_dict = utils.ParseAlert(self.draft_alert_content, "xml", alert.uuid)
    # Remove alert IDs due to their random nature.
    del alert_dict["alert_id"]
    del draft_dict["alert_id"]
    self.assertDictEqual(alert_dict, draft_dict)
Example #2
0
    def handle(self, *args, **options):
        if len(args) != 2:
            raise CommandError(
                "Wrong arguments number! Please use python manage.py import_templates"
                " template_type template_path (e.g. python manage.py import_templates"
                " area /home/user/path/to/templates/ or python manage.py"
                " import_templates message /home/user/path/to/templates/")

        templates_type = args[0]
        templates_path = args[1]

        template_objects = []
        for file_name in os.listdir(templates_path):
            if not file_name.endswith(".xml"):
                print("Ignored file: %s" % file_name)
                continue

            file_path = os.path.join(templates_path, file_name)
            with open(file_path, "r") as template_file:
                template_content = template_file.read()
            template_dict = utils.ParseAlert(template_content, "xml",
                                             uuid.uuid4())
            if templates_type == "area":
                template_model = models.AreaTemplate
            elif templates_type == "message":
                template_model = models.MessageTemplate

            template_obj = template_model()
            template_obj.title = file_name.rstrip(".xml").strip()
            template_obj.content = template_content
            template_objects.append(template_obj)

        # Save to DB.
        template_model.objects.bulk_create(template_objects)
Example #3
0
 def test_parse_partial_alert(self):
     """Tests if partial XML alert parsed correctly."""
     file_name = "partial_template"
     golden_alert_dict = {
         "response_type":
         "AllClear",
         "severity":
         "Severe",
         "instruction":
         "This is an instruction",
         "description":
         "This is a description",
         "msg_type":
         "Alert",
         "category":
         "Env",
         "certainty":
         "Possible",
         "urgency":
         "Expected",
         "title":
         "Alert Message",  # Default.
         "link":
         "%s%s" %
         (settings.SITE_URL, reverse("alert", args=[file_name, "xml"])),
     }
     alert_dict = utils.ParseAlert(self.partial_alert_content, "xml",
                                   file_name)
     for key in golden_alert_dict:
         if not alert_dict[key]:
             continue  # We need values present in both template and alert files.
         self.assertEqual(alert_dict[key], golden_alert_dict[key])
Example #4
0
    def get(self, request, *args, **kwargs):
        feed_type = kwargs["feed_type"]

        audience = request.GET.get('audience', '')
        # print(audience)

        if "alert_id" in kwargs:
            try:
                alert = models.Alert.objects.get(uuid=kwargs["alert_id"])
            except models.Alert.DoesNotExist:
                raise Http404

            if feed_type == "html":
                context = {
                    "alert": utils.ParseAlert(alert.content, feed_type,
                                              alert.uuid)
                }
                response = render_to_string("core/alert.html.tmpl", context)
                return HttpResponse(
                    BeautifulSoup(response, feed_type).prettify())

            return HttpResponse(alert.content, content_type="text/xml")

        feed_data = utils.GenerateFeed(feed_type)
        if feed_type == "json":
            if audience == "":
                return JsonResponse(feed_data, safe=False)
            new_feed = []
            for alert in feed_data:
                if alert["audience"] == audience:
                    new_feed.append(alert)
            return JsonResponse(new_feed, safe=False)

        return HttpResponse(feed_data, content_type="text/%s" % feed_type)
Example #5
0
 def test_parse_valid_alert(self):
   """Tests if valid XML alert parsed correctly."""
   golden_alert_dict = {
       "circles": [],
       "sent": parser.parse("2014-08-16T00:32:11+00:00"),
       "expires": parser.parse("2014-08-16T01:32:11+00:00"),
       "alert_id": self.VALID_ALERT_UUID,
       "link": "%s%s" % (settings.SITE_URL,
                         reverse("alert", args=[self.VALID_ALERT_UUID,
                                                "xml"])),
       "response_type": "Monitor",
       "severity": "Extreme",
       "instruction": "Instruction here.",
       "description": "And description",
       "msg_type": "Alert",
       "category": "Fire",
       "name": "[email protected]: sender",
       "title": "Some headline.",
       "event": "Fire fire fire.",
       "area_desc": "This and that area.",
       "certainty": "Observed",
       "parameters": [{"name": "name1", "value": "val1"},
                      {"name": "name2", "value": "val2"}],
       "geocodes": [{"name": "geo_code1", "value": "geo_code_value1"}],
       "polys": [],
       "urgency": "Immediate"
   }
   alert_dict = utils.ParseAlert(self.valid_alert_content, "xml",
                                 self.VALID_ALERT_UUID)
   for key in golden_alert_dict:
     self.assertEqual(alert_dict[key], golden_alert_dict[key])
Example #6
0
  def CheckValues(self, uuid, initial_dict):
    """Asserts that initial and parsed data is equal.

    Args:
      uuid: (string) Alert UUID, assumed to be the filename of the alert XML.
      initial_dict: (dict) Initial alert data dictionary.
    Returns:
      Parsed alerts dictionary.
    """

    alert = models.Alert.objects.get(uuid=uuid)

    alert_dict = utils.ParseAlert(alert.content, "xml", uuid)
    for key in initial_dict:
      self.assertEqual(alert_dict[key], initial_dict[key])
    return alert_dict
Example #7
0
  def get(self, request, *args, **kwargs):
    feed_type = kwargs["feed_type"]

    if "alert_id" in kwargs:
      try:
        alert = models.Alert.objects.get(uuid=kwargs["alert_id"])
      except models.Alert.DoesNotExist:
        raise Http404

      if feed_type == "html":
        context = {
            "alert": utils.ParseAlert(alert.content, feed_type, alert.uuid)
        }
        response = render_to_string("core/alert.html.tmpl", context)
        return HttpResponse(BeautifulSoup(response, feed_type).prettify())

      return HttpResponse(alert.content, content_type="text/xml")

    return HttpResponse(utils.GenerateFeed(feed_type),
                        content_type="text/%s" % feed_type)
Example #8
0
  def test_end2end_alert_create_from_template(self):
    """Emulates alert from template creation process using webdriver.

       Afrer webdriver part is done it checks whether alert file has created
       in active alerts directory and deletes alert file after that.
    """

    self.GoToAlertsTab()
    self.Login()

    # Alert tab.
    self.GoToAlertTab()
    self.SetMessageTemplate(1)

    # Message tab.
    self.GoToMessageTab()
    self.SetAlertSenderName(self.sender_name)
    self.SetContact(self.contact)

    # Area tab.
    self.GoToAreaTab()
    self.SetAreaTemplate(4)

    # Release tab.
    self.GoToReleaseTab()
    self.SetUsername(self.TEST_USER_LOGIN)
    self.SetPassword(self.TEST_USER_PASSWORD)
    self.ReleaseAlert()

    alert_uuid = UUID_RE.findall(self.GetUuid())[0]
    self.assertTrue(models.Alert.objects.filter(uuid=alert_uuid).exists())

    # Ensure that feed contains new alert.
    response = self.client.get("/feed.xml")
    self.assertContains(response, alert_uuid)

    # Check alert XML against initial values.
    alert = models.Alert.objects.get(uuid=alert_uuid)
    message_template_xml = models.MessageTemplate.objects.get(id=1).content
    area_template_xml = models.AreaTemplate.objects.get(id=4).content
    alert_dict = utils.ParseAlert(alert.content, "xml", alert_uuid)
    message_dict = utils.ParseAlert(message_template_xml, "xml", alert_uuid)
    area_dict = utils.ParseAlert(area_template_xml, "xml", alert_uuid)
    alert_expires_at = alert_dict["expires"]
    alert_sent_at = alert_dict["sent"]
    self.assertEqual((alert_expires_at - alert_sent_at).seconds / 60,
                     int(message_dict["expiresDurationMinutes"]))
    del message_dict["expiresDurationMinutes"]

    # Message template assertions.
    for key in message_dict:
      if message_dict.get(key):
        self.assertEqual(alert_dict[key], message_dict[key])

    # Area template assertions.
    for key in area_dict:
      if area_dict[key]:
        self.assertEqual(alert_dict[key], area_dict[key])

    # Check web field is set to default.
    alert_default_web = "%s%s" % (settings.SITE_URL,
                                  reverse("alert", args=[alert_uuid, "html"]))
    self.assertEqual(alert_dict["web"], alert_default_web)
Example #9
0
 def test_parse_invalid_alert(self):
     """Tests if invalid XML alert parsed correctly."""
     self.assertDictEqual(
         utils.ParseAlert(self.invalid_alert_content, "xml", "no_filename"),
         {})