Delphi mock and databases - database

I was reading Nick Hodges' blog http://nickhodges.com/post/Delphi-Mocks-The-Basics.aspx which is very interesting.
However it doesn't say how I can test classes with statements referring to databases in it for instance TQuery.Next or TQuery.ExecSQL or TQuery.FieldByName... etc
Did anybody face the same issue ? If so how did you solve it ?

What we have done at work is to have repositories that return a TDataSet. This way, you create a mock/fake of the repository (depending if you want to test how many tests methods get called, etc). Example:
TMyDatabaseRepository = class(TInterfacedObject, IMyDatabaseRepository)
// .. blah ..
function GetAllTheFun : TDataSet;
// .. blah ..
end;
TMyProcessThatAccessesTheDatabase = class
// .. blah ..
public
constructor Create(const AMyDatabaseRepository : IMyDatabaseRepository);
// .. blah ..
end;
So when it comes to testing, we passing in a mock IMyDatabaseRepository. GetAllTheFun actually returns a TKbmMemTable with data sample data set up.
While I haven't used Delphi Mocks, I do remember that you can override methods on the 'fly' (or something like that), so you might not need to go through the trouble of creating a separate class that implements IMyDatabaseRepository
Edit:
That is a fair large subject to try and cover here but there a few number of web sites (blogs) that cover this type of thing:
http://delphisorcery.blogspot.com.au/2011/09/pimp-your-unit-tests-using-mock-objects.html
http://www.finalbuilder.com/Resources/Blogs/PostId/417/introducing-delphi-mocks.aspx
http://blog.synopse.info/post/2012/10/14/Stubs-and-Mocks-for-Delphi-with-mORMot
http://blog.synopse.info/post/2012/10/14/Interfaces-in-practice%3A-dependency-injection%2C-stubs-and-mocks
http://blog.synopse.info/post/2012/10/14/Advanced-mocks-and-stubs

Related

cakePHP get a variable from each Model and Controller

I got a question. I have a db table with settings (id, name).
If I read them from the db
$settings = $this->Setting->find('list');
How can I do this in the AppController or something like that to access from each Controller and Model?
Hope someone can help me.
Thanks
Explanation:
I would assume you're looking for something like below (Obviously you'll want to tweak it per your own application, but - it's the idea).
In the app controller, it
finds the settings from the table
repeats through each and puts each one into a "Configure" variable
Code:
/**
* Read settings from DB and populate them in constants
*/
function fetchSettings(){
$this->loadModel('Setting');
$settings = $this->Setting->findAll();
foreach($settings as $settingsData) {
$value = $settingsData['Setting']['default_value'];
//note: can't check for !empty because some values are 0 (zero)
if(isset($settingsData['Setting']['value'])
&& $settingsData['Setting']['value'] !== null
&& $settingsData['Setting']['value'] !== '') {
$value = $settingsData['Setting']['value'];
}
Configure::write($settingsData['Setting']['key'], $value);
}
}
Then, you can access them anywhere in your app via Configure::read('myVar');
A warning from the CakePHP book about Configure variables. (I think they're fine to use in this case, but - something to keep in mind):
CakePHP’s Configure class can be used to store and retrieve
application or runtime specific values. Be careful, this class allows
you to store anything in it, then use it in any other part of your
code: a sure temptation to break the MVC pattern CakePHP was designed
for. The main goal of Configure class is to keep centralized variables
that can be shared between many objects. Remember to try to live by
“convention over configuration” and you won’t end up breaking the MVC
structure we’ve set in place.

getting all instances of IFoo from MEF aggregatecatalog in silverlight

I am sure this cant be hard - can it?
the only function seems to be GetExports but that seems to take 2 generic parameters plus a ExportDefintion that itself takes 5 values including a lambda - surely not? I thought I could do something like agcat.GetExports<IFoo>()
You don't get instances from a catalog you get them from a container.
var container = new CompositionContainer(agCat);
var foos = container.GetExports<IFoo>(); // Or GetExportedValues<IFoo>()

Display a (Synopse) SQLite3 table-column in a Delphi7 TListView

I would like to take the following unit (DrivesData) and display the drive column in a TListView. I've never worked with the (Synopse) SQLite3 code before so I'm hoping someone could give me a little push in the right direction.
Just add the DrivesData unit to the uses clause then run and it will create the "drives.sqlite" database file with a list of drives 'A' to 'Z'.
unit DrivesData;
interface
uses
SynCommons, SQLite3Commons;
type
TDrives = class(TSQLRecord)
private
{ Private declarations }
FDrive: RawUTF8;
protected
{ Protected declarations }
FDrivesModel: TSQLModel;
FDrivesDatabase: TSQLRest;
public
{ Public declarations }
constructor Create(); override;
destructor Destroy(); override;
published
{ Published declarations }
property Drive: RawUTF8 read FDrive write FDrive;
end;
var
DriveRecord: TDrives;
implementation
uses
SQLite3;
function CreateDrivesModel(): TSQLModel;
begin
Result := TSQLModel.Create([TDrives]);
end;
{ TDrives }
constructor TDrives.Create();
var
X: Char;
begin
inherited Create();
FDrivesModel := CreateDrivesModel();
FDrivesDatabase := TSQLRestServerDB.Create(FDrivesModel, 'drives.sqlite');
TSQLRestServerDB(FDrivesDatabase).DB.Execute(
'CREATE TABLE IF NOT EXISTS drives ' +
'(id INTEGER PRIMARY KEY, drive TEXT NOT NULL UNIQUE COLLATE NOCASE);');
for X := 'A' to 'Z' do
begin
TSQLRestServerDB(FDrivesDatabase).DB.Execute(
'INSERT OR IGNORE INTO drives (drive) VALUES ("' + X + ':")');
end;
end;
destructor TDrives.Destroy();
begin
if Assigned(FDrivesDatabase) then
FDrivesDatabase.Free();
if Assigned(FDrivesModel) then
FDrivesModel.Free();
inherited Destroy();
end;
initialization
DriveRecord := TDrives.Create();
finalization
if Assigned(DriveRecord) then
DriveRecord.Free();
end.
Nice try!
But I'm afraid you are missing some points of the framework:
for instance you're mixing record level and MVC application level: a TSQLRecord maps a DB table and you should not declare MVC TSQLModel and TSQLRest inside this class;
and you're missing the ORM approach, you don't need to write all those SQL code (the CREATE TABLE and the INSERT): the framework will write it for you, with no error, and the exact expected column type (with collations)!
Instead of using a TSQLRestServerDB directly by itself, you should better use a TSQLRestClientDB (which will instantiate its privately owned TSQLRestServerDB), even if you are still working locally. So you'll get a lot more features with no performance penalty.
You are using a Char type in your code. Our framework is UTF-8 oriented, so you should use AnsiChar instead, or use StringToUtf8() function to ensure correctness (at least with Unicode version of Delphi).
I'll recommend that you take a look at the sample code source code and the provided documentation (especially the SAD document, in the general presentation in the first pages, including the SynFile main demo).
To retrieve some data, then display it in the VCL (e.g. in a TListBox), take a look at the TSQLTableJSON class. There are some code sample in the SAD document (take a look at the keyword index, at the beginning of the document, if you're a bit lost).
Perhaps StackOverflow is not the best place to ask such specific questions. You have our forum available at http://synopse.info to post any questions regarding this framework. You can post your code here.
Thanks for your interest!

Idiomatic List Wrapper

In Google App Engine, I make lists of referenced properties much like this:
class Referenced(BaseModel):
name = db.StringProperty()
class Thing(BaseModel):
foo_keys = db.ListProperty(db.Key)
def __getattr__(self, attrname):
if attrname == 'foos':
return Referenced.get(self.foo_keys)
else:
return BaseModel.__getattr__(self, attrname)
This way, someone can have a Thing and say thing.foos and get something legitimate out of it. The problem comes when somebody says thing.foos.append(x). This will not save the added property because the underlying list of keys remains unchanged. So I quickly wrote this solution to make it easy to append keys to a list:
class KeyBackedList(list):
def __init__(self, key_class, key_list):
list.__init__(self, key_class.get(key_list))
self.key_class = key_class
self.key_list = key_list
def append(self, value):
self.key_list.append(value.key())
list.append(self, value)
class Thing(BaseModel):
foo_keys = db.ListProperty(db.Key)
def __getattr__(self, attrname):
if attrname == 'foos':
return KeyBackedList(Thing, self.foo_keys)
else:
return BaseModel.__getattr__(self, attrname)
This is great for proof-of-concept, in that it works exactly as expected when calling append. However, I would never give this to other people, since they might mutate the list in other ways (thing[1:9] = whatevs or thing.sort()). Sure, I could go define all the __setslice__ and whatnot, but that seems to leave me open for obnoxious bugs. However, that is the best solution I can come up with.
Is there a better way to do what I am trying to do (something in the Python library perhaps)? Or am I going about this the wrong way and trying to make things too smooth?
If you want to modify things like this, you shouldn't be changing __getattr__ on the model; instead, you should write a custom Property class.
As you've observed, though, creating a workable 'ReferenceListProperty' is difficult and involved, and there are many subtle edge cases. I would recommend sticking with the list of keys, and fetching the referenced entities in your code when needed.

How do I dynamically determine if a Model class exist in Google App Engine?

I want to be able to take a dynamically created string, say "Pigeon" and determine at runtime whether Google App Engine has a Model class defined in this project named "Pigeon". If "Pigeon" is the name of a existant model class, I would like to then get a reference to the Pigeon class so defined.
Also, I don't want to use eval at all, since the dynamic string "Pigeon" in this case, comes from outside.
You could try, although probably very, very bad practice:
def get_class_instance(nm) :
try :
return eval(nm+'()')
except :
return None
Also, to make that safer, you could give eval a locals hash: eval(nm+'()', {'Pigeon':pigeon})
I'm not sure if that would work, and it definitely has an issue: if there is a function called the value of nm, it would return that:
def Pigeon() :
return "Pigeon"
print(get_class_instance('Pigeon')) # >> 'Pigeon'
EDIT: Another way of doing it is possibly (untested), if you know the module:
(Sorry, I keep forgetting it's not obj.hasattr, its hasattr(obj)!)
import models as m
def get_class_instance(nm) :
if hasattr(m, nm) :
return getattr(m, nm)()
else : return None
EDIT 2: Yes, it does work! Woo!
Actually, looking through the source code and interweb, I found a undocumented method that seems to fit the bill.
from google.appengine.ext import db
key = "ModelObject" #This is a dynamically generated string
klass = db.class_for_kind(key)
This method will throw a descriptive exception if the class does not exist, so you should probably catch it if the key string comes from the outside.
There's two fairly easy ways to do this without relying on internal details:
Use the google.appengine.api.datastore API, like so:
from google.appengine.api import datastore
q = datastore.Query('EntityType')
if q.get(1):
print "EntityType exists!"
The other option is to use the db.Expando class:
def GetEntityClass(entity_type):
class Entity(db.Expando):
#classmethod
def kind(cls):
return entity_type
return Entity
cls = GetEntityClass('EntityType')
if cls.all().get():
print "EntityType exists!"
The latter has the advantage that you can use GetEntityClass to generate an Expando class for any entity type, and interact with it the same way you would a normal class.

Resources