Example #1
0
    def post(self):
        try:
            if Site.find_by_sitename(request.json["site_name"]):
                return {
                    'message':
                    'Site {} already exists'.format(request.json["username"])
                }

            new_site = Site(site_name=request.json['site_name'],
                            city=request.json['city'],
                            site_address=request.json['site_address'],
                            longitude=request.json['longitude'],
                            latitude=request.json['latitude'],
                            number_of_string=request.json['number_of_string'],
                            total_capacity=request.json['total_capacity'])

            db.session.add(new_site)
            db.session.commit()

            return {
                'message': 'Site {} was created'.format(new_site.site_name)
            }

        except:
            return {'message': 'Something went wrong'}, 500
Example #2
0
    def test_expects_separated_reports(self, webmock):
        # Assume
        test_dir = pathjoin(AUDITS_DIR, "sub-domain-com")
        self.assertPathDoesNotExist(test_dir)

        # Arrange
        domain = 'sub.domain.com'
        webmock.get(requests_mock.ANY, text='ok')
        site = Site(domain)
        test_cases = [
            # audit_type, expected_report_designator
            ("design", "design"),
            ("code", "code"),
            (None, "all")
        ]

        for audit_type, expected_report_designator in test_cases:
            site.audit_type = audit_type
            audit = AxeSiteAudit(site)

            # Act
            csv_path = audit.write_violations_to_csv()

            # Assert
            filename_template = "sub-domain-com-site-{}-violations.csv"
            expected_filename = filename_template.format(expected_report_designator)
            expected_path = pathjoin(test_dir, expected_filename)
            self.assertEqual(expected_path, csv_path)
Example #3
0
def lambda_handler(event, context):
    logger.info('got event{}'.format(event))

    site = deserialize_site(event)
    if site is None:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No valid Site data sent in the body."}'
        )

    # Check to see if there are any items already existing with that slug
    existing_site_check = Site.find(site.slug)
    if existing_site_check is not None:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: Duplicate slug value specified. This must be a unique value for each site."}'
        )

    # Actually create the record now
    if not site.save():
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: Unable to create record due to failed validation checks."}'
        )
    else:
        response_body = Site.find(site.slug).to_json(
        )  # Reload the object from the database to ensure that any on-save hooks are accounted for
        return respond('200', response_body)
def home(language='es'):
    site = Site(language, splitByLanguage('Inicio | Home', language))
    site.blowUp = True

    collection = Collection(site)
    items = collection.asItems()

    return render_template('home.html', site=site, items=items)
Example #5
0
    def test_site_validation(self):
        site = Site()
        self.assertFalse(
            site.is_valid(),
            'Default site values should not validate due to empty name and slug'
        )

        site.name = "Valid Site Name"
        site.slug = 'valid-site-name'
        self.assertTrue(site.is_valid(),
                        'These hand-coded values should be valid')

        # Test some known-bad slugs
        bad_slugs = [
            'valid site name',  # no whitespace
            'valid--site--name',  # no repeated hyphens
            'Valid-Site-Name',  # No capital letters
            'chris\'-awesome-site',  # No apostrophes
        ]
        for bad_slug in bad_slugs:
            site.name = 'Valid Site Name'
            site.slug = bad_slug
            self.assertFalse(
                site.is_valid(),
                'This slug should have been invalid: \'%(slug)\'' % site.slug)
Example #6
0
File: test.py Project: CMGS/ymir
def cleanup():
    from models.site import Site, Block
    Site.drop_table(fail_silently=True)
    Block.drop_table(fail_silently=True)
    from utils.cache import local_cache
    for k, v in local_cache.iteritems():
        if not v:
            continue
        v.drop_table(fail_silently=True)
    from utils.cache import rds
    keys = rds.keys('c:*')
    if keys:
        rds.delete(*keys)
 def __init__(self, handler):
   try:
     site = cache.get("site")
     if site:
       self.site = site
     else:
       site = Site.all().get()
       cache.add("site", site)
       self.site = site
   except:
     site = Site.all().get();
     cache.add("site", site)
     self.site = site
   self.handler = handler
Example #8
0
    def test_expects_to_validate_internal_urls(self, webmock):
        # Arrange
        webmock.get(requests_mock.ANY, text='ok')
        domain = 'sub.domain.com'
        site = Site.from_domain_or_url(domain)

        test_cases = [
            # url,                                                  is_valid
            ['https://sub.domain.com/',                             True],
            ['https://sub.domain.com/foo',                          True],
            ['https://sub.domain.com/foo?q=foo',                    True],
            ['https://domain.com/',                                 False],
            ['foo/bar',                                             False],
            ['https://google.com',                                  False],
            ['https://google.com/',                                 False],
            ['https://sub.domain.com/mailto:[email protected]',       False],
            ['https://sub.domain.com/tel:555-555-5555',             False],
            ['https://sub.domain.com/fax:555-555-5555',             False],
            ['https://sub.domain.com/foo#header',                   False],
            ['https://sub.domain.com/javascript: openMarker(1)',    False],
            ['https://sub.domain.com/foo.jpg',                      False],
            ['https://sub.domain.com/foo.mp3',                      False],
            ['https://sub.domain.com/foo.mov',                      False],
            ['https://sub.domain.com/foo.pdf',                      False]
        ]

        # Act / Assert
        for url, expected in test_cases:
            is_valid = site.is_valid_internal_url(url)
            self.assertEqual(expected, is_valid, url)
Example #9
0
 def test_get_one(self):
     site = Site.find('test_site_1')
     self.assertEqual("123 Fake Street", site.address)
     self.assertEqual('test_site_1', site.name)
     self.assertEqual('Yellow', site.availability_status)
     self.assertEqual(False, site.is_open)
     self.assertEqual('8-4', site.hours)
Example #10
0
def lambda_handler(event, context):
    logger.info('got event{}'.format(event))
    #get the site name from the url
    if 'pathParameters' not in event:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug specified in the path"}'
        )
    if 'sitename' not in event['pathParameters']:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug found in the path parameters"}'
        )
#    site_name = urllib.parse.unquote(event['pathParameters']['sitename'])
# TODO: implement url decoding, or do pattern validation on the sitename
    site_name = event['pathParameters']['sitename']

    if len(site_name) == 0:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: Empty sitename"}'
        )

    site = Site.find(site_name)
    if site is None:
        return respond(
            '404',
            '{ "errorCode": "404", "errorMessage":"Not Found: no Site found with that slug"}'
        )

    #actually delete the site
    site.delete()
    return respond('200', '')
Example #11
0
File: test.py Project: CMGS/ymir
def setup():
    import tests
    import config
    for k in dir(config):
        value = getattr(tests, k, None)
        if not value:
            continue
        setattr(config, k, value)

    from models.site import Site, Block
    from query.site import create
    Site.create_table(fail_silently=True)
    Block.create_table(fail_silently=True)
    global site
    from tests.base import TEST_TOKEN
    site = create(TEST_TOKEN, 'test')
Example #12
0
    def test_expects_to_filter_by_audit_type(self):
        # Arrange
        domain = 'sub.domain.com'
        site = Site.from_domain_or_url(domain)
        page = Page(site)
        test_axe_report_path = helper.fixture_file_path(
            'httpbin-org-page-all-violations.json')

        with open(test_axe_report_path, "r") as f:
            data = json.loads(f.read())

        axe_errors = data["violations"]

        test_cases = [
            # audit_type   expected_violations_length
            ("design", 2),
            ("code", 3),
            (None, 5)
        ]

        for audit_type, expected_violations_length in test_cases:
            audit = AxePageAudit(page, audit_type)
            sorted_violations = []

            # Act
            for error in axe_errors:
                sorted_violations += Violation.s_from_audit_axe_error(
                    audit, error)

            # Assert
            self.assertEqual(expected_violations_length,
                             len(sorted_violations))
Example #13
0
    def test_expect_successful_page_audit(self, webmock):
        # Arrange
        domain = 'httpbin.org'
        test_axe_report_path = helper.fixture_file_path('httpbin-org-page-all-violations.json')
        webmock.get(requests_mock.ANY, text='ok')
        site = Site.from_domain_or_url(domain)
        page = Page(site)
        audit_type = None

        # Assume
        self.assertIsNone(page.audit)
        self.assertPathExists(test_axe_report_path)

        # Act
        # Mock the AxeAudit generate_report method to return our test fixture file
        # path when page.axe_audit called.
        with patch.object(AxePageAudit, 'generate_report') as mocked_method:
            mocked_method.return_value = test_axe_report_path
            page.axe_audit(audit_type)

        # Assert
        self.assertIsNotNone(page.audit)
        self.assertEqual(page.site, site)
        self.assertIn(domain, page.url)
        self.assertEqual(5, len(page.audit.violations))
        self.assertEqual(5, len(page.audit.errors))
        self.assertEqual(0, len(page.audit.warnings))
Example #14
0
 def post(self, *args, **kwargs):
   email = self.request.get("email")
   code = self.request.get("code")
   password = self.request.get("password")
   site = Site.all().get()
   if email and not code:
     if User.send_recovery_email(email, site.title):
       self.response.out.write("The email has been sent. Please check your email to reset your password.")
       return True
     else:
       self.response.out.write("The email was not sent. Please try again.")
       return False
   elif email and code and password:
     user = User.get_by_email(email)
     if user:
       if user.set_password(password, site.secret):
         login = User.login(email, password, site)
         self.session["user"] = login
         user.destroy_token()
         self.redirect('/')
         return True
       else:
         self.response.out.write("An Error Occurred Resetting Password, Please try again.")
         return False
     else:
       self.response.out.write("Cannot Reset Password For This User")
       return False
   return False
Example #15
0
    def test_expects_violations_in_csv(self, webmock):
        # Arrange
        test_dir = pathjoin(AUDITS_DIR, "sub-domain-com")
        violations_csv_path = pathjoin(test_dir, "sub-domain-com.csv")
        webmock.get(requests_mock.ANY, text='ok')
        domain = 'sub.domain.com'
        site = Site(domain)
        page = Page(site)
        audit = AxeSiteAudit(site)
        source = 'test'
        identifier = 'test-error'
        severity = 'low'
        violation = Violation(
            page=page,
            source=source,
            identifier=identifier,
            severity=severity
        )
        violation.kind = "error"
        violation.help = "Error must be fixed"
        violation.help_url = "https://help.com"
        violation.html = "<p>Test</p>"
        violation.failure = "This is incorrect"

        # Act
        audit.write_to_violation_csv(violations_csv_path, [violation])
        with open(violations_csv_path, 'r') as file:
            csv_rows = list(csv.reader(file))
            row_count = len(csv_rows)

        # Assert
            self.assertEqual(row_count, 2)
            self.assertEqual(csv_rows[0][0], "page_url")
            self.assertEqual(csv_rows[1][8], violation.failure)
Example #16
0
def lambda_handler(event, context):
    #get the site name from the url
    if 'pathParameters' not in event:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug specified in the path"}'
        )
    if 'sitename' not in event['pathParameters']:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug found in the path parameters"}'
        )
    site_name = urllib.parse.unquote(event['pathParameters']['sitename'])

    if len(site_name) == 0:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: Empty sitename"}'
        )

    site = Site.find(site_name)

    if site is None:
        return respond(
            '404', '{ "errorCode": "404", "errorMessage":"Invalid site name"}')

    return respond('200', site.to_json())
Example #17
0
    def test_create_site_nodata(self):
        # Make note of the starting site count
        starting_sites = Site.all()

        event = {
            'httpMethod': 'PUT',
            'path': '/site',
            'resource': '/site',
            'pathParameters': None,
            'body': None,
        }

        response = LambdaApiHandler.site_apis(event)
        self.assertEqual('400', response['statusCode'])
        # Cleanup validation
        self.assertEqual(len(starting_sites), len(Site.all()),
                         "Failed to clean up the site we created!")
Example #18
0
def deserialize_site(event):
    """ Extract a Site object from the Event body """
    if event['body'] is None:
        return None

    json_body = json.loads(event['body'])
    site = Site.from_dict(json_body)
    return site
Example #19
0
def deserialize_site(event):
    """ Extract a Site object from the Event body """
    if event['body'] is None:
        return None

    json_body = json.loads(event['body'])
    site = Site.from_dict(json_body)
    return site
Example #20
0
File: site.py Project: CMGS/ymir
def create(token, name):
    site = Site.create(token=token, name=name)
    node = get_node(site.id)
    site.node = node
    site.save()
    comment_table = generate(site.id, token, node)
    comment_table.create_table()
    local_cache[token] = site
    return site
Example #21
0
def lambda_handler(event, context):
    logger.info('got event{}'.format(event))

    site = deserialize_site(event)
    if site is None:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No valid Site data sent in the body."}')

    # Check to see if there are any items already existing with that slug
    existing_site_check = Site.find(site.slug)
    if existing_site_check is not None:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: Duplicate slug value specified. This must be a unique value for each site."}')

    # Actually create the record now
    if not site.save():
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: Unable to create record due to failed validation checks."}')
    else:
        response_body = Site.find(site.slug).to_json() # Reload the object from the database to ensure that any on-save hooks are accounted for
        return respond('200', response_body)
Example #22
0
 def test_auction_results(self):
     """Test auction bids result calculation"""
     bids = [
         Bid(Bidder('BRANDON', -0.001), 'banner', 50),
         Bid(Bidder('ASEMA', -0.0432), 'banner', 51)
     ]
     site = Site('test.com', [bids[0].bidder, bids[1].bidder], 40)
     auction = Auction(site, [AdUnit.banner], bids)
     actual = auction.get_max_bids()
     self.assertEqual(actual['banner'].bid, 50, 'Invalid Auction')
Example #23
0
    def test_create_site(self):
        event = {
            'httpMethod':
            'PUT',
            'path':
            '/site',
            'resource':
            '/site',
            'pathParameters':
            None,
            'body':
            json.dumps({
                "Site": {
                    "name": "tc_lambda_sites_test_create_site",
                    "address": "1234 Fake Street",
                    "hours": "8-3",
                    "is_open": False,
                    "availability_status": "Red"
                }
            }),
        }
        # Make note of the starting site count
        starting_sites = Site.all()

        response = LambdaApiHandler.site_apis(event)
        self.assertEqual('200', response['statusCode'])
        self.assertEqual(len(starting_sites) + 1, len(Site.all()))

        # Fetch the site separately and validate the content
        site = Site.find('tc_lambda_sites_test_create_site')
        self.assertIsNotNone(site)
        self.assertEqual('tc_lambda_sites_test_create_site', site.name)
        self.assertEqual("1234 Fake Street", site.address)
        self.assertEqual('Red', site.availability_status)
        self.assertEqual(False, site.is_open)
        self.assertEqual('8-3', site.hours)

        # Cleanup.
        if site != None:
            site.delete()
        # Cleanup validation
        self.assertEqual(len(starting_sites), len(Site.all()),
                         "Failed to clean up the site we created!")
Example #24
0
 def post(self):
   site = Site.all().get()
   if(site):
     self.redirect("/")
   save_items = {'site.title':'','site.admin':'','site.password':''}
   form_items = ['site.title','site.admin','site.password']
   for item in form_items:
     if item in self.request.arguments():
       if self.request.get(item) != "":
         save_items[item] = self.request.get(item)
       else:
         self.json_out({"success":False,"message":"%s is not entered" % item})
         return False
     else:
       self.json_out({"success":False,"message":"%s is not in the form" % item})
       return False
   user = self.ws.users.get_current_user(self)
   site = Site.create(save_items['site.admin'],save_items['site.password'],save_items['site.title'],user)
   self.redirect('/')
Example #25
0
    def test_expects_new_site_from_url(self):
        # Arrange
        url = 'http://sub.domain.com/path?q=foo'

        # Act
        site = Site(url)

        # Assert
        self.assertEqual(url, site.url)
        self.assertEqual('http', site.scheme)
        self.assertEqual('http://sub.domain.com', site.base_url)
Example #26
0
    def respond(self):

        site_id = str(uuid.uuid4())[:8]
        site_key = uuid.uuid4()

        new_site = Site(site_id, site_key)
        db.session.add(new_site)
        db.session.commit()

        response = {'site_id': site_id, 'site_key': site_key}
        return render_template('template_signup.html', context=response)
Example #27
0
    def test_expects_page_instance(self):
        # Arrange
        domain = 'sub.domain.com'
        site = Site.from_domain_or_url(domain)

        # Act
        page = Page(site)

        # Assert
        self.assertIsInstance(page, Page)
        self.assertEqual(page.site, site)
        self.assertIn(domain, page.url)
Example #28
0
    def test_get_all(self):
        starting_sites = Site.all()

        sites = Site.all()
        self.assertTrue( len(sites) > 0, 'No sites found with Site.all()')
        site = sites[0]
        self.assertEqual('Chris\' Awesome Test Site #2', site.name)
        self.assertEqual('chris-awesome-test-site-2', site.slug)
        self.assertEqual("1234 Fake Street", site.xstreet)
        self.assertEqual('Universal City', site.xcity)
        self.assertEqual('78005', site.xzip)
        # self.assertEqual(Decimal('175.1'), site.latitude)
        # self.assertEqual(Decimal('176.0'), site.longitude)
        self.assertEqual('175.1', site.latitude)
        self.assertEqual('176.0', site.longitude)
        self.assertEqual('10am', site.opentime)
        self.assertEqual('6pm', site.closetime)
        self.assertEqual('M-T', site.days)
        self.assertEqual(None, site.sitecoordinator)
        self.assertEqual(True, site.is_open)

        self.assertEqual(len(starting_sites), len(Site.all()), 'Site.all() somehow altered the record count')
Example #29
0
 def test_auction_results_performance(self):
     """Evaluate response time for auction results"""
     bids = [
         Bid(Bidder('BRANDON', -0.001), 'banner', 50),
         Bid(Bidder('ASEMA', -0.0432), 'banner', 51)
     ]
     site = Site('test.com', [bids[0].bidder, bids[1].bidder], 40)
     auction = Auction(site, [AdUnit.banner], bids)
     time_start = time.time()
     auction.get_max_bids()
     time_end = time.time()
     time_span = time_end - time_start
     self.assertLess(time_span, 1, 'Results Method Performance Inadequate')
Example #30
0
    def test_expects_new_axe_page_audit(self):
        # Arrange
        url = 'https://sub.domain.com'
        site = Site(url)
        page = Page(site)

        # Act
        page_audit = AxePageAudit(page)

        # Assert
        self.assertIsInstance(page_audit, AxePageAudit)
        self.assertEqual(url, page_audit.url)
        self.assertListEqual([], page_audit.violations)
Example #31
0
    def test_expects_new_axe_site_audit(self, webmock):
        # Arrange
        webmock.get(requests_mock.ANY, text='ok')
        domain = 'sub.domain.com'
        site = Site(domain)

        # Act
        site_audit = AxeSiteAudit(site)

        # Assert
        self.assertIsInstance(site_audit, AxeSiteAudit)
        self.assertEqual(site, site_audit.site)
        self.assertListEqual([], site_audit.violations)
Example #32
0
    def test_expects_spider_instance(self, webmock):
        # Arrange
        domain = 'sub.domain.com'
        site = Site.from_domain_or_url(domain)
        webmock.get(requests_mock.ANY, text='ok')

        # Act
        spider = SitemapSpider(site)

        # Assert
        self.assertIsInstance(spider, SitemapSpider)
        self.assertEqual(site, spider.site)
        self.assertIn(site.base_url, spider.base_url)
Example #33
0
    def test_get_all(self):
        starting_sites = Site.all()

        sites = Site.all()
        self.assertTrue(len(sites) > 0, 'No sites found with Site.all()')
        site = sites[0]
        self.assertEqual('Chris\' Awesome Test Site #2', site.name)
        self.assertEqual('chris-awesome-test-site-2', site.slug)
        self.assertEqual("1234 Fake Street", site.xstreet)
        self.assertEqual('Universal City', site.xcity)
        self.assertEqual('78005', site.xzip)
        # self.assertEqual(Decimal('175.1'), site.latitude)
        # self.assertEqual(Decimal('176.0'), site.longitude)
        self.assertEqual('175.1', site.latitude)
        self.assertEqual('176.0', site.longitude)
        self.assertEqual('10am', site.opentime)
        self.assertEqual('6pm', site.closetime)
        self.assertEqual('M-T', site.days)
        self.assertEqual(None, site.sitecoordinator)
        self.assertEqual(True, site.is_open)

        self.assertEqual(len(starting_sites), len(Site.all()),
                         'Site.all() somehow altered the record count')
Example #34
0
def lambda_handler(event, context):
    
    sites = Site.all()
    
    if sites == None:
        return respond('500', '{"errorCode":"500","errorMessage":"Unable to fetch a list of sites"}')
    
    sites_json = []
    for site in sites:
        sites_json.append(site.to_json())
    j = ','.join(sites_json)
    response_body = "[ " + j + " ]"

    return respond('200', response_body)
Example #35
0
 def save_site_info(self):
     inputs = self.get_input()
     if web.ctx.method == "POST":
         username = inputs.get('username', '').strip()
         position = inputs.get('position', '').strip()
         case_number = inputs.get('case_number', '').strip()
         copy_right = inputs.get("copyright", '').strip()
         try:
             Site.update(username=username,
                         position=position,
                         case_number=case_number,
                         copyright=copy_right). \
                 where(Site.id == 1).execute()
             self.private_data["update_success"] = True
             return web.seeother(self.make_url('home'))
         except Exception as e:
             log.error('create album failed%s' % traceback.format_exc())
             self.private_data["update_success"] = False
             self.private_data["update_message"] = u"更新失败"
             return web.seeother(self.make_url('save_site_info'))
     if web.ctx.method == "GET":
         site = Site.get_or_none(Site.id == 1)
         self.private_data["site"] = site
         return self.display("admin/site_info")
    def test_as_item_returns_expected_results(self):
        data = googleData()

        site = Site('es', '')
        collection = Collection(site)
        collection.googleData = data

        # Assert data is turned right into a list of Items.
        assert collection.asItems()[1].name() == 'Nombre del objeto'

        # Assert data is skipped if all the fields are empty.
        assert collection.asItems()[0].name() == 'Nombre del objeto 2'

        # Assert empty list is returned when there's no data.
        collection.googleData = []
        assert collection.asItems() == []
Example #37
0
 def test_get_site_details(self):
     event = {
         'httpMethod': 'GET',
         'path': '/site/the-alamo',
         'resource': '/site/{sitename}',
         'pathParameters': {
             'sitename': 'the-alamo'
         },
         'body': None,
     }
     response = lambda_handler(event, None)
     self.assertIsNotNone(response)
     self.assertEqual('200', response['statusCode'], 'Maybe the data hasn\'t been created yet? This is a manual process until we get fixtures installed')
     site = Site.from_dict(json.loads(response['body']))
     self.assertEqual('the-alamo', site.slug)
     self.assertEqual('The Alamo', site.name)
Example #38
0
    def test_expects_new_site_from_domain(self, webmock):
        # Arrange
        domain = 'sub.domain.com'
        webmock.get(requests_mock.ANY, text='ok')

        # Act
        site = Site(domain)

        # Assert
        self.assertIsInstance(site, Site)
        self.assertEqual('https', site.scheme)
        self.assertEqual('sub', site.subdomain)
        self.assertEqual('domain', site.domain)
        self.assertEqual('com', site.tld)
        self.assertEqual('sub.domain.com', site.fqdn)
        self.assertEqual('https://sub.domain.com', site.url)
Example #39
0
 def test_get_site_details(self):
     event = {
         'httpMethod': 'GET',
         'path': '/site/the-alamo',
         'resource': '/site/{sitename}',
         'pathParameters': {
             'sitename': 'the-alamo'
         },
         'body': None,
     }
     response = GetSiteDetails.lambda_handler(event, None)
     self.assertIsNotNone(response)
     self.assertEqual('200', response['statusCode'])
     site = Site.from_dict(json.loads(response['body']))
     self.assertEqual('the-alamo', site.slug)
     self.assertEqual('The Alamo', site.name)
Example #40
0
    def test_expects_site_for_a_localhost_url(self):
        # Arrange
        url = 'http://localhost:3000/'

        # Act
        site = Site.from_domain_or_url(url)

        # Assert
        self.assertIsInstance(site, Site)
        self.assertEqual('http', site.scheme)
        self.assertEqual('', site.subdomain)
        self.assertEqual('localhost', site.domain)
        self.assertEqual('', site.tld)
        self.assertEqual('localhost', site.fqdn)
        self.assertEqual('http://localhost:3000/', site.url)
        self.assertEqual('http://localhost:3000', site.base_url)
Example #41
0
 def test_get_site_details(self):
     event = {
         'httpMethod': 'GET',
         'path': '/site/the-alamo',
         'resource': '/site/{sitename}',
         'pathParameters': {
             'sitename': 'the-alamo'
         },
         'body': None,
     }
     response = GetSiteDetails.lambda_handler(event, None)
     self.assertIsNotNone(response)
     self.assertEqual('200', response['statusCode'])
     site = Site.from_dict(json.loads(response['body']))
     self.assertEqual('the-alamo', site.slug)
     self.assertEqual('The Alamo', site.name)
Example #42
0
 def test_get_site_details(self):
     event = {
         'httpMethod': 'GET',
         'path': '/site/the-alamo',
         'resource': '/site/{sitename}',
         'pathParameters': {
             'sitename': 'the-alamo'
         },
         'body': None,
     }
     response = lambda_handler(event, None)
     self.assertIsNotNone(response)
     self.assertEqual('200', response['statusCode'], 'Maybe the data hasn\'t been created yet? This is a manual process until we get fixtures installed')
     site = Site.from_dict(json.loads(response['body']))
     self.assertEqual('the-alamo', site.slug)
     self.assertEqual('The Alamo', site.name)
Example #43
0
def lambda_handler(event, context):
    #get the site name from the url
    if 'pathParameters' not in event:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug specified in the path"}')
    if 'sitename' not in event['pathParameters']:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug found in the path parameters"}')
    site_name = urllib.parse.unquote(event['pathParameters']['sitename'])

    if len(site_name) == 0: 
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: Empty sitename"}')
        
    site = Site.find(site_name)

    if site is None:
        return respond('404', '{ "errorCode": "404", "errorMessage":"Invalid site name"}')

    return respond('200', site.to_json())
Example #44
0
 def test_get_one(self):
     site = Site.find('chris-awesome-test-site-2')
     self.assertIsNotNone(site, 'Default site not found. This probably needs to be created manually')
     self.assertEqual('Chris\' Awesome Test Site #2', site.name)
     self.assertEqual('chris-awesome-test-site-2', site.slug)
     self.assertEqual("1234 Fake Street", site.xstreet)
     self.assertEqual('Universal City', site.xcity)
     self.assertEqual('78005', site.xzip)
     # self.assertEqual(Decimal('175.1'), site.latitude)
     # self.assertEqual(Decimal('176.0'), site.longitude)
     self.assertEqual('175.1', site.latitude)
     self.assertEqual('176.0', site.longitude)
     self.assertEqual('10am', site.opentime)
     self.assertEqual('6pm', site.closetime)
     self.assertEqual('M-T', site.days)
     self.assertEqual(None, site.sitecoordinator)
     self.assertEqual(True, site.is_open)
Example #45
0
    def test_site_validation(self):
        site = Site()
        self.assertFalse(site.is_valid(), 'Default site values should not validate due to empty name and slug')

        site.name = "Valid Site Name"
        site.slug = 'valid-site-name'
        self.assertTrue(site.is_valid(), 'These hand-coded values should be valid')

        # Test some known-bad slugs
        bad_slugs = [
            'valid site name', # no whitespace
            'valid--site--name', # no repeated hyphens
            'Valid-Site-Name', # No capital letters
            'chris\'-awesome-site', # No apostrophes
        ]
        for bad_slug in bad_slugs:
            site.name = 'Valid Site Name'
            site.slug = bad_slug
            self.assertFalse(site.is_valid(), 'This slug should have been invalid: \'%(slug)\'' % site.slug)
Example #46
0
def lambda_handler(event, context):
    logger.info('got event{}'.format(event))
#get the site name from the url
    if 'pathParameters' not in event:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug specified in the path"}')
    if 'sitename' not in event['pathParameters']:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug found in the path parameters"}')
#    site_name = urllib.parse.unquote(event['pathParameters']['sitename'])
    # TODO: implement url decoding, or do pattern validation on the sitename
    site_name = event['pathParameters']['sitename']

    if len(site_name) == 0: 
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: Empty sitename"}')
        
    site = Site.find(site_name)
    if site is None: 
        return respond('404', '{ "errorCode": "404", "errorMessage":"Not Found: no Site found with that slug"}')
    
    #actually delete the site
    site.delete()
    return respond('200', '')
	def read(self, file):
		result = {
			"errors" : [],
			"data" : [],
			"dialect" : None
		}
		csvio = StringIO.StringIO(file)
		dialect = csv.Sniffer().sniff(file)
		csvreader = csv.DictReader(csvio, dialect = dialect)
		for row in csvreader:
			result["data"].append(row)
			"""
			Here we need to render each user account
			store it and get ready to start sending emails etc.
			"""
			if not row.get('             E-MAIL  ADDRESS', None):
				result['errors'].append({
					"message" : "Could not retrieve field             E-MAIL  ADDRESS",
					"row" : row
				})
				continue
			new_user = User.get_by_email(row.get('             E-MAIL  ADDRESS', 'CANCEL'))
			if not new_user:
				site = Site.all().get()
				new_user = User.create_user(row.get('             E-MAIL  ADDRESS', 'NONE'), 'NONE', site.secret)
			new_user.firstname = row.get('FIRST NAME', None)
			new_user.lastname = row.get('LAST NAME', None)
			new_user.spouse = row.get('SPOUSE', None)
			new_user.address = row.get('ADDRESS LINE 1', None) + '\n' + row.get('ADDRESS LINE 2', None) + '\n' + row.get('CITY', None) + '\n' + row.get('STATE', None) + ',' + row.get('ZIP', None) + '\n' + row.get('COUNTRY', None)
			if row.get('PHONE NUMBER', None):
				new_user.phone = row.get('PHONE NUMBER', None)
			if row.get('FAX NUMBER', None):
				new_user.fax = row.get('FAX NUMBER', None)
			
			new_user.put()
		
		#clear the user cache
		cache.Cache().clear()
		return result
Example #48
0
def lambda_handler(event, context):
    print("Recompiling All Sites static JSON")

    print("Uploading to S3")
    SiteContentCompiler.compileSiteJson(Site.all())
Example #49
0
    def test_create_new(self):
        # Keep track of the initial set, so that we can discern which changes were caused by this test
        starting_sites = Site.all()

        site = Site()
        site.name = 'Chris\' Awesome Test Site #1'
        site.slug = 'chris-awesome-test-site-1'
        site.xstreet = '1234 Fake Street'
        site.xcity = 'Universal City'
        site.xzip = '78005'
        # site.latitude = Decimal('175.1')
        # site.longitude = Decimal('176.0')
        site.latitude = '175.1'
        site.longitude = '176.0'
        site.opentime = '10am'
        site.closetime = '6pm'
        site.days = 'M-T'
        site.sitecoordinator = None # TODO: test variations of this too
        site.sitetype = 'Tax Preparation'

        site.is_open = True

        result = site.save()
        self.assertEqual(200, result, 'Failed to save the new site')
        # Validate that the record was indeed written out to the DB
        self.assertEqual(len(starting_sites)+1, len(Site.all()), 'No Site record was actually written')

        # # Now fetch the site data back out
        site2 = Site.find('chris-awesome-test-site-1')
        self.assertEqual('Chris\' Awesome Test Site #1', site2.name)
        self.assertEqual('chris-awesome-test-site-1', site2.slug)
        self.assertEqual("1234 Fake Street", site2.xstreet)
        self.assertEqual('Universal City', site2.xcity)
        self.assertEqual('78005', site2.xzip)
        # self.assertEqual(Decimal('175.1'), site2.latitude)
        # self.assertEqual(Decimal('176.0'), site2.longitude)
        self.assertEqual('175.1', site2.latitude)
        self.assertEqual('176.0', site2.longitude)
        self.assertEqual('10am', site2.opentime)
        self.assertEqual('6pm', site2.closetime)
        self.assertEqual('M-T', site2.days)
        self.assertEqual(None, site2.sitecoordinator)
        self.assertEqual(True, site2.is_open)
        
        # Delete the newly created site
        self.assertEqual(200, site2.delete())
        self.assertEqual(len(starting_sites), len(Site.all()), 'The site creation test failed to clean up after itself')
Example #50
0
File: site.py Project: CMGS/ymir
def get_site_by_token(token):
    site = local_cache.get(token, None)
    if not site:
        site = Site.select().where(Site.token == token).first()
        local_cache[token] = site
    return site
Example #51
0
def lambda_handler(event, context):
    logger.info('got event{}'.format(event))
    # Extract the ID from the path parameters
    if 'pathParameters' not in event:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug specified in the path"}')
    if 'sitename' not in event['pathParameters']:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug found in the path parameters"}')
    if 'body' not in event:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site data attached in the request body."}')
    if event['body'] is None:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No valid Site data attached in the request body."}')

    #site_name = urllib.parse.unquote(event['pathParameters']['sitename'])
    # TODO: either validate that the sitename is a properly-formatted slug, or run it through url decoding first
    site_name = event['pathParameters']['sitename']

    # Fetch from the DB and validate that a record WAS found
    site = Site.find(site_name)
    update_count = 0
    if site is None:
        return respond('404', '{ "errorCode": "404", "errorMessage":"Invalid site name"}')

    # Check for fields being updated
    site_data = json.loads(event['body'])
    if 'name' in site_data:
        site.name = site_data['name']
        update_count += 1
    if 'xstreet' in site_data:
        site.xstreet = site_data['xstreet']
        update_count += 1
    if 'xcity' in site_data:
        site.xcity = site_data['xcity']
        update_count += 1
    if 'xzip' in site_data:
        site.xzip = site_data['xzip']
        update_count += 1
    if 'latitude' in site_data:
        site.latitude = site_data['latitude']
        update_count += 1
    if 'longitude' in site_data:
        site.longitude = site_data['longitude']
        update_count += 1
    if 'opentime' in site_data:
        site.opentime = site_data['opentime']
        update_count += 1
    if 'closetime' in site_data:
        site.closetime = site_data['closetime']
        update_count += 1
    if 'days' in site_data:
        site.days = site_data['days']
        update_count += 1
    if 'sitecoordinator' in site_data:
        site.sitecoordinator = site_data['sitecoordinator']
        update_count += 1
    if 'sitetype' in site_data:
        site.sitetype = site_data['sitetype']
        update_count += 1

    if update_count == 0:
        # return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No (valid) fields updated in the request body."}')
        # On second thought, let's let this operation succeed. Why not?
        # As far as the requester is concerned, the updates they requested have already been applied.
        # Also, this will even be faster than submitting a PutItem request with no purpose.
        logger.debug("No actual updates to run, so just return the site object as-is")
        return respond('200', site.to_json())

    results = site.save()
    if results is None:
        return respond('500', '{ "errorCode": "500", "errorMessage":"Server error: failed to save"}')

    # Reload the object from the database to ensure that any on-save hooks are accounted for
    response_body = Site.find(site.slug).to_json()
    return respond('200', response_body)
Example #52
0
 def get(self):
   site = Site.all().get()
   if(site):
     self.redirect("/")
   self.render_out("templates/install.html")
Example #53
0
 def get(self, args):
   array_args = args.split("/")
   key = array_args[1]
   self.json_out(Site.export(key))
Example #54
0
    def site_apis(event):
        """ Handle all of the Site Management API endpoints """
        response_body = ''
        response_code = '200'

        site_name = None if event['pathParameters'] == None else event['pathParameters']['sitename']
        site_data = LambdaApiHandler.deserialize_site(event) # This will simply return None if there is no (correctly formatted) data in the request body
        
        if event['httpMethod'] == 'GET':
            if site_name == None:
                # Fetch all sites
                print("Fetching all sites")
                sites = Site.all()
                sites_json = []
                for site in sites:
                    sites_json.append(site.to_json())
                j = ','.join(sites_json)
                response_body = "[ " + j + " ]"
                response_code = '200'
                print("Compiled response: " + response_code + " : " + response_body)
            else:
                # Fetch single site
                print("Querying a single site: " + site_name)
                site = Site.find(site_name)
                response_body = site.to_json()
                response_code = '200'
        
        elif event['httpMethod'] == 'PUT':
            # Create a new site
            if site_data == None:
                response_body = '{"error":"Invalid Site data in request body"}'
                response_code = '400'
            else:
                if site_data.save():
                    response_body = Site.find(site_data.name).to_json() # Reload the object from the database to ensure that any on-save hooks are accounted for
                    response_code = '200'
                else:
                    response_body = '{"error":"failed to create site"}'
                    response_code = '500'
        
        elif event['httpMethod'] == 'POST':
            # Update an existing site status
            if site_name == None:
                response_body = '{"error":"bad request. Please specify the sitename path parameter"}'
                response_code = '400'
            elif site_data == None:
                response_body = '{"error":"Invalid Site data in request body"}'
                response_code = '400'
            else:
                if site_data.save():
                    response_body = ''
                    response_code = '200'
                else:
                    response_body = '{"error":"failed to update site"}'
                    response_code = '500'
        
        elif event['httpMethod'] == 'DELETE':
            # Destroy an existing Site
            if site_name == None:
                response_body = '{"error":"bad request. Please specify the sitename path parameter"}'
                response_code = '400'
            else:
                site = Site.find(site_name)
                if site == None:
                    response_body = '{"error":"Invalid site_name"}'
                    response_code = '400'
                elif site.delete():
                    response_body = ''
                    response_code = '200'
                else:
                    response_body = '{"error":"failed to delete site"}'
                    response_code = '400'
        else:
            response_body = '{"error":"bad request"}'
            response_code = '400'
        
        #utilities.respond(response_code, response_body) # TODO: test this method before implementing
        return {
            'statusCode': response_code,
            'body': response_body,
            'headers': {
                'Content-Type': 'application/json'
            },
        }
Example #55
0
File: init.py Project: CMGS/ymir
#!/usr/bin/python
#coding:utf-8

import logging
from models.site import Site, Block

logger = logging.getLogger('peewee')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())

Site.create_table(fail_silently=True)
Block.create_table(fail_silently=True)