How to work out which wire goes where when replacing light fixture
Familiarise yourself with typical ways of wiring lights in your country and locale. There are often one standard way of doing things but there are very often other ways of wiring things up that you need to be aware of in case you encounter them. Search related questions here for diagrams.
If you dont have a good tool go and spend $10 on something that might save your life and which will help you work this out.
Familiarise yourself with safe methods of working with electricity. You probably want someone else around to call an ambulance if you get electrocuted. Make sure anyone else in the house knows you are working on the circuit so that they don't do something silly like turning a breaker back on while you are working on a circuit. Make sure you know how to test your tester each time you perform a test.


To work out which wire goes where, apart from matching the wiring colours to known standards, I would 


With the light on, verify that you can use your tester to identify at least one live/hot wire. If you can't do this, call an electrician.
Disconnect the circuit using the breaker in the main panel.
Test all the wires in the ceiling box are dead.
Identify the earth wires


bare uninsulated or with green or green/yellow insulation.
often connected to metal box/casing/etc in ceiling or elsewhere

Disconnect all the wire nuts except the ground/earth wires.
Draw a diagram of all the wires showing colours of insulation, presence of coloured tape or other markings on wires.
Make sure no wires are touching.
Switch the breaker back on.
Identify an earth/ground wire, use that for testing. If not present, pick a neutral wire (by insulation colour)
Test every other wire to see which ones are live with respect to your chosen reference wire (ground or neutral). repeat test with other reference wires. write down results carefully and clearly.
Repeat tests with light switch on other position.
Work out what must be the permanent live, what must be the switched live.
Use knowledge from 1 above and test results to deduce correct connections.
Turn off breaker
Check wires are all dead. Check tester still works on live wire elsewhere.
Make connections
Turn breaker on and check lights and outlets work as expected.
Call electrician if needed.




Diagrams


US example
US example


Ceiling wires


US example
US example
US example (horrible)
UK example 1 (old&amp;new colours)
UK example 2 (old colours)
DE example
AU example


Switch wires


US example
UK example