Subdomain database configuration picking up root domain config
As long as you have the more specific one at the top of your array like you do, it should work.

It looks like your using some custom (non-stock) Craft config logic judging from the $customDbConfig variable.

What happens if you echo $_SERVER['SERVER_NAME']; from the test1.foo.com domain?

If it's an exact match and it is still not selecting the right database, then I'd suspect your custom logic.

Strip all of that out to just Craft's default multi-environment config and see if it works that way.