parameterized at TestClass level in JUnit? - junit

I have a set of tests cases in a single JUnit class, say test1() and test2().
Example:
class Template
{
test1()
test2()
}
I want to execute my set of tests(test class) over the elements in a list. For example, let's say I had a list of table names (e.g., table1, table2, ...), and I want to execute my set of tests over each table name.
Need test results as follow,
table1
test1_result
test2_result
table2
test1_result
test2_result
I have searched, found 'Parameterized test cases' but this is parameterized at test case level, but i need parameterized at Test class level. is this possible?

I think you are confused about Parameterized or didn't describe your needs well. What you describe is what Parameterized does. For each input to your test class (each array returns from Parameters) every unit test in the class is run. So if you pass table1 and table2 to your class, test1 and test2 will each be run twice, once with table1 and once with table2.
If this is not what you are looking for, please describe the difference between Parameterized and what you are looking for better.

Related

Understanding SQL Aliases

I understand the concept of SQL aliases, but in the following doctrine query language example, the alias is at the front of the table names, as well as following behind them. Could someone help explain whats happening in this query? I want to try to get a better understanding of whats happening before i attempt to alter it.
public function getByDomain($domain)
{
return $this->createQuery('d')->select('d.*, c.*, p.*, cl.*')
->innerJoin('d.Table1 c')
->innerJoin('c.Table2 p')->innerJoin('c.Table3 cl')
->where('d.name=?',$domain)->fetchOne();
}
What is happening is that you are calling $this->createQuery() from inside a method that resides in a class that extends Doctrine_Table. The createQuery() method takes one parameter $alias, and returns a Doctrine_Query object with the 'from' automatically added in (that is why there is no ->from() call in the statement).
The full code probably looks like this:
class DomainTable extends Doctrine_Table
{
public function getByDomain($domain)
{
return $this->createQuery('d')->select('d.*, c.*, p.*, cl.*')
->innerJoin('d.Table1 c')
->innerJoin('c.Table2 p')->innerJoin('c.Table3 cl')
->where('d.name=?',$domain)->fetchOne();
}
}
In Doctrine, the alias can be used in front of the other model names you want to perform a join on. Doctrine will automatically determine the foreign keys if you have the proper relations defined in your schema files.
So this code is selecting all columns from Domain, Table1, Table2 and Table3 where the Domain.name column matches $domain, and only returns 1 result (LIMIT 1).

Why does MySQL permit non-exact matches in SELECT queries?

Here's the story. I'm testing doing some security testing (using zaproxy) of a Laravel (PHP framework) application running with a MySQL database as the primary store for data.
Zaproxy is reporting a possible SQL injection for a POST request URL with the following payload:
id[]=3-2&enabled[]=on
Basically, it's an AJAX request to turn on/turn off a particular feature in a list. Zaproxy is fuzzing the request: where the id value is 3-2, there should be an integer - the id of the item to update.
The problem is that this request is working. It should fail, but the code is actually updating the item where id = 3.
I'm doing things the way I'm supposed to: the model is retrieved using Eloquent's Model::find($id) method, passing in the id value from the request (which, after a bit of investigation, was determined to be the string "3-2"). AFAIK, the Eloquent library should be executing the query by binding the ID value to a parameter.
I tried executing the query using Laravel's DB class with the following code:
$result = DB::select("SELECT * FROM table WHERE id=?;", array("3-2"));
and got the row for id = 3.
Then I tried executing the following query against my MySQL database:
SELECT * FROM table WHERE id='3-2';
and it did retrieve the row where id = 3. I also tried it with another value: "3abc". It looks like any value prefixed with a number will retrieve a row.
So ultimately, this appears to be a problem with MySQL. As far as I'm concerned, if I ask for a row where id = '3-2' and there is no row with that exact ID value, then I want it to return an empty set of results.
I have two questions:
Is there a way to change this behaviour? It appears to be at the level of the database server, so is there anything in the database server configuration to prevent this kind of thing?
This looks like a serious security issue to me. Zaproxy is able to inject some arbitrary value and make changes to my database. Admittedly, this is a fairly minor issue for my application, and the (probably) only values that would work will be values prefixed with a number, but still...
SELECT * FROM table WHERE id= ? AND ? REGEXP "^[0-9]$";
This will be faster than what I suggested in the comments above.
Edit: Ah, I see you can't change the query. Then it is confirmed, you must sanitize the inputs in code. Another very poor and dirty option, if you are in an odd situation where you can't change query but can change database, is to change the id field to [VAR]CHAR.
I believe this is due to MySQL automatically converting your strings into numbers when comparing against a numeric data type.
https://dev.mysql.com/doc/refman/5.1/en/type-conversion.html
mysql> SELECT 1 > '6x';
-> 0
mysql> SELECT 7 > '6x';
-> 1
mysql> SELECT 0 > 'x6';
-> 0
mysql> SELECT 0 = 'x6';
-> 1
You want to really just put armor around MySQL to prevent such a string from being compared. Maybe switch to a different SQL server.
Without re-writing a bunch of code then in all honesty the correct answer is
This is a non-issue
Zaproxy even states that it's possibly a SQL injection attack, meaning that it does not know! It never said "umm yeah we deleted tables by passing x-y-and-z to your query"
// if this is legal and returns results
$result = DB::select("SELECT * FROM table WHERE id=?;", array("3"));
// then why is it an issue for this
$result = DB::select("SELECT * FROM table WHERE id=?;", array("3-2"));
// to be interpreted as
$result = DB::select("SELECT * FROM table WHERE id=?;", array("3"));
You are parameterizing your queries so Zaproxy is off it's rocker.
Here's what I wound up doing:
First, I suspect that my expectations were a little unreasonable. I was expecting that if I used parameterized queries, I wouldn't need to sanitize my inputs. This is clearly not the case. While parameterized queries eliminate some of the most pernicious SQL injection attacks, this example shows that there is still a need to examine your inputs and make sure you're getting the right stuff from the user.
So, with that said... I decided to write some code to make checking ID values easier. I added the following trait to my application:
trait IDValidationTrait
{
/**
* Check the ID value to see if it's valid
*
* This is an abstract function because it will be defined differently
* for different models. Some models have IDs which are strings,
* others have integer IDs
*/
abstract public static function isValidID($id);
/**
* Check the ID value & fail (throw an exception) if it is not valid
*/
public static function validIDOrFail($id)
{
...
}
/**
* Find a model only if the ID matches EXACTLY
*/
public static function findExactID($id)
{
...
}
/**
* Find a model only if the ID matches EXACTLY or throw an exception
*/
public static function findExactIDOrFail($id)
{
...
}
}
Thus, whenever I would normally use the find() method on my model class to retrieve a model, instead I use either findExactID() or findExactIDOrFail(), depending on how I want to handle the error.
Thank you to everyone who commented - you helped me to focus my thinking and to understand better what was going on.

SQL select everything with arbitrary IN clause

This will sound silly, but trust me it is for a good (i.e. over-engineered) cause.
Is it possible to write a SQL query using an IN clause which selects everything in that table without knowing anything about the table? Keep in mind this would mean you can't use a subquery that references the table.
In other words I would like to find a statement to replace "SOMETHING" in the following query:
SELECT * FROM table_a WHERE table_a.id IN (SOMETHING)
so that the results are identical to:
SELECT * FROM table_a
by doing nothing beyond changing the value of "SOMETHING"
To satisfy the curious I'll share the reason for the question.
1) I have a FactoryObject abstract class which grants all models that extend it some glorious factory method magic using two template methods: getData() and load()
2) Models must implement the template methods. getData is a static method that accepts ID constraints, pulls rows from the database, and returns a set of associative arrays. load is not static, accepts an associative array, and populates the object based on that array.
3) The non-abstract part of FactoryObject implements a getObject() and a getObjects() method. These call getData, create objects, and loads() the array responses from getData to create and return populated objects.
getObjects() requires ID constraints as an input, either in the form of a list or in the form of a subquery, which are then passed to getData(). I wanted to make it possible to pass in no ID constraints to get all objects.
The problem is that only the models know about their tables. getObjects() is implemented at a higher level and so it doesn't know what to pass getData(), unless there was a universal "return everything" clause for IN.
There are other solutions. I can modify the API to require getData to accept a special parameter and return everything, or I can implement a static getAll[ModelName]s() method at the model level which calls:
static function getAllModelObjects() {
return getObjects("select [model].id from [model]");
}
This is reasonable and may fit the architecture anyway, but I was curious so I thought I would ask!
Works on SQL Server:
SELECT * FROM table_a WHERE table_a.id IN (table_a.id)
Okay, I hate saying no so I had to come up with another solution for you.
Since mysql is opensource you can get the source and incorporate a new feature that understands the infinity symbol. Then you just need to get the mysql community to buy into the usefulness of this feature (steer the conversation away from security as much as possible in your attempts to do so), and then get your company to upgrade their dbms to the new version once this feature has been implemented.
Problem solved.
The answer is simple. The workaround is to add some criteria like these:
# to query on a number column
AND (-1 in (-1) OR sample_table.sample_column in (-1))
# or to query on a string column
AND ('%' in ('%') OR sample_table.sample_column in ('%'))
Therefore, in your example, two following queries should return the same result as soon as you pass -1 as the parameter value.
SELECT * FROM table_a;
SELECT * FROM table_a WHERE (-1 in (-1) OR table_a.id in (-1));
And whenever you want to filter something out, you can pass it as a parameter. For example, in the following query, the records with id of 1, 2 and 6 are filtered.
SELECT * FROM table_a WHERE (-1 in (1, 2, 6) OR table_a.id in (1, 2, 6));
In this case, we have a default value like -1 or % and we have a parameter that can be anything. If the parameter is the default value, nothing is filtered.
I suggest % character as the default value if you are querying over a text column or -1 if you are querying over the PK of the table. But it totally depends to you to substitute % or -1 with any reserved character or number that you decide on.
similiar to #brandonmoore:
select * from table_a where table_a.id not in ('0')
How about:
select * from table_a where table_a.id not ine ('somevaluethatwouldneverpossiblyexistintable_a.id')
EDIT:
As much as I would like to continue thinking of a way to solve your problem, I know there isn't a way to so I figure I'll go ahead and be the first person to tell you so I can at least get credit for the answer. It's truly a bittersweet victory though :/
If you provide more info though maybe I or someone else can help you think of another workaround.

How to change update statement before executing: Linq2Sql Classes

I have implemented Change Tracking (http://msdn.microsoft.com/en-us/library/cc280462.aspx) on some tables I am using Linq2Sql on.
As a part of this I need to add the below SQL to the start of the update statements generated.
DECLARE #originator_id varbinary(128);
SET #originator_id = CAST('SyncService' AS varbinary(128));
WITH CHANGE_TRACKING_CONTEXT (#originator_id)
....generated statements....
....
....
I know I can create stored procedures and manually map the fiels but I would like to avoid this if possible.
does anyone know a way to override and edit the SQL on SubmitChanges()?
You can override the Update method by implementing partial classes on your datacontext that LINQ to SQL will call instead. Just give it the signature:
partial void UpdateClassName(ClassName instance)
You can also pass through to what it would normally do using:
ExecuteDynamicInsert(instance);
Unfortunately there is no mechanism just to get the intended SQL back for inserts/update/deletes (you can get SELECT statements with GetCommand on the DataContext)

Can LINQToSQL be used with sproc that uses sp_executeSQL? If not, how do you handle?

LINQToSQL doesn't like my sproc. It says that the sproc has return type "none", which is probably, because I am using an sp_ExecuteSQL statement to produce the results.
The SQL Server Sproc Code
I have a stored procedure similar to the following
CREATE PROCEDURE Foo
#BarName varchar(50)
AS
BEGIN
DECLARE #SQL NVARCHAR(1024)
SET #SQL = 'SELECT tbFoo.FooID, tbFoo.Name FROM tbFOO ';
IF #BarName IS NOT NULL
BEGIN;
SET #SQL = #SQL
+ ' JOIN tbBar '
+ ' ON tbFoo.FooID = tbBar.FooID '
+ ' AND tbBar.BarName = ''' + #BarName + ''''
END;
EXEC sp_executeSQL #SQL
END
Returns
This sproc returns a set of FooID | FooName tuples.
12345 | Tango
98765 | Cash
Goal
This stored procedure is going to be used to return search results on a search page. This is a fairly common search pattern. I want to find Foos that meet a condition, however the condition is being applied to a separate table. I could have chosen to write this query directly without using sp_executeSQL, however what this approach does is to create SQL that will only include the tables actually being queried. In a real world scenario, I could have 12 joins, instead of 1 and this methodology allows me to only string together joins that will actually be used as criteria.
The problem
LINQ to SQL doesn't like it. It says that this query returns type "none" and doesn't allow me to specify a return type. I'm not sure if other ORMs, such as NHibernate, Entity Framework or LLBLGen would be able to handle this or not. LINQToSQL has worked fine thus far on the project and I'm 95% finished with the project and don't want to use a different ORM for a single method. It might be something to refactor if I make further changes, but for now, I'm not ready to do a switch to a different ORM just for this.
I really want to find a way to make this work in LinqToSql! I'm not sure if it can or not. I haven't found any official documentation on this apparent limitation.
Alternatives that I'm considering so far
I've come up with a few alternatives so far. I don't like any of them so I really hope that someone has a good "hack" to solve this problem. These are what I've got thus far:
Re-write the sproc. Get rid of sp_executeSQL. Do LEFT JOINs on all the tables.
Use ADO.Net and hand roll the method.
Don't use a sproc, but instead try to do all the filtering in LINQ.
You can use Linq2SQL to call your sproc, but the Entity modeler probably can't generate the call wrapper for you because it can't figure out what the sproc is returning, so you'll have to create the call wrapper yourself.
To do this create an Entity Model "non-designer" module with a partial class definition matching your Entity Model data Context (and Entities if necessary) and define the call wrapper like this.
namespace bar.Context
{
public partial class EntityModelDataContext
{
/// <summary>
/// LINQ to SQL class mapper for Foo StoredProcedure
/// </summary>
/// <remarks>
/// This one is too tough for the LINQ to SQL modeler tool to auto-generate
/// </remarks>
/// <returns></returns>
[Function(Name = "dbo.Foo")]
[ResultType(typeof(bar.Entity.tbFoo))]
public ISingleresult<bar.Entity.tbFoo> Foo([Parameter(Name = "BarName", DbType = "varchar")] string barname)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), barname);
return ((ISingleResult<bar.Entity.tbFoo>)(result.ReturnValue));
}
}
}
namespace bar.Entity
{
/// <summary>
/// Data Modeler couldn't figure out how to generate this from the sproc
/// hopefully your entity model generated this and you don't need to replicate it
/// </summary>
[Table(Name = "dbo.tbFoo")]
public partial class tbFoo {
....
}
}
Is there some reason you can't handle the query using the object properties in Linq?
I'd need to see the table schema, including the foreign key linkage, in order to give a good example, but it'd be something like:
dbContextObject.Foos.Where(foo=> foo.Bars.Where(bar=> bar.BarName == searchString))
You'd then have an IEnumerable of Foos matching the condition and you could do whatever you wanted with.
If searchString is null, then you'd just use dbContextObject.Foos.All()