def test_filter_without_label(self): """Test filtering using default label.""" q = Query('Host') q.filter('hostname', '=', 'somehostname') expected = 'WHERE host.hostname = $filterval0' self.assertTrue(expected in str(q)) self.assertEquals(q.params['filterval0'], 'somehostname')
def times(self, request): """Get times an object has changed. The object's created_at time will be added if not present. """ # Validate input times = TimesChangedSerializer(data=request.data) if not times.is_valid(): raise ValidationError(times.errors) vd = times.validated_data # Find object by type and identity query = Query(vd.get('model')) \ .identity(vd.get('identity')) \ .time(vd.get('time')) records = query.fetch() # Raise 404 if not found if not records: raise Http404() created_at = records[0][vd.get('model')]['created_at'] # Build query to get times logger.debug("GETTING TIMES") times = self._times(vd['model'], vd['identity']) if created_at not in times: times.append(created_at) results = GenericSerializer({'data': vd, 'times': times}) return Response(results.data)
def test_filter_calls_prep_val(self, m_prep): q = Query('Host') q.filter('processor_cores', '=', '42') m_prep.assert_called_once_with('Host', 'processor_cores', '42', raise_for_error=False)
def test_page_with_page(self, m_fetch): """Test providing page with a page and a size.""" q = Query('Environment') q.page(page=3, pagesize=500) expected = "SKIP 1000" self.assertTrue(expected in str(q)) expected = "LIMIT 500" self.assertTrue(expected in str(q))
def test_page_with_negative_index(self, m_fetch): """Test providing page with a negative index and a size.""" q = Query('Environment') q.page(index=-10, pagesize=500) expected = "SKIP 0" self.assertTrue(expected in str(q)) expected = "LIMIT 500" self.assertTrue(expected in str(q))
def test_count(self, m_connection): """Tests counting number of results.""" data = FakeRecords() data.append({'total': 13}) data = [data] m_connection.return_value = FakeConnection(data) q = Query('Environment') self.assertEquals(q.count(), 13)
def test_page_defaults(self, m_fetch): """Test default arguments to page() method.""" q = Query('Environment') q.page() expected = 'SKIP 0' self.assertTrue(expected in str(q)) expected = 'LIMIT 100' self.assertTrue(expected in str(q))
def _exists(self, model, identity, time): """Check that an instance of a model exists at a time. :param model: Name of the model :type model: str :param identity: Identity of the instance of the model. :type identity: str :param time: Time to verify in milliseconds since epoch :type type: int """ query = Query(model).identity(identity).time(time) records = query.fetch() logger.debug("Found {} matches for time {}".format(len(records), time)) return len(records) > 0
def test_rel_filters(self): """Test adding time filters on relationships.""" q = Query('Virtualenv') expected = ( "r0.from <= $time < r0.to AND r1.from <= $time < r1.to " "AND r_environment_state.from <= $time < r_environment_state.to " "AND r_host_state.from <= $time < r_host_state.to") self.assertTrue(expected in str(q))
def test_match_with_state(self): """Test match clause including a model with state.""" q = Query('Host') expected = ( "MATCH (environment:Environment)-[r0:HAS_HOST]->(host:Host) " "\nMATCH (environment)-[r_environment_state:HAS_STATE]" "->(environment_state:EnvironmentState) " "\nMATCH (host)-[r_host_state:HAS_STATE]->(host_state:HostState)") self.assertTrue(expected in str(q))
def test_default_time(self, m_now): """Test that default time parameter.""" q = Query('Environment') self.assertEquals(q.params['time'], 10) q = Query('Environment') q.time(None) self.assertEquals(q.params['time'], 10)
def test_multiple_filters(self): """Tests more than one filters.""" q = Query('Host') q.filter('hostname', '=', 'somehostname') q.filter('kernel', '=', 'somekernel') expected = ('WHERE host.hostname = $filterval0 AND ' 'host_state.kernel = $filterval1') self.assertTrue(expected in str(q))
def test_orderby_multiple(self): """Test multiple orderby statements.""" q = Query('Environment') q.orderby('account_number', 'ASC', label='Environment') q.orderby('name', 'DESC', label='Environment') expected = ("ORDER BY environment.account_number ASC, " "environment.name DESC") self.assertTrue(expected in str(q))
def search(self, request): """Search objects by type, identity, and property filters.""" search = SearchSerializer(data=request.data) if not search.is_valid(): raise ValidationError(search.errors) vd = search.validated_data query = Query(vd.get('model')) \ .identity(vd.get('identity')) \ .time(vd.get('time')) for f in vd.get('filters', []): query.filter(f['prop'], f['operator'], f['value'], label=f['model']) for o in vd.get('orders', []): query.orderby(o['prop'], o['direction'], label=o['model']) count = query.count() records = query.page(page=vd['page'], pagesize=vd['pagesize'], index=vd.get('index')) serializer = GenericSerializer({ 'query': str(query), 'data': vd, 'params': query.params, 'count': count, 'pagesize': vd['pagesize'], 'page': vd['page'], 'records': records }) return Response(serializer.data)
def test_orderby_no_label(self): """Test a single nondefault orderby""" q = Query('Environment') q.orderby('account_number', 'DESC') expected = "ORDER BY environment.account_number DESC" self.assertTrue(expected in str(q))
def test_orderby_invalid_property(self): """Test that orderby raises InvalidPropertyError""" q = Query('Environment') with self.assertRaises(InvalidPropertyError): q.orderby('invalidproperty', 'ASC')
def test_return_root_label(self): """Test return clause targeted at a root level model.""" q = Query('Environment') expected = "RETURN environment" self.assertTrue(expected in str(q))
def test_match_root_label(self): """Test match clause targeted at a root level model.""" q = Query('Environment') expected = "MATCH (environment:Environment)" self.assertTrue(expected in str(q))
def test_skip(self): """Test query where skip has been set.""" q = Query('Environment') q.skip(5) q.skip(10) self.assertTrue('SKIP 10' in str(q))
def test_skip_none(self): """Test query where no skip has been set.""" q = Query('Environment') self.assertFalse('SKIP' in str(q))
def test_limit(self): """Test query where a limit as been set.""" q = Query('Environment') q.limit(5) q.limit(10) self.assertTrue('LIMIT 10' in str(q))
def test_limit_none(self): """Test query where no limit has been set.""" q = Query('Environment') self.assertFalse('LIMIT' in str(q))
def test_orderby_state_property(self): """Test orderby on a state property.""" q = Query('Host') q.orderby('kernel', 'DESC', label='Host') expected = 'ORDER BY host_state.kernel DESC' self.assertTrue(expected in str(q))
def test_orderby_default(self): """Test default orderby clause.""" q = Query('Environment') expected = "ORDER BY environment.uuid ASC" self.assertTrue(expected in str(q))
def test_provided_time(self): """Test that providing a time changes the query params.""" q = Query('Environment') q.time(3) self.assertEquals(q.params['time'], 3)
def test_filter_with_label(self): """Test filtering with a non default label.""" q = Query('Host') q.filter('account_number', '=', 'somenumber', label='Environment') expected = 'WHERE environment.account_number = $filterval0' self.assertTrue(expected in str(q))
def test_filter_invalid_label(self): """Test filtering with invalid label.""" q = Query('Host') with self.assertRaises(InvalidLabelError): q.filter('someprop', 'someop', 'someval', label='InvalidLabel')
def test_filter_invalid_prop(self): """Test filtering with invalid property.""" q = Query('Host') with self.assertRaises(InvalidPropertyError): q.filter('someinvalidprop', 'someop', 'someval')
def test_return_with_state(self): """Test return clause that should include state.""" q = Query('Host') expected = 'RETURN environment, environment_state, host, host_state' self.assertTrue(expected in str(q))
def test_orderby_invalid_label(self): """Test that orderby raises InvalidLabelError""" q = Query('Environment') with self.assertRaises(InvalidLabelError): q.orderby('aproperty', 'DESC', label='invalidlabel')