Are animals programmed to escape their pens?
Yes. There is a "Claustrophobic" aspect that derives from how the passive mob ai move in minecraft. Every game tick, passive mobs choose a block within a diameter of 16 blocks to move to.(when you hold wheat, your location is used instead.) If there is not block there, or there is no air above it, they abandon that path, and do not move. This happens most of the time.
If the block they chose is valid however, they will try to move there. If their pathing algorithm cannot find a way to get there, it will keep trying to find one every game tick until it finally gives up and chooses another block, how long it takes to give up depends on game version and type of mob.
What this means is that when a mob is in a pen, if they choose to move inside the pen they just move. If they choose to move outside the pen, (about half the time if they are near the wall, or more if the pen is small) they wait for you to make an opening, then walk towards it. Depending on the proportion of inside to outside this can be more then half the animals at one time.
I have exploited this behavior to create an automated slaughterhouse with pistons, tripwires and fire that turns cows into meals automatically.
If you just want a way to stop them from escaping, you can use trapdoors as doors to your pen, as regardless of whether the trapdoors are up or down mobs see them as a solid block.